I'm looking for a well-optimized function that accepts an n X n
distance matrix and returns an n X k
matrix with the indices of the k
nearest neighbors of the ith datapoint in the ith row.
I find a gazillion different R
packages that let you do KNN, but they all seem to include the distance computations along with the sorting algorithm within the same function. In particular, for most routines the main argument is the original data matrix, not a distance matrix. In my case, I'm using a nonstandard distance on mixed variable types, so I need to separate the sorting problem from the distance computations.
This is not exactly a daunting problem -- I obviously could just use the order
function inside a loop to get what I want (see my solution below), but this is far from optimal. For example, the sort
function with partial = 1:k
when k
is small (less than 11) goes much faster, but unfortunately returns only sorted values rather than the desired indices.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…