0

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.

maria
  • 45
  • 6
  • I want to specify the usefulness of each instance in each dataframe.(The usefulness, defined as the number of instances correctly classified by this instance.) I want to add a number to the usefulness attribute (to the train data), if the label that knn is given is equal to the actual label.My data is a number of dataframes in a list. – maria Oct 24 '17 at 07:50

1 Answers1

1

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
G5W
  • 36,531
  • 10
  • 47
  • 80
  • If I have a number of data frames in a list, can I specify the corresponding data frame in addition to the row number ? – maria Oct 25 '17 at 06:39
  • I do not think that any of the implementations of knn work on a list of data frames. I think you are saying that all of the data frames in your list have the same structure and you want to compare new points with the points in all data frames. If that is true, I would recommend creating one big data frame with all of the data, but adding a column to indicate which of the original DFs each point came from. – G5W Oct 25 '17 at 12:59
  • I want to use knngow in the dprep package because this method can be used in nominal and numeric data. Is there a function in this package that I can retrieve the data of the nearest neighbor (return to your previous answer to my question) – maria Oct 30 '17 at 10:08