本文介绍了在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中将列表列表合并为一个列表
发布评论