Home > Back-end >  Calculations based on Quartiles (Any percentile)
Calculations based on Quartiles (Any percentile)

Time:11-16

For example

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

I need to calculate of mean and standard deviation of "disp" variable of each quartile based on variable "mpg".

CodePudding user response:

Specify the breaks with the quantile of 'mpg' in cut, use that as grouping variable to summarise the mean and sd of '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))
  • Related