How to calculate the mean of the top 10% in R

Mean of top 10% of values, using base R:

x = c(1:100,NA)
mean(x[x>=quantile(x, 0.9, na.rm=TRUE)], na.rm=TRUE)

Mean of top 10% of values, by grouping variable:

# Fake data
dat = data.frame(x=1:100, group=rep(LETTERS[1:3], c(30,30,40)))

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