Home > OS >  How to unnest lists in a list into a list?
How to unnest lists in a list into a list?

Time:06-24

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

CodePudding user response:

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

CodePudding user response:

you could simply use

simple_list <- unlist(processed_list, recursive = FALSE)

and then simply

df <- do.call(rbind, simple_list)

this gives:

[[1]]
[1] 1 1

[[2]]
[1] 2 2

[[3]]
[1] 3

[[4]]
[1] 3

and

     [,1] [,2]
[1,]    1    1
[2,]    2    2
[3,]    3    3
[4,]    3    3
  • Related