自定义Trimmed Mean函数在R中返回'NaN'

ozxc1zmp  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(114)

我试图构建一个修剪均值函数,但函数返回'NaN',我不确定问题所在的函数

trimmed_mean <- function(x, trim) {
    n = length(x)
    ## the number to trim on each end
    n_to_trim = floor(trim * length(x))
    ## sort the vector
    x_sorted = sort(x)
    ## the indices of the elements to trim at the low end
    lo_idx = 1:n_to_trim
    ## the indices of the elements to trim at the high end
    hi_idx = (n - n_to_trim):n
    ## get rid of the lowest elements
    x_trimmed = x_sorted[!lo_idx]
    ## get rid of the highest elements
    x_trimmed = x_trimmed[!hi_idx]
    return(mean(x_trimmed))
}

## should give 2.75
trimmed_mean(c(-20, 1, 3, 2, 2, 5, 20, 2, 3, 4), trim = .1)

它应该返回2.75。

rjee0c15

rjee0c151#

这里有一个非常简单的想法。
您需要使用-而不是!来排除数字指定的元素:

x_trimmed = x_sorted[-c(lo_idx, hi_idx)]

而不是对应的两条!线
我通过运行debug(trimmed_mean)然后再次运行trimmed_mean(...)调用发现了这一点(我没有立即看到它)。当我发现有令人惊讶的结果的步骤时,我能够更仔细地观察那条线,看看哪里出了问题。(你也可以通过在代码中引入大量的cat()print()语句来跟踪结果,但是debug()(或debugonce())更方便。您还可以在RStudio中交互式地设置调试标志。
还要注意,如果n_to_trim被舍入为0,会发生一些奇怪的事情。

相关问题