preProcess 不返回值,它只是根据提供的数据建立整个预处理模型。因此,您需要运行 predict(还需要 RANN 包),但即使您使用人工数据执行此操作,也会出现错误:
Error in FUN(newX[, i], ...) :
cannot impute when all predictors are missing in the new data point
因为 k-nn 插补不能在 both 您的预测变量均为 NA 的行中起作用。
这是一个只有 20 行的演示,为了清晰和易于检查:
library(caret)
t <- data.frame(seq_len(20),seq_len(20))
for (i in 1:20)
{
if (i %% 3 == 0) t[i,1] <- NA;
if (i %% 7 == 0) t[i,2] <- NA
}
names(t) <- c('V1', 'V2')
preProcValues <- preProcess(t, method = c("knnImpute"))
library(RANN)
t_imp <- predict(preProcValues, t)
查看结果时,请记住方法 "center", "scale" 已自动添加到您的预处理中,即使您没有显式调用它们:
> str(preProcValues)
List of 19
$ call : language preProcess.default(x = t, method = c("knnImpute"))
$ dim : int [1:2] 12 2
$ bc : NULL
$ yj : NULL
$ et : NULL
$ mean : Named num [1:2] 10.5 10.5
..- attr(*, "names")= chr [1:2] "V1" "V2"
$ std : Named num [1:2] 6.25 6.14
..- attr(*, "names")= chr [1:2] "V1" "V2"
$ ranges : NULL
$ rotation : NULL
$ method : chr [1:3] "knnImpute" "scale" "center"
$ thresh : num 0.95
$ pcaComp : NULL
$ numComp : NULL
$ ica : NULL
$ k : num 5
$ knnSummary:function (x, ...)
$ bagImp : NULL
$ median : NULL
$ data : num [1:12, 1:2] -1.434 -1.283 -0.981 -0.83 -0.377 ...
..- attr(*, "dimnames")=List of 2
.. ..$ : chr [1:12] "1" "2" "4" "5" ...
.. ..$ : chr [1:2] "V1" "V2"
..- attr(*, "scaled:center")= Named num [1:2] 10.5 10.5
.. ..- attr(*, "names")= chr [1:2] "V1" "V2"
..- attr(*, "scaled:scale")= Named num [1:2] 6.63 6.63
.. ..- attr(*, "names")= chr [1:2] "V1" "V2"
- attr(*, "class")= chr "preProcess"