r - colMeans(x, na.rm = TRUE) 错误 : 'x' must be numeric in KNN classification

标签 r runtime-error knn

我有以下代码尝试在分类模型中使用 knn:

library(dplyr)
library(e1071)
library(ggplot2)
library(nnet)
library(DMwR)
library(rpart.plot)
library(class)

dat         <- read.csv("C:/Users/Ze/Desktop/HallowSet/train.csv",header = T,stringsAsFactors = F)

needToSolve <- read.csv("C:/Users/Ze/Desktop/HallowSet/test.csv",header = T,stringsAsFactors = F)

dat$color <- factor(dat$color)
dat$type  <- factor(dat$type)

sp    <- sample(1:nrow(dat),0.7*nrow(dat))
train <- dat[sp,]
test  <- dat[-sp,]
full  <- rbind(train,test)



pre <-kNN(type ~ .,train ,test,k=3,norm=TRUE,type='class')

但是当代码到达下一行时,我得到一个 colMeans(x, na.rm = TRUE) : 'x' must be numeric,我不知道为什么会这样,也不知道如何解决,有人可以告诉我它? 提前致谢。

海峡(完整):

'data.frame':   259 obs. of  12 variables:
$ id           : int  62 699 23 172 701 70 809 393 465 839 ...
$ bone_length  : num  0.304 0.417 0.585 0.498 0.477 ...
$ rotting_flesh: num  0.267 0.625 0.593 0.374 0.479 ...
$ hair_length  : num  0.527 0.329 0.681 0.58 0.404 ...
$ has_soul     : num  0.387 0.28 0.936 0.512 0.545 ...
$ color        : Factor w/ 6 levels "black","blood",..: 4 2 4 4 3 5 6 4 6 2 ...
$ type         : Factor w/ 3 levels "Ghost","Ghoul",..: 3 1 2 3 2 1 1 2 1 3 ...
$ bone_flesh   : num  0.0812 0.2608 0.3467 0.1866 0.2282 ...
$ bone_hair    : num  0.16 0.137 0.398 0.289 0.192 ...
$ bone_soul    : num  0.118 0.117 0.547 0.255 0.26 ...
$ flesh_hair   : num  0.141 0.205 0.404 0.217 0.193 ...
$ flesh_soul   : num  0.103 0.175 0.555 0.192 0.261 ...

最佳答案

“颜色”是一个因素。 kNN 只接受数字输入。您可以将 Color 变量转换为数值变量或完全删除 Color。

dat$color = as.numeric(dat$color)

关于r - colMeans(x, na.rm = TRUE) 错误 : 'x' must be numeric in KNN classification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47729435/

相关文章:

注销和登录时 ios Facebook 集成错误

r - R 的 Dockerfile 配置 - 无法加载某些包

r - 在 r 中使用 "for"循环和表格

r - 从 R 中的多个 JPEG 生成 PDF

java - 预期如何修复 '('或 '['

R中的R树和图分区库

R:引用类类型的引用类中的字段

ruby-on-rails - Ruby on Rails ActiveModel::MassAssignmentSecurity::错误

python - 如何从 1,000,000 行和 20,000 个特征中获取最近邻矩阵?

machine-learning - cross_val_score 与另一种计算准确度的方法之间的差异