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

How to unnest lists in a list into a list?

Consider the minimal working example

raw_list <- list(1, 2)
process_list <- function(item) {
    if(item == 1) {
        return(list(c(1, 1), c(2, 2)))
    }
    else {
        return(c(3, 3))
    }
}

processed_list <- lapply(raw_list, process_list)

df <- do.call(rbind, processed_list)

processed_list is

[[1]]
[[1]][[1]]
[1] 1 1

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


[[2]]
[1] 3 3

and df is

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

     [,1]      [,2]     
[1,] numeric,2 numeric,2
[2,] 3         3 

How do I unnest processed_list to get

[[1]]
[1] 1 1

[[2]]
[1] 2 2

[[3]]
[1] 3 3

or how do I unnest df to get

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

>Solution :

I think you should also list the c(3, 3) in the function, then unlist non-recursively.

raw_list <- list(1, 2)

process_list <- function(item) {
  if(item == 1) {
    return(list(c(1, 1), c(2, 2)))
  }
  else {
    return(list(c(3, 3)))
  }
}

processed_list <- lapply(raw_list, process_list)

unlist(processed_list, recursive=FALSE)
# [[1]]
# [1] 1 1
# 
# [[2]]
# [1] 2 2
# 
# [[3]]
# [1] 3 3
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