Search code examples
rlistjoincbind

cbind items from multiple lists recursively


Given three (or n lists):

one   <- list(a=1:2,b="one")
two   <- list(a=2:3,b="two")
three <- list(a=3:4,b="three")

What would be a more efficient way of cbindind each list item across the n lists, to get this result?

mapply(cbind,mapply(cbind,one,two,SIMPLIFY=FALSE),three,SIMPLIFY=FALSE)

$a
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    2    3    4

$b
     [,1]  [,2]  [,3]   
[1,] "one" "two" "three"

This works okay when n is 2 or 3 but is quickly going to become ludicrously complex. Is there a more efficient variation on this? I have seen similar questions on S.O. but have struggled to adapt them.


Solution

  • Or like this:

    mapply(cbind, one, two, three)
    

    Or like this:

    mylist <- list(one, two, three)
    do.call(mapply, c(cbind, mylist))