list 如何在R中组合两个列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36665492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to combine two lists in R
提问by Rohit Singh
I have two lists:
我有两个清单:
l1 = list(2, 3)
l2 = list(4)
I want a third list:
我想要第三个列表:
list(2, 3, 4).
How can I do it in simple way. Although I can do it in for loop, but I am expecting a one liner answer, or maybe an in-built method.
我怎样才能以简单的方式做到这一点。虽然我可以在 for 循环中做到这一点,但我期待一个单一的答案,或者可能是一个内置的方法。
Actually, I have a list:list(list(2, 3), list(2, 4), list(3, 5), list(3, 7), list(5, 6), list(5, 7), list(6, 7)).
After computing on list(2, 3)
and list(2, 4)
, I want list(2, 3, 4)
.
实际上,我有一个列表:list(list(2, 3), list(2, 4), list(3, 5), list(3, 7), list(5, 6), list(5, 7), list(6, 7)).
在计算list(2, 3)
和之后list(2, 4)
,我想要list(2, 3, 4)
.
回答by Vincent Bonhomme
c
can be used on lists (and not only on vectors):
c
可用于列表(不仅限于向量):
# you have
l1 = list(2, 3)
l2 = list(4)
# you want
list(2, 3, 4)
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
# you can do
c(l1, l2)
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
If you have a list of lists, you can do it (perhaps) more comfortably with do.call
, eg:
如果您有一个列表列表,您可以(也许)更轻松地使用do.call
,例如:
do.call(c, list(l1, l2))
回答by akrun
We can use append
我们可以用 append
append(l1, l2)
It also has arguments to insert element at a particular location.
它还具有在特定位置插入元素的参数。
回答by John Proestakes
I was looking to do the same thing, but to preserve the list as a just an array of strings so I wrote a new code, which from what I've been reading may not be the most efficient but worked for what i needed to do:
我想做同样的事情,但为了将列表保留为一个字符串数组,所以我编写了一个新代码,从我所阅读的内容来看,它可能不是最有效的,但适用于我需要做的事情:
combineListsAsOne <-function(list1, list2){
n <- c()
for(x in list1){
n<-c(n, x)
}
for(y in list2){
n<-c(n, y)
}
return(n)
}
It just creates a new list and adds items from two supplied lists to create one.
它只是创建一个新列表并从两个提供的列表中添加项目以创建一个。