For each row of 'x' finds the 'knn' nearest rows of 'y', or of 'x' itself if 'y' is 'NULL', by euclidean distance.
tgs_dist_knn(x, y = NULL, knn, threshold = Inf)A data frame with the columns 'row1' (a row of 'x'), 'row2' (a row of 'y', or of 'x' if 'y' is 'NULL'), 'dist' (their distance) and 'rank' (1 for the nearest row), sorted by 'row1' and 'rank'. 'row1' and 'row2' are factors if the matrices have row names.
'tgs_dist_knn' returns the same neighbours as selecting the 'knn' smallest distances of each row of 'x' from 'tgs_dist(x, y)' (or from 'tgs_dist(x)'), but it never holds all the distances in memory: its memory consumption is a factor of max(NXxNC + NYxNC, NXxKNN), where NX and NY are the numbers of rows of 'x' and 'y' and NC their number of columns.
The distances, including the treatment of missing values, are those of 'tgs_dist'. If 'y' is 'NULL' a row is not a neighbour of itself. Ties are broken by the lower row number, a pair whose distance is 'NA' is never a neighbour, and only the distances that are less or equal than 'threshold' are reported, so a row may have fewer than 'knn' neighbours.
With BLAS ('tgs_use.blas') and data without missing values, the squared distance between points x and y is computed as 'sum(x^2) + sum(y^2) - 2 * sum(x * y)', which loses precision for points that are close relative to their norms.