Skip to contents

Given a distance matrix, calculate the \(k\) nearest neighbors of each location, including the location itself. The matrix should contain only zeros on the diagonal, and all other elements should be positive.

Usage

dist_to_knn(x, k = min(10, nrow(x)))

Arguments

x

A (square) distance matrix. Elements should be non-negative and the diagonal zeros, but this is not checked.

k

The number of nearest neighbors, counting the location itself.

Value

A matrix of integers, row \(i\) containing the \(k\) nearest neighbors of location \(i\), including itself.

Examples

x <- matrix(c(0, 0,
              1, 0,
              2, 1,
              0, 4,
              1, 3),
            ncol = 2, byrow = TRUE)
d <- dist(x, diag = TRUE, upper = TRUE)
dist_to_knn(d, k = 3)
#>   [,1] [,2] [,3]
#> 1    1    2    3
#> 2    2    1    3
#> 3    3    2    1
#> 4    4    5    3
#> 5    5    4    3