Skip to contents

Extract Top k Nearest Neighbor Pairs by Distance

Usage

nearest_knn(dis, k, top = 3)

Arguments

dis

A symmetric distance matrix (as `dist` or matrix).

k

Integer. Number of nearest neighbors to compute per item.

top

Integer. Number of top-ranked unique nearest neighbor pairs to return (default: 3).

Value

A data frame with columns `i`, `j`, and `dis`, listing the top nearest neighbor pairs and their distances.

Details

Returns the top closest k-nearest neighbor pairs based on pairwise distances, excluding duplicates.

Examples

dist_mat <- dist(matrix(rnorm(100), ncol = 5))
top_pairs <- nearest_knn(dist_mat, k = 5, top = 10)
head(top_pairs)
#>     i  j       dis
#> 1   6 10 0.5976470
#> 3   6  7 0.7377675
#> 5   2 20 0.8554354
#> 7  13 20 0.9773879
#> 9   7  9 1.0302414
#> 11 10 20 1.0479293