The average value of 10% of the values ββusing the R base:
x = c(1:100,NA) mean(x[x>=quantile(x, 0.9, na.rm=TRUE)], na.rm=TRUE)
The average value is 10% of the values, grouping the variable:
With dplyr
library(dplyr) dat %>% group_by(group) %>% summarise(meanTop10pct = mean(x[x>=quantile(x, 0.9)]))
group meanTop10pct (fctr) (dbl) 1 A 29.0 2 B 59.0 3 C 98.5
With data.table
library(data.table) setDT(dat)[, list(meanTop10pct = mean(x[x>=quantile(x, 0.9)])), by=group]
group meanTop10pct 1: A 29.0 2: B 59.0 3: C 98.5
source share