Skip to contents

Constructs a spatial neighborhood network from spatial coordinates using either Delaunay triangulation or K-nearest neighbors (KNN) approach.

Usage

buildSpatialNetwork(
  coords,
  method = c("delaunay", "knn"),
  k = 10L,
  filter_dist = NA,
  binary = TRUE,
  verbose = FALSE
)

Arguments

coords

Numeric matrix of spatial coordinates. Rows are spatial locations, columns are coordinate dimensions (typically x, y).

method

Character string specifying the network construction method.

  • "delaunay": Delaunay triangulation (default). Creates a network where neighbors are determined by triangulation. Works well for relatively uniform spatial distributions.

  • "knn": K-nearest neighbors. Each spot is connected to its k nearest neighbors based on Euclidean distance.

k

Integer. Number of nearest neighbors for KNN method. Default is 10. Ignored when method = "delaunay".

filter_dist

Numeric or NA. Maximum distance threshold for neighbors. Pairs with distance > filter_dist are not considered neighbors. Default is NA (no filtering).

binary

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

verbose

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

Value

A square numeric matrix representing the spatial adjacency/weight matrix. Row and column names correspond to the spatial locations (from rownames of coords).

  • If binary = TRUE: Values are 1 (neighbors) or 0 (non-neighbors)

  • If binary = FALSE: Values are Euclidean distances (0 for non-neighbors)

Details

Delaunay Triangulation: Creates a network based on Delaunay triangulation, which maximizes the minimum angle of all triangles. This is a natural way to define neighbors in 2D/3D space. Requires the geometry package.

K-Nearest Neighbors: Connects each point to its k nearest neighbors based on Euclidean distance. More robust to irregular spatial distributions but requires choosing k. Requires the RANN package.

Examples

# Generate example coordinates
set.seed(42)
coords <- cbind(x = runif(100), y = runif(100))
rownames(coords) <- paste0("spot_", 1:100)

# Build network using Delaunay triangulation
W_delaunay <- buildSpatialNetwork(coords, method = "delaunay")

# Build network using KNN
W_knn <- buildSpatialNetwork(coords, method = "knn", k = 6)