Mayou Mayou - 3 months ago 13
R Question

Combining elements of list of lists by index

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!

Answer

You can do:

do.call(Map, c(c, lst))
Comments