Skip to contents

Get the k nearest neighbors for each location, including the location itself. This function calls dist, so the options for the distance measure used is the same as for that one. Distances are calculated between rows.

Usage

coords_to_knn(x, k = min(10, nrow(x)), method = "euclidean", p = 2)

Arguments

x

a numeric matrix, data frame or "dist" object.

k

The number of nearest neighbors, counting the location itself.

method

the distance measure to be used. This must be one of "euclidean", "maximum", "manhattan", "canberra", "binary" or "minkowski". Any unambiguous substring can be given.

p

The power of the Minkowski distance.

Value

An integer matrix of the \(k\) nearest neighbors for each location. Each row corresponds to a location, with the first element of each row being the location itself. Locations are encoded as integers.

Examples

x <- matrix(c(0, 0,
              1, 0,
              2, 1,
              0, 4,
              1, 3),
            ncol = 2, byrow = TRUE)
plot(x)

coords_to_knn(x)
#>   [,1] [,2] [,3] [,4] [,5]
#> 1    1    2    3    5    4
#> 2    2    1    3    5    4
#> 3    3    2    1    5    4
#> 4    4    5    3    1    2
#> 5    5    4    3    2    1