What is an efficient way from inverting a list of character vectors as shown below?
lov <- list(v1=c("a", "b"), v2=c("a", "c"), v3=c("a"))
list(a=c("v1", "v2", "v3"), b=c("v1"), c=c("v2"))
Similar to Revert list structure, but involving vectors:
R – Reverse a List. To reverse a list in R programming, call rev() function and pass given list as argument to it. rev() function returns returns a new list with the contents of given list in reversed order.
The rev() method in R is used to return the reversed order of the R object, be it dataframe or a vector. It computes the reverse columns by default. The resultant dataframe returns the last column first followed by the previous columns. The ordering of the rows remains unmodified.
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 unlist
ing the 'lov'.
split(rep(names(lov), lengths(lov)), unlist(lov))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With