Skip to contents

Constructs a spatial adjacency matrix using K-nearest neighbors. Each point is connected to its k nearest neighbors based on Euclidean distance.

Usage

getSpatialNeighbors_KNN(
  coords,
  k = 10L,
  mutual = FALSE,
  binary = TRUE,
  verbose = FALSE
)

Arguments

coords

Numeric matrix of spatial coordinates.

k

Integer. Number of nearest neighbors. Default is 10.

mutual

Logical. If TRUE, only mutual nearest neighbors are connected (both A->B and B->A must exist). Default is FALSE.

binary

Logical. If TRUE (default), return binary adjacency matrix. If FALSE, return distance-weighted matrix.

verbose

Logical. Whether to print progress messages. Default is FALSE.

Value

Square numeric matrix of spatial adjacency weights.

Details

Uses the RANN package for efficient nearest neighbor search with KD-trees. The resulting network may be asymmetric (A is neighbor of B doesn't mean B is neighbor of A) unless mutual = TRUE.

Examples

set.seed(42)
coords <- cbind(x = runif(50), y = runif(50))
rownames(coords) <- paste0("spot_", 1:50)
W <- getSpatialNeighbors_KNN(coords, k = 6)