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

     [,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

Leave a Reply