Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function to combine multiple lists of lists into a single list of lists?

Suppose we have list l which is a list of lists.

a <- list(c(1,2,3))
b <- list(c(4,5,6), c(7,8,9))
c <- list(c(10,11,12), c(13,14,15), c(16,17,18))

l <- list(a, b, c)

So l is a list of lists, where each of those lists itself contains at least one list.

Question

How can I make a function which can extract all the lowest level lists into a single list of lists?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# Goal
list(c(1,2,3), c(4,5,6), c(7,8,9), c(10,11,12), c(13,14,15), c(16,17,18))

Notes:

  • The example is a minimal reproducible example for which it would be possible to hard-code a solution, but it is important that the solution generalise, since the real problem has tens-of-thousands of lists each containing unknown numbers of lists – so a hard-coded solution definitely won’t scale!

  • I hope to find a solution in base R, if possible.

A few things I’ve tried so far

Some unsuccessful attempts, mostly using sapply() and unlist():

sapply(l, function(x) { unlist(x) })
# [[1]]
# [1] 1 2 3
# 
# [[2]]
# [1] 4 5 6 7 8 9
# 
# [[3]]
# [1] 10 11 12 13 14 15 16 17 18

unlist(a)
# [1] 1 2 3

# unlist() seems to combine the elements of multiple lists into one list (not desired here)..
unlist(b)
# [1] 4 5 6 7 8 9

I thought the recursive = FALSE argument looked promising, but unfortunately I couldn’t get it to do what I wanted either:

unlist(b, recursive = FALSE)
# [1] 4 5 6 7 8 9

>Solution :

Use unlist, non-recursive on your initial list.

unlist(l, recursive=FALSE)
# [[1]]
# [1] 1 2 3
# 
# [[2]]
# [1] 4 5 6
# 
# [[3]]
# [1] 7 8 9
# 
# [[4]]
# [1] 10 11 12
# 
# [[5]]
# [1] 13 14 15
# 
# [[6]]
# [1] 16 17 18
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading