假设我有几个具有相同结构的列表,例如:
list1 <- list(foo="abc", bar=1:3)
list2 <- list(foo="def", bar=5:7)
所以,它们的内容如下所示:
> list1
$foo
[1] "abc"
$bar
[1] 1 2 3
> list2
$foo
[1] "def"
$bar
[1] 4 5 6
我想将它们组合起来,结果应该如下所示:
> list3
$foo
[1] "abc" "def"
$bar
[1] 1 2 3 4 5 6
最好的方法是什么?我尝试了 c(list1, list2)
、list(list1, list2)
等的一些组合。或者唯一的解决方案是编写我自己的函数来扫描所有成员两个列表的名称并匹配它们的名称吗?
最佳答案
你可以这样做:
Map(c, list1, list2)
它也适用于两个以上的列表:
Map(c, list1, list2, list3, list4, list5)
如果您的所有列表都位于更高级别的列表中,例如:
list_of_lists = list(list1, list2, list3, list4, list5)
那么你可以这样做:
do.call(Map, c(f = c, list_of_lists))
关于r - 按成员姓名加入列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27096298/