Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

in r combine a list of lists into one list

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"

I only found this sad way by using a for-loop:

listofvectors <- list()
for (i in 1:length(listoflists))  {listofvectors <- c(listofvectors, listoflists[[i]])}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Or as @d.b mentioned in the comments, unlist with recursive = FALSE can also work

unlist(listoflists, recursive = FALSE)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...