tidyverse / purrr

A functional programming toolkit for R
https://purrr.tidyverse.org/
Other
1.28k stars 272 forks source link

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

Closed werkstattcodes closed 4 months ago

werkstattcodes commented 10 months ago

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.

hadley commented 4 months ago

Yeah, agreed. I'm going to merge this with #1096 since I think it'll be easiest to fix both at once.