Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining elements of list of lists by index

Tags:

list

r

Consider the following list of lists:

lst = list(list(c(1,2), c(3,4)),list(c(5,6), c(7,8)),list(c(9,10), c(11,12)))

The list lst contains three lists, each list containing two vectors as elements. I would like to combine the elements of the underlying lists by index. In other words, I would like to merge vector 1 from list 1 with that of list 2 and list 3, and vector 2 from list 1 with that of list 2 and list 3, etc...

This is the result I am looking to achieve:

res = list(c(1,2,5,6,9,10), c(3,4,7,8,11,12))

I know that this can be achieved as follows in case of two separate lists:

mapply(c, lst1, lst2)

However, I am not sure how to replicate the same logic using a list of lists.

Any efficient way to achieve that? Please keep in mind that in reality, lst is a list of 5000 lists, and each underlying list contains a large number of vectors.

Thanks!

like image 326
Mayou Avatar asked Oct 21 '13 17:10

Mayou


3 Answers

You can do:

do.call(Map, c(c, lst))
like image 65
flodel Avatar answered Oct 12 '22 01:10

flodel


You're on the right track:

do.call(function(...) mapply(c,...,SIMPLIFY = FALSE),args = lst)
[[1]]
[1]  1  2  5  6  9 10

[[2]]
[1]  3  4  7  8 11 12
like image 43
joran Avatar answered Oct 12 '22 02:10

joran


I was looking for something along the lines of the OP's question... but with a list of data frames instead of vectors. In that case, slightly modifying @joran's answer above gives the desired result. Consider:

mylist <- 
  lapply(1:2, function(y){
    df1 <- data.frame(a=y, b=y^2, c=y^3)
    df2 <- data.frame(d=y, e=y+1)
    return(list(df1=df1, df2=df2))
    }) 

You can then re-combine the sub-list elements into separate data frames based on their common indexes:

mylist2 <- do.call(function(...) Map("rbind", ...), mylist)
like image 35
Grant Avatar answered Oct 12 '22 02:10

Grant