cliu
cliu

Reputation: 965

Unlist a sublist and combine their elements under the same list

I have a list of lists problem where I want to just unlist the bottom-level list and then combine all the elements in the same list. Here is the example:

alllist <- list(list(5,c(1,2)),list(3,c(4,5))) #A list of two sublists
alllist
[[1]]
[[1]][[1]]
[1] 5

[[1]][[2]]
[1] 1 2


[[2]]
[[2]][[1]]
[1] 3

[[2]][[2]]
[1] 4 5

#Unlist will unlist all levels
unlist(alllist, recursive = FALSE)
[[1]]
[1] 5

[[2]]
[1] 1 2

[[3]]
[1] 3

[[4]]
[1] 4 5
#But I want to keep the top level such that the result would be:
[1]
5 1 2

[2]
3 4 5
#I would also like to keep the order of the elements from the sublist while unlisting them

Upvotes: 1

Views: 219

Answers (1)

akrun
akrun

Reputation: 887981

We can use lapply to loop over the list and unlist

lapply(alllist, unlist)

-output

#[[1]]
#[1] 5 1 2

#[[2]]
#[1] 3 4 5

Upvotes: 2

Related Questions