r - 使用 knnImpute 时 preProcess() 中的 "Error: Must subset rows with a valid subscript vector"

标签 r na knn

我正在使用 kaggle 的 pokemon 数据通过 preProcess() 练习 KNN 插补,但是当我这样做时,我在 predict() 之后遇到了以下消息步。我想知道我是否使用了不正确的数据格式,或者某些列是否具有不适当的“类”。下面是我的代码。

library(dplyr)
library(ggplot2)
library(tidyr)
library(reshape2)
library(caret)
library(skimr)
library(psych)
library(e1071)
library(data.table)


pokemon <- read.csv("https://www.dropbox.com/s/znbta9u9tub2ox9/pokemon.csv?dl=1")

pokemon = tbl_df(pokemon)

# select relevant features

df <- select(pokemon, hp, weight_kg, height_m, sp_attack, sp_defense, capture_rate)

pre_process_missing_data <- preProcess(df, method="knnImpute")
classify_legendary <- predict(pre_process_missing_data, newdata = df)


我收到了这个错误信息
Error: Must subset rows with a valid subscript vector.
x Subscript `nn$nn.idx` must be a simple vector, not a matrix.
Run `rlang::last_error()` to see where the error occurred.

最佳答案

preProcess 的输入必须是 data.frame .这有效:

pre_process_missing_data <- preProcess(as.data.frame(df), method="knnImpute")

classify_legendary <- predict(pre_process_missing_data, newdata = df)
classify_legendary 

> classify_legendary
# A tibble: 801 x 6
       hp weight_kg height_m sp_attack sp_defense capture_rate
    <dbl>     <dbl>    <dbl>     <dbl>      <dbl> <chr>       
 1 -0.902    -0.498  -0.429     -0.195     -0.212 45          
 2 -0.337    -0.442  -0.152      0.269      0.325 45          
 3  0.415     0.353   0.774      1.57       1.76  45          
 4 -1.13     -0.484  -0.522     -0.349     -0.748 45          
 5 -0.412    -0.388  -0.0591     0.269     -0.212 45          
 6  0.340     0.266   0.496      2.71       1.58  45          
 7 -0.939    -0.479  -0.615     -0.659     -0.247 45          
 8 -0.375    -0.356  -0.152     -0.195      0.325 45          
 9  0.378     0.221   0.404      1.97       1.58  45          
10 -0.902    -0.535  -0.800     -1.59      -1.82  255         
# ... with 791 more rows

关于r - 使用 knnImpute 时 preProcess() 中的 "Error: Must subset rows with a valid subscript vector",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62085827/

相关文章:

machine-learning - k 最近邻的分类属性的距离度量

performance - R 中的执行效率与程序员效率

带约束的 R 线性模型

r - R 中的高级调试功能?

R:在按日期匹配行后,用第二个 dfrm 中的值替换第一个 dfrm 中多列中的 NA 值

r - 将R中选定列中的所有NA替换为FALSE

r - Julia 的包中是否有 rep() 函数?

r - 我可以缩写 df[ !is.na(df$val) & df$val > 15] 吗?

python - KNeighborsClassifier 中如何使用参数 "weights"?

matlab - 如何使用K近邻分类进行字符预测