How to handle lack of names with unnest_wider()

Hi all,

Sometimes (or often) functions don't name outputs. A simple toy example is range():

library(tidyverse)
iris %>%
  group_by(Species) %>%
  summarise(range = list(range(Petal.Length))) %>%
  unnest_wider(range)
#[some messages]
#> # A tibble: 3 x 3
#>   Species     ...1  ...2
#>   <fct>      <dbl> <dbl>
#> 1 setosa       1     1.9
#> 2 versicolor   3     5.1
#> 3 virginica    4.5   6.9

Notice the column names (or lack off). I would like to solve that, ideally before or during the call to unnest_wider() and not as a post-hoc patch (i.e. not by renaming unnested columns) and not be redefining range (it would kill the whole point).

Unless I am mistaken, there don't seem to be an argument for defining names on the fly in unnest_wider(). (My guess is that #tidyr developers want to give an incentive for users to name things properly, which makes sense but which is not always easy.)

I am also not aware of how to name things inside a call to summarise() or list().

So unless, I missed something, my question becomes: what is the best way to name the elements of the vectors within a (column) list ?(for the particular case of a list containing elements of the same length)

Out of many attempts, I tried:

library(tidyverse)
iris %>%
  group_by(Species) %>%
  summarise(range = list(range(Petal.Length))) %>%
  pull(range) %>%
  walk(~ names(.x) <- c("min", "max"))
#> Error in ~names(.x) <- c("min", "max"): object '.x' not found

I am not surprised it does not work and it is not very elegant, but it is interesting that the error message is unexpected (at least to me)...

Any tidy solution would be great, but if simple base R functions exist for that too, I would be interested to know.

Apologies if I missed the obvious... (a little tired).

Best to all,

Alex

Why don't you just name the outputs beforehand?

library(tidyverse)

iris %>%
    group_by(Species) %>%
    summarise(range = list(set_names(range(Petal.Length),
                                     c("min", "max")
                                     )
                           )
              ) %>% 
    unnest_wider(range)
#> # A tibble: 3 x 3
#>   Species      min   max
#>   <fct>      <dbl> <dbl>
#> 1 setosa       1     1.9
#> 2 versicolor   3     5.1
#> 3 virginica    4.5   6.9
3 Likes

Indeed... Should have thought of that. Thanks!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.