Skip to contents

Given a matrix of spatial coordinates, this function computes the k-nearest neighbors (KNN) for each point using Euclidean distance. It returns the neighbor indices and distances.

Usage

SpatialKNN(sample_information_coordinate, k = 50)

Arguments

sample_information_coordinate

A data.frame or matrix. Rows are spatial units (e.g., cells or spots), columns are coordinates (e.g., x and y).

k

Integer. Number of nearest neighbors to compute (default = 50).

Value

A list with:

knn_value

A matrix of distances to the k nearest neighbors (first column is self, with distance 0).

knn_sample

A matrix of neighbor names (cell/spot IDs), with self in the first column.

Details

- The input coordinate matrix must have rownames corresponding to spot or cell IDs. - The output includes a neighbor matrix with the first column as the self point. - Distances to self are set to 0 by definition.

Author

Bin Duan

Examples

if (FALSE) { # \dontrun{
coords <- data.frame(x = runif(10), y = runif(10))
rownames(coords) <- paste0("cell", 1:10)
result <- SpatialKNN(coords, k = 3)
result$knn_sample
result$knn_value
} # }