在r中将列表列表合并为一个列表 [英] in r combine a list of lists into one list
本文介绍了在r中将列表列表合并为一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我找不到可以获取子列表的所有条目的列表吗?这是一个简单的示例,列出了一个列表:
I cannot find out can to get a list of all entry of the sublists? Here's a simple example, a list o lists:
listoflists <- list("A"=list(c(1,2,3),c(2,34,2)), "B" = list(c(1,2),c(2,3,2,1)), "C" = list(c("sdf",3,2)))
$A
$A[[1]]
[1] 1 2 3
$A[[2]]
[1] 2 34 2
$B
$B[[1]]
[1] 1 2
$B[[2]]
[1] 2 3 2 1
$C
$C[[1]]
[1] "sdf" "3" "2"
我只是通过使用for循环发现了这种可悲的方式:
I only found this sad way by using a for-loop:
listofvectors <- list()
for (i in 1:length(listoflists)) {listofvectors <- c(listofvectors, listoflists[[i]])}
推荐答案
我们可以在do.call
中使用串联函数(c
)来平整嵌套的list
We can use the concatenate function (c
) within do.call
to flatten the nested list
res <- do.call(c, listoflists)
all.equal(listofvectors, res, check.attributes = FALSE)
#[1] TRUE
或者如评论中提到的@ d.b一样,unlist
和recursive = FALSE
也可以工作
Or as @d.b mentioned in the comments, unlist
with recursive = FALSE
can also work
unlist(listoflists, recursive = FALSE)
这篇关于在r中将列表列表合并为一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文