Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cbind items from multiple lists recursively

Tags:

join

list

r

cbind

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.

like image 641
thelatemail Avatar asked Mar 01 '13 00:03

thelatemail


Video Answer


3 Answers

Use Reduce and Map (Map being a simple wrapper for mapply(..., SIMPLIFY = FALSE)

Reduce(function(x,y) Map(cbind, x, y),list(one, two,three))

When using Reduce or most of the functional programming base functions in R, you usually can't pass arguments in ... so you normally need to write a small anonymous function to do what you want.

like image 151
mnel Avatar answered Oct 16 '22 18:10

mnel


Or like this:

mapply(cbind, one, two, three)

Or like this:

mylist <- list(one, two, three)
do.call(mapply, c(cbind, mylist))
like image 38
flodel Avatar answered Oct 16 '22 19:10

flodel


sep.list <- unlist(list(one, two, three), recursive = FALSE)
lapply(split(sep.list, names(sep.list)), do.call, what = cbind)
like image 2
adibender Avatar answered Oct 16 '22 18:10

adibender