我想用最接近的邻居的平均值来估算缺失值,但是当我尝试kNN时,会给出错误消息。
因此向量是“股票价格”,这意味着我在周末不适用。我想用凹函数替换NA值(星期六,星期日):(星期五值+星期一值)/ 2。我认为k = 2的kNN函数将是适当的,但是我收到一条错误消息。
> Oriental_Stock$Stock
[1] 42.80 43.05 43.00 43.00 42.20 NA NA 42.50 40.00 40.25 40.55
41.50 NA NA 40.85
> kNN(Oriental_Stock, variable = colnames("Stock"), k = 2)
Error in `[.data.table`(data, indexNA2s[, variable[i]], `:=`(imp_vars[i],
: i is invalid type (matrix). Perhaps in future a 2 column matrix could
return a list of elements of DT (in the spirit of A[B] in FAQ 2.14).
Please report to data.table issue tracker if you'd like this, or add
your comments to FR #657.
请让我知道是否可以执行此操作,也许还有比kNN更简单的选项。我不是数据科学家,而是学生,所以对此我不太了解。预先感谢您的任何建议!
答案 0 :(得分:0)
Knn将在data.frame上工作,在其中它根据行之间的距离选择邻居。它不适用于矢量。
for循环可能是一个合理的解决方案:
#this finds the locations of the first NA of each couple of NAs
#the TRUE / FALSE part below picks only the first NA from each couple
idx <- which(is.na(stock))[c(TRUE, FALSE)]
#this iterates over the above indexes and calculates the mean and updates the NAs
for (x in idx) {
stock[x] <- stock[x+1] <- (stock[x-1] + stock[x+2]) / 2
}
结果:
> stock
[1] 42.800 43.050 43.000 43.000 42.200 42.350 42.350 42.500 40.000
[10] 40.250 40.550 41.500 41.175 41.175 40.850
我使用stock
作为数据:
stock <- c(42.80,43.05, 43.00, 43.00, 42.20, NA, NA, 42.50, 40.00, 40.25, 40.55,
41.50, NA, NA, 40.85)