5

给定三个(或n列表):

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

为了得到这个结果,cbind在列表中查找每个列表项的更有效方法是什么?n

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"

n当它23但很快会变得非常复杂时,这可以正常工作。有没有更有效的变化?我在 SO 上看到过类似的问题,但一直在努力适应它们。

4

3 回答 3

7

使用Reduceand Map(Map作为一个简单的包装器mapply(..., SIMPLIFY = FALSE)

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

在 R 中使用Reduce或大多数函数式编程基函数时,您通常无法传入参数,...因此您通常需要编写一个小的匿名函数来执行您想要的操作。

于 2013-03-01T00:45:40.337 回答
6

或者像这样:

mapply(cbind, one, two, three)

或者像这样:

mylist <- list(one, two, three)
do.call(mapply, c(cbind, mylist))
于 2013-03-01T00:53:03.343 回答
2
sep.list <- unlist(list(one, two, three), recursive = FALSE)
lapply(split(sep.list, names(sep.list)), do.call, what = cbind)
于 2013-03-01T00:55:49.783 回答