Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert a List of Character Vectors in R

Tags:

r

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:

like image 903
cannin Avatar asked Mar 06 '16 12:03

cannin


People also ask

How do I flip a list in R?

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.

How do I reverse the order of an array in R?

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.


1 Answers

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))
like image 84
akrun Avatar answered Sep 29 '22 11:09

akrun