简体   繁体   中英

How can I get the average of a percentile in R?

I have a vector of values, and I need to calculate the mean of the 90% worst values in that vector. I came up with the following (procedural) function:

percentile_worst <- function(d, p = 0.9) {
  quant = quantile(d, p)
  worst = c()
  for (t in seq(1, length(d))) {
    if (d[t] <= quant) {
      worst = c(worst, d[t])
    }
  }
  return(mean(worst))
}

Is there any more efficient way to do this?

如果数据在数据框中,则可以进行子设置:

mean(d$foo[d$foo < quantile(d$foo, .9), ])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM