Reputation: 45
I want to use the knn method for classification, but in addition to retrieving the appropriate label, I also need to retrieve the values of the nearest neighbor (to the test data). How can I retrieve the nearest neighbor in 1nn? For example, I have the following data
#this is the train data
X Y L
1 4 T
2 5 F
3 6 T
#this is the test data
X Y L
8 3 T
#knn with k=1
knn(train[,-3],test[,-3],train$L,k=1)
The response of this function is only the appropriate label("T"), but I want to return the value of the nearest neighbor(For example, here it is returned: row 3:3 6 T) please help me.
Upvotes: 0
Views: 1111
Reputation: 37641
Several different packages have implementations of knn and you do not say which you are using. Not all of them provide the neighbor, but the version of knn in FNN does.
library(FNN)
KNN_Model = knn(train[,-3],test[,-3],train$L,k=1)
attr(KNN_Model, "nn.index")
[,1]
[1,] 3
Upvotes: 1