您的索引有点偏离
impute.to.window.mean <- function(x, window) {
na.idx <- which(is.na(x)) #find missing values in x
for (na in na.idx) {
y <- sort(x[(na - window):(na + window)])
x[na] <- mean(y)
}
return(x)
}
浏览一个例子
set.seed(1)
x <- sample(10)
na <- 6
x[na] <- NA
# [1] 3 4 5 7 2 NA 9 6 10 1
window <- 3L
我之所以使用sort
它,是因为它NA
一步一步降低了 s;你想要这个向量的平均值,它是所有的值window
sort(x[(na - window):(na + window)])
# [1] 2 5 6 7 9 10
mean(sort(x[(na - window):(na + window)]))
# [1] 6.5
立即测试您的功能
impute.to.window.mean(x, window)
# [1] 3.0 4.0 5.0 7.0 2.0 6.5 9.0 6.0 10.0 1.0
编辑
实际上,您可能应该使用
y <- sort(x[pmax(1L, (na - window)):pmin(length(x), (na + window))])
相反,如果 anNA
发生在 2 并且您的窗口 > 1
## current version
impute.to.window.mean(x, 10)
# Error in x[(na - window):(na + window)] :
# only 0's may be mixed with negative subscripts
## version with pmax/pmin
impute.to.window.mean(x, 10)
# [1] 3.000000 4.000000 5.000000 7.000000 2.000000 5.222222 9.000000 6.000000 10.00000 1.000000
mean(sort(x))
# [1] 5.222222
impute.to.window.mean <- function(x, window) {
na.idx <- which(is.na(x)) #find missing values in x
for (na in na.idx) {
# y <- sort(x[(na - window):(na + window)])
y <- sort(x[pmax(1L, (na - window)):pmin(length(x), (na + window))])
x[na] <- mean(y)
}
return(x)
}