基于四分位数(任何百分位数)的计算

Calculations based on Quartiles (Any percentile)

例如

summary(mtcars$mpg)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  10.40   15.43   19.20   20.09   22.80   33.90 

我需要根据变量“mpg”计算每个四分位数的“disp”变量的均值和标准差。

cut中指定breaks和'mpg'的quantile,将其用作summarisemean的分组变量sd 共 'disp'

library(dplyr)
mtcars %>%
     group_by(mpg_grp = cut(mpg, breaks = c(-Inf, quantile(mpg), Inf))) %>% 
     summarise(disp_mean = mean(disp), disp_sd = sd(disp))