Roccer
Roccer

Reputation: 919

How to flatten a list with tibbles and tibbles within lists to have all tibbles on the same level?

I have a list where the list elements are tibbles or lists that contain multiple tibbles. I would like to get a list where all the tibbles are on the same level.

How would I do that?

library(tibble)

tib_1 <- tibble(a = 1:4, b = LETTERS[1:4])
tib_2 <- tibble(c = 1:4, d = LETTERS[1:4])
tib_3 <- tibble(e = 1:4, f = LETTERS[1:4])
tib_4 <- tibble(g = 1:4, h = LETTERS[1:4])

my_list <- list(tib_1, tib_2, list(tib_3, tib_4))

desired_list <- list(tib_1, tib_2, tib_3, tib_4)

Upvotes: 1

Views: 375

Answers (1)

akrun
akrun

Reputation: 887118

We can just use flatten

library(rlang)
out <- flatten(my_list)

-checking

identical(desired_list, out)
#[1] TRUE

Upvotes: 2

Related Questions