1

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?

vog
  • 770
  • 5
  • 11

1 Answers1

1

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
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Is there a way to use your code with "bind_rows" to include the name/value of each list as a variable? The code will work in this fashion ```bind_rows(df, .id = 'grp')``` – vog Dec 03 '21 at 10:06
  • @vog did you meant `bind_cols` as in the present context i.e. `purrr::map(ll, bind_cols)` or if it is bind_rows, `purrr::map(ll, ~ bind_rows(.x, .id = 'grp'))` – akrun Dec 03 '21 at 16:36
  • 1
    Thank you @Akrun ! – vog Dec 03 '21 at 17:07