list 将元素添加到 R 中的列表(在嵌套列表中)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14054120/
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
Adding elements to a list in R (in nested lists)
提问by HymanStinger
I have a nested list l3 as:
我有一个嵌套列表 l3 为:
l1<- as.list(c(1,2,3,4,5))
l1
l2<- as.list(c(6,7,8,9,10))
l2
l3<- list(l1,l2)
l3
l3 shows as:
l3 显示为:
> l3
[[1]]
[[1]][[1]]
[1] 1
[[1]][[2]]
[1] 2
[[1]][[3]]
[1] 3
[[1]][[4]]
[1] 4
[[1]][[5]]
[1] 5
[[2]]
[[2]][[1]]
[1] 6
[[2]][[2]]
[1] 7
[[2]][[3]]
[1] 8
[[2]][[4]]
[1] 9
[[2]][[5]]
[1] 10
I need to add a third list l4 to l3 such that l3 becomes:
我需要将第三个列表 l4 添加到 l3,以便 l3 变为:
[[1]][[1]]
[1] 1
to
[[2]][[5]]
[1] 10
[[3]][[1]]
[1] 30
[[3]][[2]]
[1] 32
[[3]][[3]]
[1] 33
[[3]][[4]]
[1] 34
[[3]][[5]]
[1] 35
where l4 was:
其中 l4 是:
l4<- as.list(c(31,32,33,34,35))
how do I accomplish it? I've tried (c)
, list
, even explicitly put the arguments and got an out of bounds error
. What can I use to get this done?
我该如何实现?我试过(c)
, list
, 甚至明确地提出了论点并得到了一个out of bounds error
. 我可以用什么来完成这项工作?
回答by Sven Hohenstein
It works with append
and list
:
它适用于append
和list
:
append(l3, list(l4))
The result:
结果:
> str(append(l3, list(l4)))
List of 3
$ :List of 5
..$ : num 1
..$ : num 2
..$ : num 3
..$ : num 4
..$ : num 5
$ :List of 5
..$ : num 6
..$ : num 7
..$ : num 8
..$ : num 9
..$ : num 10
$ :List of 5
..$ : num 31
..$ : num 32
..$ : num 33
..$ : num 34
..$ : num 35
回答by agstudy
I don't know what you have tried with c
, but it works
我不知道你试过什么c
,但它有效
c(l3,list(l4))
PS: append
is a wrapper of c
to insert in a specific index, (see after argument )
PS:append
是c
插入特定索引的包装器,(见参数后)