【问题标题】:Finding Mean of Vector, Excluding Quantile Cutoffs in R查找向量的均值,不包括 R 中的分位数截止值
【发布时间】:2014-08-05 13:57:01
【问题描述】:

我想找到两个分位数截止值范围内的数字向量的平均值(提供一种简单的方法来计算控制异常值的平均值)。


示例: 三个参数,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))
}

显然有许多严格的方法可以做到这一点。然而,我在许多观察中应用了这个函数——我很好奇你是否可以提供函数设计或预先存在的包的提示,它们会很快做到这一点。

【问题讨论】:

    标签: r subset mean outliers


    【解决方案1】:

    您可以使用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
    

    【讨论】:

      【解决方案2】:

      我不会打电话给subset,可能会很慢:

      meanSub <- function(x, lower = 0, upper = 1){
        Cutoffs <- quantile(x, probs = c(lower,upper))
        return(mean(x[x >= Cutoffs[1] & x <= Cutoffs[2]]))
      }
      

      否则,您的代码是可以的,应该已经非常快了。当然,作为内存数据的单线程计算而言。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-08-01
        • 2012-09-11
        • 2018-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        相关资源
        最近更新 更多