Welcome to OStack Knowledge Sharing 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 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...