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 cbind
ind 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.
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.
Or like this:
mapply(cbind, one, two, three)
Or like this:
mylist <- list(one, two, three)
do.call(mapply, c(cbind, mylist))
sep.list <- unlist(list(one, two, three), recursive = FALSE)
lapply(split(sep.list, names(sep.list)), do.call, what = cbind)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With