Reputation: 179
I'm using the knn function of the class package:
k <- knn(train = training, test = testset, cl = classes, k = 1, prob = TRUE)
Is there any way to obtain the indexes of the k nearest neighbors in the training data for a given example in the test set? I don't find anything about that in the documentation of the package! The knn function only returns the classes of the test examples and the classification probabilities, but not the indexes of the k nearest neighbors for each test example.
Thanks in advance!
Upvotes: 2
Views: 2540
Reputation: 37879
You need a different package to do that. You need the FNN package in R and the function get.knn. You can read the documentation here
Here is a simple example:
library(FNN)
data <- cbind(1:100, 1:100)
a <- get.knn(data, k=3)
and you type this to get the 3 nearest neighbors' indices for each record:
> a$nn.index
[,1] [,2] [,3]
[1,] 2 3 4
[2,] 1 3 4
[3,] 2 4 1
[4,] 3 5 2
[5,] 6 4 3
[6,] 5 7 4
[7,] 6 8 5
[8,] 9 7 10
[9,] 10 8 11
[10,] 9 11 12
[11,] 12 10 9
Upvotes: 2