For each cell, computes the distance to the nearest neighbouring cell,
optionally restricted to specific phenotypes.
The query cell is excluded even when it has the target phenotype. Distinct
cells at the same coordinates remain neighbours. If fewer than k other
target cells are available within the sample, their distances are averaged;
if none are available, the distance is NA.
Arguments
- dt
A
data.tablewith columnssample_id,x, andy. Sample identifiers must be complete and nonblank; coordinates must be finite real numeric vectors. Samples are processed independently. Empty tables retain their columns and receive an empty result column.- target_phenotype
Character string or
NULL. If provided, distances are computed only to cells of this phenotype. Requires aphenotypecolumn.- k
Positive integer. Number of nearest neighbours to consider. Default
1.
Value
The input data.table with an added nn_distance column
(mean distance to the k nearest neighbours).
Examples
dt <- data.table::data.table(
sample_id = "s1", cell_id = 1:20,
x = runif(20, 0, 100), y = runif(20, 0, 100)
)
result <- nearest_neighbours(dt, k = 3)
head(result[, .(cell_id, nn_distance)])
#> cell_id nn_distance
#> <int> <num>
#> 1: 1 12.937976
#> 2: 2 11.203918
#> 3: 3 13.765183
#> 4: 4 20.192255
#> 5: 5 14.425834
#> 6: 6 7.784847