Let's say I have a list with named elements. The elements are tibbles. I would like to convert the list into one single tibble.
purrr's list_rbind
works, with the critical shortcoming (at least for my purpose) that it drops the
element which is a 0-row tibble (although it is a named element).
library(tidyverse)
li <- list("a"=tibble(x=1), "b"=tibble(x=2), "c"=tibble(x=NULL))
li
#> $a
#> # A tibble: 1 × 1
#> x
#> <dbl>
#> 1 1
#>
#> $b
#> # A tibble: 1 × 1
#> x
#> <dbl>
#> 1 2
#>
#> $c
#> # A tibble: 0 × 0
li %>% purrr::list_rbind(., names_to="element_names")
#> # A tibble: 2 × 2
#> element_names x
#> <chr> <dbl>
#> 1 a 1
#> 2 b 2
The outcome I am looking for would be
#> element_names x
#> <chr> <dbl>
#> 1 a 1
#> 2 b 2
#> 3 c NA (or NULL?)
Any help? Many thanks.
You can use enframe()
and unnest()
:
library(tibble)
library(tidyr)
enframe(li, name = "element_names") |>
unnest(value, keep_empty = TRUE)
# A tibble: 3 × 2
element_names x
<chr> <dbl>
1 a 1
2 b 2
3 c NA