7

What is an efficient way from inverting a list of character vectors as shown below?

Input

lov <- list(v1=c("a", "b"), v2=c("a", "c"), v3=c("a"))

Expected

list(a=c("v1", "v2", "v3"), b=c("v1"), c=c("v2"))

Similar to Revert list structure, but involving vectors:

Community
  • 1
  • 1
cannin
  • 2,735
  • 2
  • 25
  • 32

1 Answers1

11

We can either convert the list to a data.frame (using stack or melt from library(reshape2)) and then split the 'ind' column by the 'values' in 'd1'.

d1 <- stack(lov)
split(as.character(d1$ind), d1$values)

Or if the above method is slow, we can replicate (rep) the names of 'lov' by the length of each list element (lengths gives a vector output of the length of each element) and split it by unlisting the 'lov'.

split(rep(names(lov), lengths(lov)), unlist(lov))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • The second one is preferrable, since it does not involve added packages – cannin Mar 06 '16 at 13:10
  • 4
    @cannin The first one also doesn't need any packages. I was referring to `melt` which comes from `reshape2`. Otherwise, `stack` is a `base R` function. – akrun Mar 06 '16 at 13:11