A slightly different approach using dplyr
:
library(tidyverse)
baseball %>%
group_by(team) %>%
nest() %>%
mutate(
ret = map(data, ~quantile(.$ab, probs = c(0.25, 0.75))),
ret = invoke_map(tibble, ret)
) %>%
unnest(ret)
Here you can specify the needed quantiles in the probs
argument.
The invoke_map
call seems to be necessary, as quantile
does not return a data frame; see this answer.
You can also put that all into a function:
get_quantiles <- function(.data, .var, .probs = c(0.25, 0.75), .group_vars = vars()) {
.var = deparse(substitute(.var))
return(
.data %>%
group_by_at(.group_vars) %>%
nest() %>%
mutate(
ret = map(data, ~quantile(.[[.var]], probs = .probs)),
ret = invoke_map(tibble, ret)
) %>%
unnest(ret, .drop = TRUE)
)
}
mtcars %>% get_quantiles(wt, .group_vars = vars(cyl))
A new approach would be to use group_modify()
from dplyr
. Then you'd call:
baseball %>%
group_by(team) %>%
group_modify(~{
quantile(.x$ab, probs = c(0.25, 0.75)) %>%
tibble::enframe()
}) %>%
spread(name, value)