3

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!

tomasu
  • 1,388
  • 9
  • 11
  • If you extract the column 'stats', it is a unnamed vector – akrun Oct 01 '19 at 15:06
  • 1
    You could remove the last line and put this before `unnest_wider`. Not sure if it's much better though `mutate_at('stats', map, setNames, c("min", "lwr", "med", "upr", "max"))`. Another option would be to name the stats element of the list created by boxplot.stats in the original `map` step. – IceCreamToucan Oct 01 '19 at 15:45

1 Answers1

3

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)
akrun
  • 874,273
  • 37
  • 540
  • 662