在数据帧的行

时间:2017-01-02 21:28:35

标签: r vectorization apply mapply

我正在尝试使用Tukey's test来计算数据框每行的平均值,不包括异常值。

df <- data.frame(matrix(rnorm(1000000), ncol = 10))
averaging_wo_outliers <- function(x){
    q_result = quantile(x, probs = c(0.25, 0.75), na.rm=TRUE)
    lowerq = q_result[1]
    upperq = q_result[2]
    iqr = upperq - lowerq
    threshold_upper = (iqr * 1.5) + upperq
    threshold_lower = lowerq - (iqr * 1.5)
    return(mean(x[(x <= threshold_upper) & (
        x >= threshold_lower)]))
}
result <- apply(df, 1, averaging_wo_outliers)

现在这很慢。采用类似于this answer的方法,我一直试图通过矢量化来加快速度。甚至可以更快地完成这项任务吗?此外,如果它不可矢量化(如果这是一个单词!),您认为使用dplyrdata.table可能会有所帮助,或者我不应该期望使用这些包有任何改进吗?谢谢。

0 个答案:

没有答案