Home > OS >  Unlist LAST level of a list in R
Unlist LAST level of a list in R

Time:12-03

I have a list of list like ll:

ll <- list(a = list(data.frame(c = 1, d = 2), data.frame(h = 3, j = 4)), b = list(data.frame(c = 5, d = 6), data.frame(h = 7, j = 9)))

I want to unnest/unlist the last level of the structure (the interior list). Note that every list contains the same structure. I want to obtain lj:

lj <- list(a = (data.frame(c = 1, d = 2, h = 3, j = 4)), b = data.frame(c = 5, d = 6, h = 7, j = 9))

I have tried the following code without any success:

lj_not_success <- unlist(ll, recursive = F)

However, this code unlists the FIRST level, not the LAST one.

Any clue?

CodePudding user response:

We may need to cbind the inner list elements instead of unlisting as the expected output is a also a list of data.frames

ll_new <- lapply(ll, function(x) do.call(cbind, x))

-checking

> identical(lj, ll_new)
[1] TRUE
  • Related