我正在尝试构建一个修剪后的均值函数,但该函数返回“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。
这里有一个非常简单的想法。
您需要使用
-
而不是 !
来排除以数字指定的元素:
x_trimmed = x_sorted[-c(lo_idx, hi_idx)]
而不是对应的带有
!
的两行
另请注意,如果
n_to_trim
向下舍入为 0 ...,会发生一些奇怪的事情