I have the follow code to try to use the knn in a classification model:
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')
But when the code reach the next line I get an colMeans(x, na.rm = TRUE) : 'x' must be numeric, I don't know why is that happening and how to solve it someone can tell me it? Thaks in the advance.
str(full):
'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 ...
'Color' is a factor. kNN only takes numeric inputs. You can turn your Color variable into a numeric variable or just remove Color entirely.
dat$color = as.numeric(dat$color)