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 p-value and its adjusted p-value are
written to rowData() of the input object.
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. Moran’s I is the classical autocorrelation statistic.
spatialLagGLM is a simpler regression-style alternative.
What it offers is:
SpatialExperiment you pass
in;design formula, so that the lag is tested while
adjusting for colData variables such as a cluster or
condition;What it does not offer is the statistical track record of the methods
above. The p-values come from a quasi-Poisson fit that has not been
shown to be calibrated for this test (see Checking calibration and Limitations). If you need a well-established SVG
test, use one of the packages above; use spatialLagGLM for
exploratory screening and for 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 null hypothesis is \(\gamma = 0\): given the offset and the design terms, the expression at a spot is not associated with the weighted mean of the normalised expression of its neighbours. The effect size reported is \(\hat\gamma\).
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 p_value adjusted_p_value
#> <numeric> <numeric> <numeric>
#> Gene1 -0.000299181 0.7531493 0.998085
#> Gene2 0.029788392 0.0255892 0.296740
#> Gene3 -0.002536482 0.8530038 0.998085designcolData variables,
e.g. ~ condition. Use ~ 1 for no adjustment.
With ~ condition, the lag is tested 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", "p_value")
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 p_value
#> ~ condition -0.0002991805 7.531493e-01
#> ~ 1 0.0245069855 1.085077e-205radiusspatialCoords(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_sizep_valueadjusted_p_valuep_value across genes.
NA 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.
Two points on interpretation. First, the effect size is in units of normalised counts, so it depends on how highly a gene is expressed: a highly expressed gene has a smaller \(\hat\gamma\) for the same relative pattern. Compare genes by p-value, not by effect size, and treat the effect size cutoff in the volcano plot as a display choice. Second, the p-values are exploratory (see below).
plotSpatialLag() draws a gene on the tissue coordinates,
either as raw counts or as its spatial lag (the covariate used in the
model).
plotLagVolcano() shows effect size against adjusted
p-value for all genes.
An interactive explorer combining both is available with
runSpatialLagExplorer(res0) (requires the
shiny package).
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 conclusions do 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", "p_value", "adjusted_p_value"
)]
)
head(tab[order(tab$p_value), ], 5)
#> spatial_effect_size p_value adjusted_p_value
#> ENSG00000198804 0.008430688 0 0
#> ENSG00000198712 0.008871279 0 0
#> ENSG00000198938 0.009816672 0 0
#> ENSG00000198899 0.012239997 0 0
#> ENSG00000198888 0.011995452 0 0top_gene <- rownames(tab)[which.min(tab$p_value)]
plotSpatialLag(res_real, top_gene, metric = "spatial_lag")The quasi-Poisson p-values have not been shown to be calibrated for this test, so check them on your data. The mock data gives a first look: genes 2 to 50 have no spatial pattern, so under a calibrated test about 5% of their p-values would fall below 0.05.
null_p <- rd(res0)$p_value[-1]
mean(null_p < 0.05)
#> [1] 0.1632653
hist(null_p,
breaks = 20, main = "Genes 2-50 (no spatial pattern)",
xlab = "p-value"
)In a simulation by the package author (independent negative binomial
genes on this grid, design ~ 1, 40 replicates), about 18%
of null p-values were below 0.05. The p-values are therefore
anti-conservative and a small p-value should not be
read as 0.05-level evidence.
A permutation null gives an empirical reference. Permuting the spots (columns) of the count matrix keeps each spot’s library size but breaks any link between expression and location. Running the method on permuted data shows what p-values to expect from no spatial signal:
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_p <- rd(res_perm)$p_value
obs_p <- rd(res0)$p_value
mean(perm_p < 0.05)
#> [1] 0.28
## Empirical p-value: how often a permuted gene is at least as extreme.
emp_p <- vapply(
obs_p, function(p) {
(1 + sum(perm_p <= p)) / (1 + length(perm_p))
},
numeric(1)
)
emp_p["Gene1"]
#> [1] NAWith only 50 genes the permutation null is coarse. With a full dataset, pool several permutations and use the pooled p-values the same way.
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.21.1 ExperimentHub_3.3.2
#> [3] AnnotationHub_4.3.3 BiocFileCache_3.3.3
#> [5] dbplyr_2.6.0 SpatialExperiment_1.25.0
#> [7] SingleCellExperiment_1.35.2 SummarizedExperiment_1.45.0
#> [9] Biobase_2.73.2 GenomicRanges_1.67.0
#> [11] Seqinfo_1.5.0 IRanges_2.47.5
#> [13] S4Vectors_0.53.0 BiocGenerics_0.59.13
#> [15] generics_0.1.4 MatrixGenerics_1.27.0
#> [17] matrixStats_1.5.0 spatialLagGLM_0.99.4
#> [19] BiocStyle_2.41.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.81.9 fastmap_1.2.0
#> [10] digest_0.6.39 lifecycle_1.0.5 KEGGREST_1.53.6
#> [13] RSQLite_3.53.3 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.39.8 RColorBrewer_1.1-3 abind_1.4-8
#> [28] BiocParallel_1.47.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.3.0
#> [43] cachem_1.1.0 parallel_4.6.2 AnnotationDbi_1.77.0
#> [46] BiocManager_1.30.27 XVector_0.53.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.0 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.62
#> [73] buildtools_1.0.0 pkgconfig_2.0.3