Tomas
Tomas

Reputation: 115

Use knn with k=1 and classify the test dataset in R

Using the iris dataset in R I have come up with two different subsets.

test <- iris[seq(1, nrow(iris), by = 5),]
training <- iris[-seq(1, nrow(iris), by = 5),]

I'm now looking for the k nearest neighbor using k=1. Here's my attempt and output.

knn(test, k = 1, prob=TRUE)

**Error in knn(test, k = 1, prob = TRUE) : 
  argument "test" is missing, with no default**

Why is this telling me that "test" is missing? Thanks

Upvotes: 0

Views: 977

Answers (1)

Bryan Goggin
Bryan Goggin

Reputation: 2489

Try this:

test <- iris[seq(1, nrow(iris), by = 5),-5] #hide the species from knn
training <- iris[-seq(1, nrow(iris), by = 5),-5]

cl <-iris[-seq(1, nrow(iris), by = 5),]$Species #this is where you tell
# it which species is which.

knn(train = training, test = test, cl = cl, k = 1, prob=TRUE)

[1] setosa     setosa     setosa     setosa     setosa     setosa     setosa    
[8] setosa     setosa     setosa     versicolor versicolor versicolor versicolor
[15] virginica  versicolor versicolor versicolor versicolor versicolor virginica 
[22] virginica  virginica  virginica  virginica  virginica  virginica  virginica 
[29] virginica  virginica 
attr(,"prob")
[1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Levels: setosa versicolor virginica

Upvotes: 0

Related Questions