[英]Finding Mean of Vector, Excluding Quantile Cutoffs in R
我想找到兩個分位數臨界值范圍內的數字向量的均值(提供一種簡單的方法來計算控制異常值的均值)。
示例 :三個參數x
(數字的向量) lower
下限邊界,而upper
則上限。
meanSub <- function(x, lower = 0, upper = 1){ Cutoffs <- quantile(x, probs = c(lower,upper)) x <- subset(x, x >= Cutoffs[1] & x <= Cutoffs[2]) return(mean(x)) }
顯然,有很多海峽前進的方式來做到這一點。 但是,我將此功能應用於許多觀察結果-我很好奇您是否可以提供功能設計或預先存在的程序包的提示,這些提示可以非常快地完成此操作。
您可以使用同樣的方法mean
對於非零值用途trim
的說法。
meanSub_g <- function(x, lower = 0, upper = 1){
Cutoffs <- quantile(x, probs = c(lower,upper))
return(mean(x[x >= Cutoffs[1] & x <= Cutoffs[2]]))
}
meanSub_j <- function(x, lower=0, upper=1){
if(isTRUE(all.equal(lower, 1-upper))) {
return(mean(x, trim=lower))
} else {
n <- length(x)
lo <- floor(n * lower) + 1
hi <- floor(n * upper)
y <- sort.int(x, partial = unique(c(lo, hi)))[lo:hi]
return(mean(y))
}
}
require(microbenchmark)
set.seed(21)
x <- rnorm(1e6)
microbenchmark(meanSub_g(x), meanSub_j(x), times=10)
# Unit: milliseconds
# expr min lq median uq max neval
# meanSub_g(x) 233.037178 236.089867 244.807039 278.221064 312.243826 10
# meanSub_j(x) 3.966353 4.585641 4.734748 5.288245 6.071373 10
microbenchmark(meanSub_g(x, .1, .7), meanSub_j(x, .1, .7), times=10)
# Unit: milliseconds
# expr min lq median uq max neval
# meanSub_g(x, 0.1, 0.7) 233.54520 234.7938 241.6667 272.3872 277.6248 10
# meanSub_j(x, 0.1, 0.7) 94.73928 95.1042 126.7539 128.6937 130.8479 10
我不會叫subset
,它可能很慢:
meanSub <- function(x, lower = 0, upper = 1){
Cutoffs <- quantile(x, probs = c(lower,upper))
return(mean(x[x >= Cutoffs[1] & x <= Cutoffs[2]]))
}
否則,您的代碼就可以了,應該已經非常快了。 當然,要關注內存數據的單線程計算。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.