I need to calculate boxplot statistics for a data.frame with many, many groups.
What I ideally need is:
library(dplyr)
iris %>%
group_by(Species) %>%
summarise(boxplot=boxplot.stats(Sepal.Length))) # + some kind of magic
# A tibble: 3 x 6
Species lower_whisker lower_hinge median upper_hinge upper_whisker
<fct> <dbl> <dbl> <dbl> <dbl> <dbl>
1 setosa 4.3 4.8 5 5.2 5.8
2 versicolor 4.9 5.6 5.9 6.3 7
3 virginica 5.6 6.2 6.5 6.9 7.9
But so far, I've managed to do a half-purrr mapping thing and cannot unpack it.
boxplot.stats2 <- function(x, ...) {
res <- boxplot.stats(x, ...)
res <- res$stats
names(res) <- c('lower_whisker','lower_hinge','median','upper_hinge','upper_whisker')
#t(as.data.frame(res))
res
}
iris %>%
group_by(Species) %>%
summarise(boxplot=list(boxplot.stats2(Sepal.Length)),
#manual unpacking
lower_whisker = boxplot[[1]]['lower_whisker'],
lower_hinge = boxplot[[1]]['lower_hinge'],
median = boxplot[[1]]['median'],
upper_hinge = boxplot[[1]]['upper_hinge'],
upper_whisker = boxplot[[1]]['upper_whisker']
)
It gives the same result, but I suspect there should be a more elegant solution for it.