unnest_wider() and unnest_longer() improvements

tidyr 1.3.0

tidyr
unnest_longer() and unnest_wider() have received some quality of life and consistency improvements.
Published

January 24, 2023

Install tidyr 1.3.0 with:

pak::pak("cran/tidyr@1.3.0")

unnest_wider() and unnest_longer() improvements

unnest_longer() and unnest_wider() have received some quality of life and consistency improvements.

unnest_wider() now gives a better error when unnesting an unnamed vector:

library(tidyr)

df <- tibble(
  id = 1:2,
  x = list(c("a", "b"), c("d", "e", "f"))
)

df
# A tibble: 2 × 2
     id x        
  <int> <list>   
1     1 <chr [2]>
2     2 <chr [3]>
df |> 
  unnest_wider(x)
Error in `unnest_wider()`:
ℹ In column: `x`.
ℹ In row: 1.
Caused by error:
! Can't unnest elements with missing names.
ℹ Supply `names_sep` to generate automatic names.
df |> 
  unnest_wider(x, names_sep = "_")
# A tibble: 2 × 4
     id x_1   x_2   x_3  
  <int> <chr> <chr> <chr>
1     1 a     b     <NA> 
2     2 d     e     f    

unnest_longer() has gained a keep_empty argument like unnest(), and it now treats NULL and empty vectors the same way:

df <- tibble(
  id = 1:3,
  x = list(NULL, integer(), 1:3)
)

df 
# A tibble: 3 × 2
     id x        
  <int> <list>   
1     1 <NULL>   
2     2 <int [0]>
3     3 <int [3]>
df |> unnest_longer(x)
# A tibble: 3 × 2
     id     x
  <int> <int>
1     3     1
2     3     2
3     3     3
df |> unnest_longer(x, keep_empty = TRUE)
# A tibble: 5 × 2
     id     x
  <int> <int>
1     1    NA
2     2    NA
3     3     1
4     3     2
5     3     3

Learn more