Learn R Programming

SVG (version 1.0.0)

getSpatialNeighbors_KNN: Build Spatial Network via K-Nearest Neighbors

Description

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
)

Value

Square numeric matrix of spatial adjacency weights.

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.

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

Run this code
set.seed(42)
coords <- cbind(x = runif(50), y = runif(50))
rownames(coords) <- paste0("spot_", 1:50)

# \donttest{
if (requireNamespace("RANN", quietly = TRUE)) {
    W <- getSpatialNeighbors_KNN(coords, k = 6)
}
# }

Run the code above in your browser using DataLab