我有一个可行的解决方案,但我正在寻找一个更干净、更可读的解决方案,它可能会利用一些较新的dplyr窗口函数.
使用mtcars数据集,如果我想查看第25、50、75百分位,以及每加仑英里数("mpg")的平均值和计数(按气缸数("cyl"),我使用以下代码:
library(dplyr)
library(tidyr)
# load data
data("mtcars")
# Percentiles used in calculation
p <- c(.25,.5,.75)
# old dplyr solution
mtcars %>% group_by(cyl) %>%
do(data.frame(p=p, stats=quantile(.$mpg, probs=p),
n = length(.$mpg), avg = mean(.$mpg))) %>%
spread(p, stats) %>%
select(1, 4:6, 3, 2)
# note: the select and spread statements are just to get the data into
# the format in which I'd like to see it, but are not critical
有没有一种方法可以让dplyr使用一些摘要函数(n_tiles、percent_rank等)更清晰地实现这一点?我所说的干净,是指没有"做"的陈述.
非常感谢.