knn: K-Nearest Neighbor Graph

View source: R/helper_functions_knn.R

knnR Documentation

K-Nearest Neighbor Graph

Description

Calculte the edge matrix of a K-nearest neighbor graph based on a distance matrix, used as helper functions in SH

Usage

knn(dists, K = 1)
knn.fast(dists, K = 1)
knn.bf(dists, K = 1)

Arguments

dists

Distance matrix

K

Number of nearest neighbors to consider (default: K = 1)

Details

knn.bf uses brute force to find the K nearest neighbors but does not require additional packages. knn uses the kNN implementation of the dbscan package. knn.fast uses the get.knn implementation of the FNN package that uses a kd-tree for fast K-nearest neighbor search.

Value

The edge matrix of the K-nearest neighbor graph. The first column gives the index of the first node of each edge. The second column gives the index of the second node of each edge. Thus, the second entry of each row is one of the K nearest neighbors of the first entry in each row.

See Also

SH

Examples

X1 <- matrix(rnorm(1000), ncol = 10)
X2 <- matrix(rnorm(1000, mean = 0.5), ncol = 10)
dists <- stats::dist(rbind(X1, X2))
# Nearest neighbor graph
knn(dists)
knn.fast(dists)
knn.bf(dists)
# 5-Nearest neighbor graph
knn(dists, K = 5)
knn.fast(dists, K = 5)
knn.bf(dists, K = 5)

DataSimilarity documentation built on April 3, 2025, 9:39 p.m.