Naming columns from a hoisted vector after unnest_wider

804 views Asked by At

Playing around with some of the new functionality of tidyr 1.0 and I've come across a bit of a head scratcher.

I've used boxplot.stats to get a vector of boxplot values I'd like to use to plot. I've done this successfully but am convinced there is a better way to name the columns of the newly unnested vector.

Here is current setup:

library(tidyverse)

iris %>%
  nest(data = -Species) %>%
  mutate(box = map(data, ~ boxplot.stats(.x[["Sepal.Length"]]))) %>%
  hoist(box, stats = "stats") %>%
  unnest_wider(stats) %>%
  rename_at(vars(contains("...")), ~ c("min", "lwr", "med", "upr", "max")) 
#> New names:
#> * `` -> ...1
#> * `` -> ...2
#> * `` -> ...3
#> * `` -> ...4
#> * `` -> ...5
#> New names:
#> * `` -> ...1
#> * `` -> ...2
#> * `` -> ...3
#> * `` -> ...4
#> * `` -> ...5
#> New names:
#> * `` -> ...1
#> * `` -> ...2
#> * `` -> ...3
#> * `` -> ...4
#> * `` -> ...5
#> # A tibble: 3 x 8
#>   Species              data   min   lwr   med   upr   max box             
#>   <fct>      <list<df[,4]>> <dbl> <dbl> <dbl> <dbl> <dbl> <list>          
#> 1 setosa           [50 x 4]   4.3   4.8   5     5.2   5.8 <named list [3]>
#> 2 versicolor       [50 x 4]   4.9   5.6   5.9   6.3   7   <named list [3]>
#> 3 virginica        [50 x 4]   5.6   6.2   6.5   6.9   7.9 <named list [3]>

Created on 2019-10-01 by the reprex package (v0.3.0)

While I get my desired output I am convinced there is a better way to tackle naming the columns.

Thanks for reading!

1

There are 1 answers

0
akrun On BEST ANSWER

We can convert to a list and set the names

library(tidyverse)
iris %>%
   group_by(Species) %>% 
   nest %>%
   mutate(box = map(data, ~ boxplot.stats(.x[["Sepal.Length"]]))) %>% 
   mutate(stats = map(box, ~ .x$stats %>%
                  as.list %>% 
                  set_names(c("min", "lwr", "med", "upr", "max")))) %>% 
   unnest_wider(stats)