spatialLagGLM asks, gene by gene, whether the expression
at a spot is associated with the expression at the spots around it, in
spatial transcriptomics data stored in a SpatialExperiment.
For each gene it fits a quasi-Poisson regression with a library-size
offset, optional design terms from colData, and the
spatial lag of the gene’s own normalised counts as an extra
covariate. The lag coefficient, its statistic and the rank of that
statistic across genes are written to rowData() of the
input object.
The package reports no p-values. The statistic is meant for ranking genes, not for testing against a significance threshold. The reason, with evidence, is in Why there are no p-values.
Several methods already find spatially variable genes (SVGs). SPARK-X Zhu et al. 2021, nnSVG Weber et al. 2023 and SpatialDE Svensson et al. 2018 test whether a gene’s expression has spatial covariance structure, using kernel or Gaussian process models, and they target any spatial pattern, with calibrated tests.
The closest relatives of this package are tools that build a
neighbour graph and compute spatial lags or Moran’s I:
spdep (CRAN) and, in Bioconductor, Voyager
with SpatialFeatureExperiment. They compute the lag and the
autocorrelation statistic of each gene, with tests designed for that
purpose. spatialLagGLM differs in that the lag enters a
count regression as a covariate, next to a library-size offset and any
colData variables, so the spatial association is estimated
given those terms, and the results are stored in the
SpatialExperiment you pass in. It does not provide
calibrated tests, so if you need hypothesis tests for spatially variable
genes use the packages above. Use spatialLagGLM to rank
genes and to obtain design-adjusted lag estimates, and confirm hits
independently.
For one gene, let \(y_i\) be the count at spot \(i\). The model is
\[\log E[y_i] = \log(s_i) + X_i\beta + \gamma\, l_i, \qquad l_i = \sum_j w_{ij}\,\frac{y_j}{s_j},\]
fitted with a quasi-Poisson family. Here \(s_i\) is the size factor of spot \(i\) (library size divided by the geometric
mean of library sizes), \(X_i\) is the
row of the design matrix, and \(w_{ij}\) are weights: the inverse distance
between spots \(i\) and \(j\) if they are within radius
of each other (and in the same sample), zero otherwise, with each row
scaled to sum to one. A spot with no neighbours has \(l_i = 0\).
The question asked is whether \(\gamma = 0\): given the offset and the design terms, is the expression at a spot associated with the weighted mean of the normalised expression of its neighbours? The effect size reported is \(\hat\gamma\) and the statistic is \(\hat\gamma\) divided by its quasi-Poisson standard error.
Because \(l_i\) is built from the same gene’s counts, this is not a spatial autoregressive (SAR) model.
The package ships a simulated dataset: a 30 x 30 grid of spots and 50
genes. Spots within 7 units of the centre are labelled
TumorCore, the rest Margin. Gene1
is up-regulated in the core; the other 49 genes are simulated without
any spatial pattern.
library(spatialLagGLM)
library(SpatialExperiment)
set.seed(1)
se <- makeMockSpatial()
se
#> class: SpatialExperiment
#> dim: 50 900
#> metadata(0):
#> assays(1): counts
#> rownames(50): Gene1 Gene2 ... Gene49 Gene50
#> rowData names(0):
#> colnames(900): Spot1 Spot2 ... Spot899 Spot900
#> colData names(2): condition sample_id
#> reducedDimNames(0):
#> mainExpName: NULL
#> altExpNames(0):
#> spatialCoords names(2) : px py
#> imgData names(0):
table(se$condition)
#>
#> Margin TumorCore
#> 751 149The function needs a SpatialExperiment with a raw-count
assay, spatial coordinates, and a sample_id column in
colData (which every SpatialExperiment has).
Spots with zero total counts must be removed first.
res <- spatialLagGLM(se, design = ~condition, radius = 2.5)
head(SummarizedExperiment::rowData(res), 3)
#> DataFrame with 3 rows and 3 columns
#> spatial_effect_size spatial_statistic spatial_rank
#> <numeric> <numeric> <integer>
#> Gene1 -0.000299181 -0.314586 36
#> Gene2 0.029788392 2.236118 4
#> Gene3 -0.002536482 -0.185341 42designcolData variables,
e.g. ~ condition. Use ~ 1 for no adjustment.
With ~ condition, the lag is estimated after allowing a
different mean in each condition, so a pattern that is fully explained
by condition is not reported. Compare:
res0 <- spatialLagGLM(se, design = ~1, radius = 2.5)
rd <- SummarizedExperiment::rowData
cols <- c("spatial_effect_size", "spatial_statistic", "spatial_rank")
out <- rbind(
as.data.frame(rd(res)["Gene1", cols]),
as.data.frame(rd(res0)["Gene1", cols])
)
rownames(out) <- c("~ condition", "~ 1")
out
#> spatial_effect_size spatial_statistic spatial_rank
#> ~ condition -0.0002991805 -0.3145858 36
#> ~ 1 0.0245069855 40.6396997 1radiusspatialCoords(se). See Choosing the radius.
assay.type"counts").
size.factorsBPPARAMBiocParallelParam,
e.g. BiocParallel::MulticoreParam(4). Genes are fitted in
parallel.
Weights are computed separately for each value of
colData(se)$sample_id, so spots in different sections are
never neighbours. All samples are assumed to share the same coordinate
units, because one radius is used for all.
The input object is returned with three new columns in
rowData():
spatial_effect_sizespatial_statisticspatial_rankNA is returned for genes whose fit failed or did not
converge, and a warning reports how many. The radius, assay and size
factors used are kept in
S4Vectors::metadata(res)$spatialLagGLM.
plotSpatialLag() draws a gene on the tissue coordinates,
either as raw counts or as its spatial lag (the covariate used in the
model). It uses the assay stored by spatialLagGLM() unless
you pass assay.type.
plotLagSummary() plots the effect size against the
absolute statistic for all genes and labels the top-ranked ones. It
draws no significance categories.
An interactive explorer combining both is available with
runSpatialLagExplorer(res0) (requires the
shiny package).
A quasi-Poisson fit would give a p-value for \(\gamma\) at no extra cost, but that p-value is not valid here. The lag \(l_i\) is made of the counts of the neighbours of spot \(i\), and spot \(i\)’s own count appears in the lags of those neighbours. Each pair of neighbouring spots therefore enters the regression twice, once as a response and once inside a covariate, and the usual standard error ignores this. If there is no spatial structure at all, the variance of the statistic exceeds what the model assumes by a factor of about
\[1 + \frac{\sum_{i \neq j} w_{ij} w_{ji}}{\sum_{i,j} w_{ij}^2},\]
which is close to 2 when neighbours are mutual (if spot \(j\) is within the radius of spot \(i\), then \(i\) is within the radius of \(j\)), as they are with a fixed radius. The standard deviation of the statistic is then about \(\sqrt{2} \approx 1.41\) instead of 1.
We can check this on the simulated data. Genes 2 to 50 have no spatial pattern, so their statistics should have a standard deviation of about 1.4:
In a larger simulation by the package author (3,000 independent
negative binomial genes on this grid, design ~ 1), the
predicted factor for these weights was 1.99, the predicted standard
deviation 1.41, and the observed standard deviation 1.45. At the usual
1.96 cutoff, 18% of null genes would be called significant instead of
5%.
This distortion depends on the weights, not on the gene, so it is
nearly the same for every gene and does not change the order of
the genes. That is why spatial_statistic and
spatial_rank are reported and p-values and significance
categories are not. Use the rank to prioritise genes.
If you need calibrated inference, compare the statistics with a
permutation null. Permuting the spots (columns) of the count matrix
keeps each spot’s library size but breaks any link between expression
and location, so the statistics from permuted data show what to expect
from no spatial signal. This recipe permutes all genes jointly and is
only appropriate with design = ~1; with design terms the
permutation would also break their association with the counts.
perm_counts <- SummarizedExperiment::assay(se, "counts")[, sample(ncol(se))]
colnames(perm_counts) <- colnames(se)
perm <- se
SummarizedExperiment::assay(perm, "counts") <- perm_counts
res_perm <- spatialLagGLM(perm, design = ~1, radius = 2.5)
perm_stat <- abs(rd(res_perm)$spatial_statistic)
obs_stat <- abs(rd(res0)$spatial_statistic)
sd(rd(res_perm)$spatial_statistic)
#> [1] 1.663106
## Fraction of permuted genes at least as extreme as Gene1:
(1 + sum(perm_stat >= obs_stat[1])) / (1 + length(perm_stat))
#> [1] 0.01960784With only 50 genes this null is coarse. On a real dataset, pool the statistics from several permutations, and treat the resulting fractions as empirical reference values, not as formal tests, unless you use many permutations.
radius sets the scale at which neighbours are defined.
Too small and many spots have no neighbours; too large and the lag
becomes a smooth regional average. A practical starting point is a small
multiple of the typical nearest-neighbour distance. On the mock grid,
spots are one unit apart, so radius = 1.5 includes the 8
surrounding spots and radius = 2.5 the 20 nearest.
coords <- spatialCoords(se)
d <- as.matrix(dist(coords))
diag(d) <- Inf
median(apply(d, 1, min))
#> [1] 1It is worth checking that the ranking does not change much over a few radii:
This example uses a 10x Visium sample of human dorsolateral
prefrontal cortex from the STexampleData package. To keep
the vignette fast we analyse the 300 most highly expressed genes.
Because spatialLagGLM() derives size factors from the genes
it is given, we compute them first from all genes and pass them
in.
library(STexampleData)
spe <- Visium_humanDLPFC()
spe <- spe[, as.logical(spe$in_tissue)]
counts_all <- SummarizedExperiment::assay(spe, "counts")
spe <- spe[, colSums(counts_all) > 0]
counts_all <- SummarizedExperiment::assay(spe, "counts")
lib <- colSums(counts_all)
sf <- lib / exp(mean(log(lib)))
top <- order(rowSums(counts_all), decreasing = TRUE)[seq_len(300)]
spe <- spe[top, ]
dim(spe)
#> [1] 300 3639The coordinates are in image pixels. We set the radius to 1.5 times the median nearest-neighbour distance, which captures the first ring of neighbours on the Visium hexagonal grid.
xy <- spatialCoords(spe)
d <- as.matrix(dist(xy))
diag(d) <- Inf
radius <- 1.5 * median(apply(d, 1, min))
radius
#> [1] 205.5055res_real <- spatialLagGLM(
spe,
design = ~1, radius = radius, size.factors = sf,
BPPARAM = BiocParallel::SerialParam()
)
tab <- as.data.frame(
SummarizedExperiment::rowData(res_real)[, c(
"spatial_effect_size", "spatial_statistic", "spatial_rank"
)]
)
head(tab[order(tab$spatial_rank), ], 5)
#> spatial_effect_size spatial_statistic spatial_rank
#> ENSG00000197971 0.03148876 144.56048 1
#> ENSG00000123560 0.05469306 109.62466 2
#> ENSG00000131095 0.13253330 95.49376 3
#> ENSG00000109846 0.15077397 95.32938 4
#> ENSG00000173786 0.16548196 92.99119 5top_gene <- rownames(tab)[which.min(tab$spatial_rank)]
plotSpatialLag(res_real, top_gene, metric = "spatial_lag")radius.sessionInfo()
#> R version 4.6.2 (2026-10-29)
#> Platform: x86_64-pc-linux-gnu
#> Running under: Ubuntu 26.04.1 LTS
#>
#> Matrix products: default
#> BLAS: /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3
#> LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.32.so; LAPACK version 3.12.0
#>
#> locale:
#> [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
#> [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
#> [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
#> [7] LC_PAPER=en_US.UTF-8 LC_NAME=C
#> [9] LC_ADDRESS=C LC_TELEPHONE=C
#> [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
#>
#> time zone: Etc/UTC
#> tzcode source: system (glibc)
#>
#> attached base packages:
#> [1] stats4 stats graphics grDevices utils datasets methods
#> [8] base
#>
#> other attached packages:
#> [1] STexampleData_1.23.0 ExperimentHub_3.5.0
#> [3] AnnotationHub_4.5.0 BiocFileCache_3.5.0
#> [5] dbplyr_2.6.0 SpatialExperiment_1.25.0
#> [7] SingleCellExperiment_1.37.0 SummarizedExperiment_1.45.0
#> [9] Biobase_2.75.0 GenomicRanges_1.67.0
#> [11] Seqinfo_1.5.0 IRanges_2.49.0
#> [13] S4Vectors_0.53.0 BiocGenerics_0.61.1
#> [15] generics_0.1.4 MatrixGenerics_1.27.0
#> [17] matrixStats_1.5.0 spatialLagGLM_0.99.6
#> [19] BiocStyle_2.43.0
#>
#> loaded via a namespace (and not attached):
#> [1] tidyselect_1.2.1 viridisLite_0.4.3 farver_2.1.2
#> [4] dplyr_1.2.1 blob_1.3.0 S7_1.0.0
#> [7] filelock_1.0.3 Biostrings_2.83.1 fastmap_1.2.0
#> [10] digest_0.6.39 lifecycle_1.0.5 KEGGREST_1.55.0
#> [13] RSQLite_3.54.1 magrittr_2.0.5 compiler_4.6.2
#> [16] rlang_1.3.0 sass_0.5.0 tools_4.6.2
#> [19] yaml_2.3.12 knitr_1.52 labeling_0.4.3
#> [22] S4Arrays_1.15.0 bit_4.6.0 curl_8.2.0
#> [25] DelayedArray_0.41.0 RColorBrewer_1.1-3 abind_1.4-8
#> [28] BiocParallel_1.49.0 purrr_1.2.2 withr_3.0.3
#> [31] sys_3.4.3 grid_4.6.2 ggplot2_4.0.4
#> [34] scales_1.4.0 cli_3.6.6 rmarkdown_2.32
#> [37] crayon_1.5.3 otel_0.3.0 httr_1.4.9
#> [40] rjson_0.2.23 BiocBaseUtils_1.17.0 DBI_1.4.0
#> [43] cachem_1.1.0 parallel_4.6.2 AnnotationDbi_1.77.1
#> [46] BiocManager_1.30.27 XVector_0.55.0 vctrs_0.7.3
#> [49] Matrix_1.7-6 jsonlite_2.0.0 bit64_4.8.6
#> [52] maketools_1.3.2 magick_2.9.1 jquerylib_0.1.4
#> [55] glue_1.8.1 codetools_0.2-20 gtable_0.3.6
#> [58] BiocVersion_3.25.1 tibble_3.3.1 pillar_1.11.1
#> [61] rappdirs_0.3.4 htmltools_0.5.9 R6_2.6.1
#> [64] httr2_1.3.0 evaluate_1.0.5 lattice_0.23-1
#> [67] png_0.1-9 memoise_2.0.1 bslib_0.12.0
#> [70] Rcpp_1.1.2 SparseArray_1.15.0 xfun_0.63
#> [73] buildtools_1.0.0 pkgconfig_2.0.3