我有一个可行的解决方案,但正在寻找一种更加清晰、易读,可能利用一些较新的dplyr窗口函数的解决方案。
使用mtcars数据集,如果我想查看每个气缸数("cyl")对应的平均数和数量以及每加仑英里数("mpg")的第25,50,75百分位数,则使用以下代码:
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等)来完成这个操作?通过“干净”我指的是不使用“do”语句。
谢谢