tidyverse / purrr

A functional programming toolkit for R

Home Page:https://purrr.tidyverse.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

FR: list_rbind - keep 0-row tibbles if in named list

werkstattcodes opened this issue · comments

First, once again many thanks for all the wonderful packages you've been contributing.

I was wondering whether an option like keep_empty=T would make sense for list_rbind.

The use case is the following:

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

I am aware that there are several ways to achieve this result (I had a pertaining question on SO here), but think a keep_empty argument would make the entire procedure more elegant and less prone to the unintended loss of rows.

In my mental model it's a bit like with unnest_longer. I see that there is already a somewhat related FR here.

Many thanks.