| Title: | Cell-Type-Resolved Exposome-Wide Association Studies for Single-Cell RNA-seq |
|---|---|
| Description: | Tests donor-level environmental exposures for association with gene expression within cell types in single-cell RNA-seq cohorts (single-cell exposome-wide association studies, sc-ExWAS). The package extends SingleCellExperiment to hold donor-level exposure measurements alongside the cells, and aggregates raw counts by donor and cell type so that the donor, not the cell, is the unit of inference (Squair et al. 2021 <doi:10.1038/s41467-021-25960-2>). The default analysis fits robust edgeR quasi-likelihood models with exposure-independent expression filtering, complete-transcriptome library sizes, design-rank checks and multiplicity correction across all genes and cell types; DESeq2 and voom-dream backends are also available. Further functions cover several exposures at once, donor-level cell-type composition, dose-response curves, exposure mixtures, meta-analysis across cohorts, power calculation, gene set testing with fgsea and imputation below the limit of detection. Exploratory functions estimate cross-omic networks within a cell type. All results are associations; the package does not identify causal effects. |
| Authors: | Cuiwei Gao [aut, cre, cph] (ORCID: <https://orcid.org/0009-0002-4896-0601>) |
| Maintainer: | Cuiwei Gao <[email protected]> |
| License: | Artistic-2.0 |
| Version: | 0.99.4 |
| Built: | 2026-11-27 22:34:27 UTC |
| Source: | https://github.com/bioc/exposomeSC |
Tests donor-level exposures for association with gene expression within cell types, with the donor as the unit of inference. Results are associations; the package does not identify causal effects.
build_sceeBuild a SingleCellExposomeExperiment from SCE + exposure matrix
run_sc_exwasCell-type-specific ExWAS via pseudobulk (edgeR, DESeq2 or voom-dream backend)
run_sc_exwas_pb_offsetNegative binomial model of the pseudobulk counts with a donor offset
run_sc_exwas_glmmMixed model of the cells with donor random effects, linear by default
run_multi_exwasBatch ExWAS across multiple exposures with global FDR
donor_pseudobulkDonor pseudobulk counts per cell type as SummarizedExperiment objects
run_dose_responsePolynomial dose-response (AIC selection)
run_dose_response_gamGAM dose-response via mgcv
run_sc_mixtureQuantile-scored mixture screening
run_mixture_qgcompQuantile g-computation with qgcomp
run_interaction_testExposure x celltype interaction F-test
run_cell_couplingGene-protein coupling via meta-regression with confounders
run_gseaPathway enrichment via fgsea
run_meta_exwasCross-cohort meta-analysis (fixed/random effects)
estimate_powerPower/sample size calculator
run_exposure_compositionExposure association with donor-level cell-type composition
run_celltype_networkCell-type-resolved network of transcripts and donor-level molecular measurements
run_exposure_networkNetwork restricted to exposure-associated features
run_comparative_networkDescriptive comparison of networks across cell types
simulate_crossomic_networkSimulated data with a known network
plot_celltype_network,
plot_network_comparison,
plot_edge_stability
Plots
exposure_impute_lodBelow-LOD imputation
as_sceeConvert from rexposome
seurat_to_exposureExtract from Seurat
Maintainer: Cuiwei Gao [email protected] (ORCID) [copyright holder]
Squair JW et al. (2021). Confronting false discoveries in single-cell differential expression. Nat Commun 12:5692. doi:10.1038/s41467-021-25960-2
Aitchison J (1986). The Statistical Analysis of Compositional Data. Chapman and Hall.
Useful links:
Bridges the bulk exposome ecosystem with single-cell
analysis by extracting the exposure matrix from an
ExposomeSet (rexposome) and combining it with
a SingleCellExperiment.
as_scee(exposome_set, sce, sample_col, exposures = NULL)as_scee(exposome_set, sce, sample_col, exposures = NULL)
exposome_set |
An |
sce |
A |
sample_col |
Character. Column in |
exposures |
Character vector (optional). Subset of exposures to include; a name that the ExposomeSet does not have is an error. Default: all. |
This function enables a common workflow: researchers have
existing bulk exposome data in rexposome format and want
to add single-cell resolution. The exposure matrix and
metadata are extracted from the ExposomeSet and
combined with the SCE to create an SCEE.
Every sample in colData(sce)[[sample_col]] must be present
in the ExposomeSet; ExposomeSet samples without cells are dropped.
A SingleCellExposomeExperiment.
Hernandez-Ferrer C et al. (2019). Comprehensive study of the exposome and omic data using rexposome Bioconductor packages. Bioinformatics 35:5344-5345.
if (requireNamespace("Biobase", quietly = TRUE)) { ## as_scee() needs only what an ExposomeSet is: a Biobase eSet whose ## assayData element "exp" holds exposures (rows) by samples ## (columns). A minimal eSet of that shape stands in here; an object ## from rexposome::loadExposome() is converted the same way. setClass("ExposomeSetExample", contains = "eSet") samples <- paste0("D", 1:4) exposures <- matrix(c(12, 25, 8, 30, 0.4, 0.9, 0.2, 1.1), nrow = 2, byrow = TRUE, dimnames = list(c("PM2.5", "Pb"), samples)) es <- methods::new("ExposomeSetExample", assayData = Biobase::assayDataNew("environment", exp = exposures), phenoData = Biobase::AnnotatedDataFrame( data.frame(sex = c(0, 1, 0, 1), row.names = samples)), featureData = Biobase::AnnotatedDataFrame( data.frame(family = c("air", "metal"), row.names = c("PM2.5", "Pb")))) sce <- SingleCellExperiment::SingleCellExperiment( assays = list(counts = matrix(1L, nrow = 5, ncol = 8, dimnames = list(paste0("G", 1:5), paste0("c", 1:8)))), colData = S4Vectors::DataFrame( cell_id = paste0("c", 1:8), donor_id = rep(samples, each = 2))) scee <- as_scee(es, sce, sample_col = "donor_id") exposureData(scee) exposureInfo(scee) }if (requireNamespace("Biobase", quietly = TRUE)) { ## as_scee() needs only what an ExposomeSet is: a Biobase eSet whose ## assayData element "exp" holds exposures (rows) by samples ## (columns). A minimal eSet of that shape stands in here; an object ## from rexposome::loadExposome() is converted the same way. setClass("ExposomeSetExample", contains = "eSet") samples <- paste0("D", 1:4) exposures <- matrix(c(12, 25, 8, 30, 0.4, 0.9, 0.2, 1.1), nrow = 2, byrow = TRUE, dimnames = list(c("PM2.5", "Pb"), samples)) es <- methods::new("ExposomeSetExample", assayData = Biobase::assayDataNew("environment", exp = exposures), phenoData = Biobase::AnnotatedDataFrame( data.frame(sex = c(0, 1, 0, 1), row.names = samples)), featureData = Biobase::AnnotatedDataFrame( data.frame(family = c("air", "metal"), row.names = c("PM2.5", "Pb")))) sce <- SingleCellExperiment::SingleCellExperiment( assays = list(counts = matrix(1L, nrow = 5, ncol = 8, dimnames = list(paste0("G", 1:5), paste0("c", 1:8)))), colData = S4Vectors::DataFrame( cell_id = paste0("c", 1:8), donor_id = rep(samples, each = 2))) scee <- as_scee(es, sce, sample_col = "donor_id") exposureData(scee) exposureInfo(scee) }
Combines a SingleCellExperiment with sample-level
exposure measurements into a unified container for sc-ExWAS.
build_scee(sce, exposure_matrix, sample_col, exposure_info = NULL)build_scee(sce, exposure_matrix, sample_col, exposure_info = NULL)
sce |
|
exposure_matrix |
Numeric matrix. Rows = samples,
columns = exposure variables, with unique row and column names.
The row names must be exactly the sample IDs in
|
sample_col |
Character. Column in |
exposure_info |
|
A SingleCellExposomeExperiment.
library(SingleCellExperiment) library(S4Vectors) set.seed(1) counts <- matrix(rpois(2000, 5), nrow = 50, dimnames = list(paste0("G", 1:50), paste0("c", 1:40))) sce <- SingleCellExperiment( assays = list(counts = counts), colData = DataFrame( cell_id = paste0("c", seq_len(40)), donor_id = rep(paste0("D", 1:4), each = 10), cell_type = rep(c("Mono", "NK"), 20))) exp_mat <- matrix(rnorm(12), nrow = 4, dimnames = list(paste0("D", 1:4), c("PM2.5", "Pb", "BPA"))) scee <- build_scee(sce, exp_mat, sample_col = "donor_id") sceelibrary(SingleCellExperiment) library(S4Vectors) set.seed(1) counts <- matrix(rpois(2000, 5), nrow = 50, dimnames = list(paste0("G", 1:50), paste0("c", 1:40))) sce <- SingleCellExperiment( assays = list(counts = counts), colData = DataFrame( cell_id = paste0("c", seq_len(40)), donor_id = rep(paste0("D", 1:4), each = 10), cell_type = rep(c("Mono", "NK"), 20))) exp_mat <- matrix(rnorm(12), nrow = 4, dimnames = list(paste0("D", 1:4), c("PM2.5", "Pb", "BPA"))) scee <- build_scee(sce, exp_mat, sample_col = "donor_id") scee
CelltypeNetwork: virtual base class for cell-type networks
showClass("CelltypeNetwork")showClass("CelltypeNetwork")
Wraps a network estimated elsewhere, or built by hand, in a
CelltypeNetworkResult so that it can be compared
with run_comparative_network and plotted. The networks
returned by run_celltype_network and
run_exposure_network are already of this class.
CelltypeNetworkResult( precision, adjacency, node_info, celltype, method = "precomputed", stability = NULL, metadata = list() )CelltypeNetworkResult( precision, adjacency, node_info, celltype, method = "precomputed", stability = NULL, metadata = list() )
precision |
Numeric square matrix: the precision (inverse covariance) matrix, one row and column per feature. |
adjacency |
Symmetric matrix of edge indicators (1 = edge, 0 = no
edge) with the dimensions of |
node_info |
|
celltype |
Character scalar: the cell type. |
method |
Character scalar: how the network was estimated. Default
|
stability |
Optional matrix of edge selection frequencies between 0
and 1 with the dimensions of |
metadata |
List of further information, for example
|
A valid CelltypeNetworkResult.
features <- c("G1", "G2", "M1") precision <- diag(3) precision[1, 3] <- precision[3, 1] <- -0.4 adjacency <- (precision != 0) * 1L diag(adjacency) <- 0L dimnames(precision) <- dimnames(adjacency) <- list(features, features) network <- CelltypeNetworkResult( precision = precision, adjacency = adjacency, node_info = S4Vectors::DataFrame( feature = features, omic_layer = c("transcript", "transcript", "metabolite")), celltype = "Monocyte", metadata = list(n_donors = 20L)) networkfeatures <- c("G1", "G2", "M1") precision <- diag(3) precision[1, 3] <- precision[3, 1] <- -0.4 adjacency <- (precision != 0) * 1L diag(adjacency) <- 0L dimnames(precision) <- dimnames(adjacency) <- list(features, features) network <- CelltypeNetworkResult( precision = precision, adjacency = adjacency, node_info = S4Vectors::DataFrame( feature = features, omic_layer = c("transcript", "transcript", "metabolite")), celltype = "Monocyte", metadata = list(n_donors = 20L)) network
Stores the estimated precision matrix, adjacency matrix,
stability scores, and node metadata from
run_celltype_network and
run_exposure_network. Use the accessors in
network-accessors to extract them, and
CelltypeNetworkResult() to wrap a network estimated
elsewhere.
## S4 method for signature 'CelltypeNetworkResult' show(object)## S4 method for signature 'CelltypeNetworkResult' show(object)
object |
A |
The show method prints a summary and returns
NULL invisibly.
precision_matrixNumeric matrix. Estimated block precision (inverse covariance) matrix.
adjacency_matrixNumeric matrix. Symmetric binary edge
indicators (1 = edge present, 0 = absent) with the dimensions of
precision_matrix and a zero diagonal.
stability_scoresNumeric matrix. Edge-level selection
frequencies (0-1) across the XStARS subsamples at the selected
penalties, for coglasso networks built with stability = TRUE.
Empty otherwise.
node_infoDataFrame. Maps each node (row/col
index) to its omic layer ("transcript" or "metabolite"),
feature name, and optional module/community assignment. It has
one row per node, in matrix order; when the matrices have row or
column names, these must equal its feature column.
celltypeCharacter. The cell type this network represents.
methodCharacter. Estimation method: "coglasso" or
"block_glasso" from run_celltype_network(),
"exposure_restricted" from run_exposure_network(), or
"precomputed" for a network supplied by the user.
metadataList. Additional parameters: n_donors, n_features, lambda values, exposure, covariates.
network-accessors,
CelltypeNetworkResult
showClass("CelltypeNetworkResult")showClass("CelltypeNetworkResult")
Sums the raw counts of each cell type within each donor and returns one
SummarizedExperiment per cell type, with the donors' exposure data
as column data. These are the pseudobulk counts that
run_sc_exwas and the other pseudobulk functions of the
package aggregate internally, so they can be passed to other
Bioconductor tools, inspected, or plotted.
donor_pseudobulk( x, celltype_col = "cell_type", celltypes = NULL, min_cells = 10L )donor_pseudobulk( x, celltype_col = "cell_type", celltypes = NULL, min_cells = 10L )
x |
A |
celltype_col |
Character. Column in |
celltypes |
Character vector (optional). Cell types to aggregate. Default: all non-missing labels, sorted. |
min_cells |
Integer. A donor is included for a cell type only when
it has at least this many cells of that type. Default 10, the default
of |
The summation is done by scrapper::aggregateAcrossCells(). Donors
with missing exposure values are kept here; the analysis functions drop
them, and filter genes, when they fit a model, so a fitted model may use
fewer donors and genes than the object returned here. Model diagnostics
(metadata() of the run_sc_exwas result) list the donors and
gene counts actually used.
A SimpleList named by cell type. Each
element is a SummarizedExperiment
with one column per included donor and
an assay "counts" with the summed raw counts (features
by donors);
rowData copied from x;
colData with the donor identifier (donor_id),
the cell type (cell_type), the number of cells summed
(n_cells) and one column per variable of
exposureData(x);
metadata recording the cell type, min_cells and
the colData columns used for donors and cell types.
Cell types in which no donor reaches min_cells are left out and
listed in metadata(result)$skipped.
Lun ATL, Kancherla J (2023). Powering single-cell analyses in the browser with WebAssembly. Journal of Open Source Software 8(89):5603. doi:10.21105/joss.05603
library(SingleCellExperiment) library(S4Vectors) set.seed(1) counts <- matrix(rpois(2000, 5), nrow = 20, dimnames = list(paste0("G", 1:20), paste0("c", 1:100))) sce <- SingleCellExperiment(assays = list(counts = counts), colData = DataFrame(donor_id = rep(paste0("D", 1:5), each = 20), cell_type = rep(c("Mono", "NK"), 50))) exp_mat <- matrix(rnorm(5), ncol = 1, dimnames = list(paste0("D", 1:5), "E1")) scee <- build_scee(sce, exp_mat, sample_col = "donor_id") pb <- donor_pseudobulk(scee, min_cells = 5L) pb SummarizedExperiment::colData(pb[["Mono"]])library(SingleCellExperiment) library(S4Vectors) set.seed(1) counts <- matrix(rpois(2000, 5), nrow = 20, dimnames = list(paste0("G", 1:20), paste0("c", 1:100))) sce <- SingleCellExperiment(assays = list(counts = counts), colData = DataFrame(donor_id = rep(paste0("D", 1:5), each = 20), cell_type = rep(c("Mono", "NK"), 50))) exp_mat <- matrix(rnorm(5), ncol = 1, dimnames = list(paste0("D", 1:5), "E1")) scee <- build_scee(sce, exp_mat, sample_col = "donor_id") pb <- donor_pseudobulk(scee, min_cells = 5L) pb SummarizedExperiment::colData(pb[["Mono"]])
Approximates the power to detect a donor-level exposure effect on one gene in one cell type at the pseudobulk level, for a range of donor numbers.
estimate_power( n_donors = seq(10, 100, by = 10), effect_size = 0.5, n_genes = 5000L, n_celltypes = 5L, alpha = 0.05, dispersion = 0.1, base_mean = 100, exposure_sd = 1 )estimate_power( n_donors = seq(10, 100, by = 10), effect_size = 0.5, n_genes = 5000L, n_celltypes = 5L, alpha = 0.05, dispersion = 0.1, base_mean = 100, exposure_sd = 1 )
n_donors |
Integer vector. Donor sample sizes to
evaluate. Default: |
effect_size |
Numeric. Expected log2 fold change per unit exposure. Default 0.5. |
n_genes |
Integer. Number of genes tested (for multiple testing correction). Default 5000. |
n_celltypes |
Integer. Number of cell types tested. Default 5. |
alpha |
Numeric. Family-wise significance level; the per-test level
is |
dispersion |
Numeric. Negative-binomial dispersion |
base_mean |
Numeric. Mean donor pseudobulk count |
exposure_sd |
Numeric. Standard deviation of the
exposure variable across donors. Default 1
(standardised). For a binary exposure that a proportion |
For a negative-binomial GLM with a log link, the large-sample standard
error of the exposure coefficient on the scale is
where is exposure_sd and the number of donors.
Power is that of a two-sided Wald test at the Bonferroni per-test level.
The approximation treats the dispersion as known and uses the normal
distribution, so it is optimistic for small numbers of donors; simulate
from the planned design when an accurate figure matters. Bonferroni is
conservative relative to Benjamini-Hochberg control of the false
discovery rate.
Pseudobulk inference has donors, not cells, as its independent units.
More cells per donor raise and so shrink the term,
but they do not increase .
A DataFrame with columns: n_donors, power,
effect_size, exposure_sd, n_tests, alpha_adjusted, dispersion,
base_mean.
Squair JW et al. (2021). Confronting false discoveries in single-cell differential expression. Nat Commun 12:5692.
pw <- estimate_power(n_donors = seq(10, 50, by = 10), effect_size = 0.5, n_genes = 2000, n_celltypes = 3) pwpw <- estimate_power(n_donors = seq(10, 50, by = 10), effect_size = 0.5, n_genes = 2000, n_celltypes = 3) pw
Environmental exposure measurements often contain values reported only as below the limit of detection (LOD), that is, left-censored values. This function replaces them by substitution, by regression on order statistics or by multiple imputation from a censored log-normal model. Missing values are kept apart from censored ones and are never imputed.
exposure_impute_lod( exposure_matrix, lod, method = c("lod_sqrt2", "lod_2", "ros", "multiple"), censored = NULL, M = 5L, verbose = TRUE )exposure_impute_lod( exposure_matrix, lod, method = c("lod_sqrt2", "lod_2", "ros", "multiple"), censored = NULL, M = 5L, verbose = TRUE )
exposure_matrix |
Numeric matrix. Rows = samples,
columns = exposure variables. In the exposures named in |
lod |
Named numeric vector of positive, finite detection limits, one
per exposure. Names must match column names of
|
method |
Character. Imputation method:
|
censored |
|
M |
Integer. Number of imputations (only for
|
verbose |
Logical. Report the numbers of censored and missing values per exposure. Default TRUE. |
Substitution is simple, but it distorts variances and associations, increasingly so as the censored fraction grows (Lubin et al. 2004).
ROS. With a single detection limit every censored value lies
below every detected value, so the censored values take the lowest ranks
among the non-missing values of the exposure. Blom plotting positions
are computed for all non-missing
values, the logarithms of the detected values are regressed on the normal
quantiles of their plotting positions, and each censored value is
replaced by the value of the fitted line at one of the lowest plotting
positions, capped just below the LOD (Helsel 2012). ROS reproduces the
distribution of the censored values, not their individual values: the
imputed values are assigned to the censored samples in row order, so they
carry no information on which censored sample had the larger true value.
Use the ROS values for summaries of the distribution; for association
analyses prefer method = "multiple". ROS is not the reverse
Kaplan-Meier estimator, which is not implemented here.
Multiple imputation. For each of the M imputations the
non-missing values of an exposure are resampled with replacement, the
mean and standard deviation of the log values are estimated by maximum
likelihood with the censored values contributing
, and every censored value is drawn from the
fitted log-normal distribution truncated to . The
bootstrap step carries the uncertainty of the fitted distribution into
the imputations (Lubin et al. 2004). Analyse each completed matrix and
combine the estimates with Rubin's rules (Rubin 1987). The draws use the
random-number stream of the session, so call set.seed() first for
reproducible imputations. If the fit fails for an exposure even on its
observed values, an error names it; impute that exposure with another
method.
ROS and multiple imputation assume a log-normal distribution and need at
least three detected values; an exposure with fewer is imputed with
LOD / sqrt(2), with a warning, and this is recorded in
lod_summary. An exposure with more than 80% of its non-missing
values censored gives a warning.
Other implementations: rexposome::ilod() and
rexposome::imputeLOD() impute values below the LOD with the QRILC
or MinProb methods of the imputeLCMD package, which are not the
methods offered here.
For method != "multiple": the numeric matrix with censored
values replaced, of the same dimensions as the input. For
method = "multiple": an S4Vectors::SimpleList of M
such matrices. In both cases a data.frame with one row per
exposure of lod that is a column of exposure_matrix
(exposure, n_detected,
n_censored, n_missing, method) records what was
done; it is the "lod_summary" attribute of the matrix, or
metadata(result)$lod_summary for the list.
Lubin JH, Colt JS, Camann D, et al. (2004). Epidemiologic evaluation of measurement data in the presence of detection limits. Environ Health Perspect 112(17):1691–1696. doi:10.1289/ehp.7199
Helsel DR (2012). Statistics for Censored Environmental Data Using Minitab and R. 2nd ed. Wiley. doi:10.1002/9781118162729
Rubin DB (1987). Multiple Imputation for Nonresponse in Surveys. Wiley. doi:10.1002/9780470316696
set.seed(1) mat <- matrix(rlnorm(200, 0, 1), nrow = 40, ncol = 5, dimnames = list(paste0("S", 1:40), c("Pb", "Cd", "Hg", "As", "BPA"))) lod <- c(Pb = 0.5, Cd = 0.3, Hg = 0.2, As = 0.1, BPA = 0.4) ## Values reported as below the LOD, and one genuinely missing value censored <- sweep(mat, 2, lod[colnames(mat)], "<") mat[censored] <- NA mat["S1", "Pb"] <- NA censored["S1", "Pb"] <- FALSE imputed <- exposure_impute_lod(mat, lod, method = "ros", censored = censored) attr(imputed, "lod_summary") imputations <- exposure_impute_lod(mat, lod, method = "multiple", censored = censored, M = 3L, verbose = FALSE) length(imputations)set.seed(1) mat <- matrix(rlnorm(200, 0, 1), nrow = 40, ncol = 5, dimnames = list(paste0("S", 1:40), c("Pb", "Cd", "Hg", "As", "BPA"))) lod <- c(Pb = 0.5, Cd = 0.3, Hg = 0.2, As = 0.1, BPA = 0.4) ## Values reported as below the LOD, and one genuinely missing value censored <- sweep(mat, 2, lod[colnames(mat)], "<") mat[censored] <- NA mat["S1", "Pb"] <- NA censored["S1", "Pb"] <- FALSE imputed <- exposure_impute_lod(mat, lod, method = "ros", censored = censored) attr(imputed, "lod_summary") imputations <- exposure_impute_lod(mat, lod, method = "multiple", censored = censored, M = 3L, verbose = FALSE) length(imputations)
Get and set the donor-level exposure data of a
SingleCellExposomeExperiment and the column of
colData that links cells to donors.
exposureData(x) exposureInfo(x) cellSampleMap(x) sampleColumn(x) sampleColumn(x) <- value exposureVariables(x) exposureData(x) <- value exposureInfo(x) <- value ## S4 method for signature 'SingleCellExposomeExperiment' exposureData(x) ## S4 method for signature 'SingleCellExposomeExperiment' exposureInfo(x) ## S4 method for signature 'SingleCellExposomeExperiment' cellSampleMap(x) ## S4 method for signature 'SingleCellExposomeExperiment' sampleColumn(x) ## S4 replacement method for signature 'SingleCellExposomeExperiment' sampleColumn(x) <- value ## S4 method for signature 'SingleCellExposomeExperiment' exposureVariables(x) ## S4 replacement method for signature 'SingleCellExposomeExperiment' exposureData(x) <- value ## S4 replacement method for signature 'SingleCellExposomeExperiment' exposureInfo(x) <- valueexposureData(x) exposureInfo(x) cellSampleMap(x) sampleColumn(x) sampleColumn(x) <- value exposureVariables(x) exposureData(x) <- value exposureInfo(x) <- value ## S4 method for signature 'SingleCellExposomeExperiment' exposureData(x) ## S4 method for signature 'SingleCellExposomeExperiment' exposureInfo(x) ## S4 method for signature 'SingleCellExposomeExperiment' cellSampleMap(x) ## S4 method for signature 'SingleCellExposomeExperiment' sampleColumn(x) ## S4 replacement method for signature 'SingleCellExposomeExperiment' sampleColumn(x) <- value ## S4 method for signature 'SingleCellExposomeExperiment' exposureVariables(x) ## S4 replacement method for signature 'SingleCellExposomeExperiment' exposureData(x) <- value ## S4 replacement method for signature 'SingleCellExposomeExperiment' exposureInfo(x) <- value
x |
|
value |
For |
exposureData()Numeric matrix, samples by exposures.
exposureInfo()DataFrame with one row per exposure.
exposureVariables()Character vector of exposure names.
sampleColumn()Character scalar: the colData
column holding each cell's sample (donor) ID. The analysis functions
read each cell's donor from this column.
cellSampleMap()DataFrame with columns
cell_id (the cell names) and sample_id, derived from
that column.
The modified object, after a validity check.
library(SingleCellExperiment) counts <- matrix(1L, nrow = 5, ncol = 12, dimnames = list(paste0("G", 1:5), paste0("c", 1:12))) sce <- SingleCellExperiment(assays = list(counts = counts), colData = S4Vectors::DataFrame( cell_id = paste0("c", 1:12), donor_id = rep(paste0("D", 1:4), each = 3))) exp_mat <- matrix(c(12, 25, 8, 30, 45, 32, 67, 51), nrow = 4, dimnames = list(paste0("D", 1:4), c("PM2.5", "age"))) scee <- build_scee(sce, exp_mat, sample_col = "donor_id") exposureVariables(scee) exposureData(scee) exposureInfo(scee) sampleColumn(scee) head(cellSampleMap(scee)) ## Replace the exposure matrix, here rescaling PM2.5 exp_new <- exposureData(scee) exp_new[, "PM2.5"] <- exp_new[, "PM2.5"] / 10 exposureData(scee) <- exp_new exposureData(scee)[, "PM2.5"]library(SingleCellExperiment) counts <- matrix(1L, nrow = 5, ncol = 12, dimnames = list(paste0("G", 1:5), paste0("c", 1:12))) sce <- SingleCellExperiment(assays = list(counts = counts), colData = S4Vectors::DataFrame( cell_id = paste0("c", 1:12), donor_id = rep(paste0("D", 1:4), each = 3))) exp_mat <- matrix(c(12, 25, 8, 30, 45, 32, 67, 51), nrow = 4, dimnames = list(paste0("D", 1:4), c("PM2.5", "age"))) scee <- build_scee(sce, exp_mat, sample_col = "donor_id") exposureVariables(scee) exposureData(scee) exposureInfo(scee) sampleColumn(scee) head(cellSampleMap(scee)) ## Replace the exposure matrix, here rescaling PM2.5 exp_new <- exposureData(scee) exp_new[, "PM2.5"] <- exp_new[, "PM2.5"] / 10 exposureData(scee) <- exp_new exposureData(scee)[, "PM2.5"]
A SingleCellExposomeExperiment with the raw counts
of 352 tracheal epithelial cells from 12 donors of the Human Lung Cell
Atlas (HLCA) core: six heavy smokers and six never smokers, with up to 10
basal, 10 secretory and 10 multiciliated-lineage cells per donor. It is a
small real data set for the vignettes and the tests. It
shows how the functions are used on real counts; with 12 donors and at
most 10 cells per donor and cell type it is far too small to support
conclusions about smoking.
An RDS file, inst/extdata/hlca_airway_subset.rds, read with
readRDS(system.file("extdata", "hlca_airway_subset.rds",
package = "exposomeSC")).
Study "Seibold_2020" of the HLCA core (Goldfarbmuren
et al. 2020): the heavy smokers T85, T90, T101, T120, T154 and T167
(smokers with at least 15 pack-years) and the never smokers T126,
T137, T153, T164, T165 and T166, the two groups that the authors
compare, as classified in their public metadata. The other two donors
of the study in the atlas, a light smoker and a child who never
smoked, are left out. Cells annotated "Basal",
"Secretory" or "Multiciliated lineage" at HLCA
annotation level 3 were eligible, and up to 10 per donor and cell type
were drawn at random with a fixed seed, without looking at expression;
donor T154 has only two multiciliated-lineage cells. The donors and
the cell types were fixed before any result on cells of these donors
was seen. The number of cells per donor and cell type was set later,
by the size limit of a Bioconductor source package: before this subset
was drawn, but after the smoking model had been run on larger sets of
cells of the same donors.
assay(x, "counts"): the raw counts of the H5AD
(/raw/X), 20,111 genes by 352 cells, as a sparse matrix. Genes
without a count in these cells are left out, so the column sums are
those of the complete transcriptome. The rows are Ensembl gene
identifiers. rowData(x)$symbol holds the gene names of the
atlas (feature_name): for 2,301 genes that name is the Ensembl
identifier again, and three names (MATR3, RAET1E-AS1 and SPATA13) are
each on two rows.
colData(x): donor_id (the donor
code of the study), cell_type, assay (10x 3' v2 or v3)
and hlca_donor_id (the donor identifier of the HLCA).
exposureData(x), one row per donor:
smoking (1 = heavy smoker, 0 = never smoker),
chemistry_v3 (1 = 10x 3' v3, 0 = 10x 3' v2), age (years)
and sex_male (1 = male, 0 = female).
metadata(x)$source: the URL, dataset version,
size and SHA-256 of the H5AD, the licence, the references, the
selection rule and, in eligible_cells, the number of eligible
cells of each donor and cell type in the atlas (29,217 in all), from
which the cells of the subset were drawn.
The CELLxGENE H5AD of the HLCA core, dataset version
688185ad-11c2-4172-a53a-f4f1f4076860
(https://datasets.cellxgene.cziscience.com/688185ad-11c2-4172-a53a-f4f1f4076860.h5ad,
5,873,612,847 bytes, SHA-256
1cbdde1e513a31bdb6a3f70296e2d0612760d2af4032e239c94596ea87b44007),
distributed under the Creative Commons Attribution 4.0 International
licence (CC BY 4.0, https://creativecommons.org/licenses/by/4.0/).
The subset was made by inst/scripts/make_hlca_airway_subset.R,
which checks the file and carries out the selection described above.
Cells and genes were selected; the counts themselves are unchanged.
Sikkema L, et al. (2023). An integrated cell atlas of the lung in health and disease. Nature Medicine, 29, 1563-1577. doi:10.1038/s41591-023-02327-2
Goldfarbmuren KC, et al. (2020). Dissecting the cellular specificity of smoking effects and reconstructing lineages in the human airway epithelium. Nature Communications, 11, 2485. doi:10.1038/s41467-020-16239-z
x <- readRDS(system.file("extdata", "hlca_airway_subset.rds", package = "exposomeSC")) x table(x$donor_id, x$cell_type) exposureData(x) S4Vectors::metadata(x)$source$licencex <- readRDS(system.file("extdata", "hlca_airway_subset.rds", package = "exposomeSC")) x table(x$donor_id, x$cell_type) exposureData(x) S4Vectors::metadata(x)$source$licence
A SingleCellExposomeExperiment with the raw counts
of 1,032 blood mononuclear cells from 43 patients of the INCOV cohort
(Su et al. 2020) at their first blood draw: 14 monocytes and 10 T cells
per patient, with the counts of 192 antibodies for the same cells, four
of them isotype controls, 13 plasma compounds of exogenous origin among
the donor variables and 182 plasma metabolites of the same draw. It is a
small real data set for
the functions that need more than transcript counts: surface proteins,
exposure measurements with missing values, and a second omic layer
measured once per donor. It shows how these functions are used on real
data. With at most 14 cells per donor and cell type it is far too small
to support conclusions, and all its donors had an acute viral infection.
An RDS file, inst/extdata/incov_pbmc_subset.rds, read with
readRDS(system.file("extdata", "incov_pbmc_subset.rds",
package = "exposomeSC")).
Patients of the INCOV cohort who, at their first blood draw, had single cells, plasma metabolomics and plasma proteomics measured, a recorded history of cigarette smoking, and were not in hospital (WHO ordinal scale 1 or 2). 43 patients meet these conditions: 37 women and 6 men aged 19 to 81, 16 of them current or former smokers. The rule was fixed from the clinical sheet and the list of files before any single-cell value of these donors was read.
assay(x, "counts"): 15,406 genes by 1,032 cells,
as a sparse matrix; the rows are gene symbols. The archive holds the
natural logarithm of one plus the counts per million of each cell,
from which the counts were recovered: every value of a cell is a whole
multiple of the value of one count, and that value times the total of
the cell is one million, which the script checks for every cell. Genes
without a count in these cells are left out, so the column sums are
those of all 24,966 genes of the archive files. The authors had kept
cells with at least 200 genes, fewer than 10,000 counts, fewer than
2,500 genes and under 10 per cent mitochondrial counts.
altExp(x, "CITE"): the counts of 192
antibodies, four of them isotype controls, for the same cells,
recovered in the same way.
x$cell_type, assigned for this data set; the
archive holds no cell types. Each sample has two gates, one for the
protein CD3 and one for the sum of the proteins CD14, CD11c, CD33 and
CD64. A gate is the midpoint of the two centres that a split of the
cells into two groups by the logarithm of one plus the count gives. A
"T cell" has CD3 above its gate, the sum not above its gate,
and fewer than 10 counts of the genes LYZ, S100A8 and
S100A9 together. A "Monocyte" has the sum above its
gate, CD3 not above its gate, at least 5 counts of those three genes
and fewer than 3 counts of CD3D, CD3E and TRAC
together. Of the 63,865 cells of the 43 samples, 9,889 are monocytes
and 38,213 T cells by this rule. In one sample, INCOV132, the two
groups of the sum lie close together (its gate is 8.8 counts, the
lowest; the others are 12 or more): 121 of its 328 cells lie above
both gates and are neither kind, against fewer than a tenth of the
cells of any other sample, and of the 43 cells that the gates alone
would make monocytes the conditions on the genes keep 16. The rule was
chosen by how well
alternatives agreed with these genes in 42 of the samples and was
applied to the 43rd as it stood. The five proteins and six genes of
the rule are constrained by it and must not be read as results.
14 monocytes and 10 T cells per donor, drawn at random with a fixed seed from the cells of each kind. The two numbers were set by the size limit of a Bioconductor source package.
colData(x): donor_id (the
patient identifier of the study), cell_type, sample_id
(the name of the sample in the archive, the patient identifier
followed by -BL) and archive_cell (the name of the cell
in the files of the archive). The column names of the object are the
patient identifier and the barcode of the cell. The rows are named by
gene symbol, which rowData(x)$symbol repeats.
exposureData(x), one row per donor:
ever_smoker (1 = current or former smoker, 0 = never smoker),
age (years), sex_male (1 = male, 0 = female), and the
plasma levels of 13 compounds of exogenous origin: cotinine;
caffeine, paraxanthine and theobromine;
pfos and pfoa (perfluorooctanesulfonate and
perfluorooctanoate); methylparaben_sulfate and
propylparaben_sulfate; hydroxychlorothalonil;
naphthol_sulfate; ethyl_glucuronide; saccharin
and acesulfame. The levels are relative abundances, scaled by
the authors so that the median of a compound within a batch is 1, and
NA where the table has no value for the sample. Ten of the 13
compounds lack a value for at least one donor: cotinine has a value
for only 5 donors, propylparaben sulfate for 17, acesulfame for 19 and
saccharin for 27. The table does not say why a value is missing. In
measurements of this kind the usual reason is that the compound was
not detected in the sample, but it is not the only one: the table
also lacks a value of glucose for one of these donors.
exposureInfo(x) gives the name of each compound in the source
table (source_name), its family, and lowest_reported,
the smallest value of the compound among the 387 samples of the table.
The table reports no limits of detection. For the metabolites that
they analysed, those with fewer than 20 per cent of the values
missing, the authors put this smallest value in place of a missing
one; six of the 13 compounds here have more missing values than that.
The 13 compounds were chosen by their kind, from their names and the
numbers of samples with a value.
metadata(x)$plasma_metabolites, 43
donors by 182 metabolites: the metabolites that the source table
assigns to a super-pathway other than xenobiotics and reports for all
43 donors, on the same relative scale. Their pathways are in
metadata(x)$metabolite_info.
metadata(x)$source: the reference, the
sources and their licences, the permission for the single-cell values
(single_cells$permission), the names, sizes and SHA-256 of the 88
input files, the selection rule, the gates of each sample
(gates) and the numbers of monocytes, T cells and other cells
of each donor (gated_cells).
The rule for the donors, the rule for the cell types, the numbers of cells and the seed were fixed before any association of a donor variable with expression, proteins or metabolites was computed on these donors. The object was first made from 42 of the 43 donors, because the first transfer of the expression file of one was incomplete, and the vignettes were first written on that version. It was then made again from all 43 by the script without that exclusion; the cells of the 14 donors that follow that donor in the order of the draw are a new random draw.
The clinical records and the plasma measurements are Table S1 of Mendeley Data, doi:10.17632/tzydswhhb5.5 (version 5, published on 4 November 2020), distributed under the Creative Commons Attribution 4.0 International licence (CC BY 4.0, https://creativecommons.org/licenses/by/4.0/). The plasma values were selected, not changed; smoking and sex were recoded as described above.
The single-cell values of genes and surface proteins are from ArrayExpress accession E-MTAB-9357 (https://www.ebi.ac.uk/biostudies/arrayexpress/studies/E-MTAB-9357), released on 29 October 2020 and downloaded on 19 November 2026. On 21 November 2026 the authors who deposited the accession gave permission in these words: "The single-cell values from E-MTAB-9357 included in exposomeSC may be used and redistributed under CC BY 4.0, with citation of Su et al. (2020)." The object holds a subset of the values that the authors released, transformed as described above.
The object as a whole is therefore distributed under CC BY 4.0. Work that uses it should cite Su et al. (2020). The permission does not imply that the authors endorse exposomeSC.
The article itself is published under CC BY-NC-ND 4.0. The values in this object come from the data that the authors deposited in Mendeley Data and ArrayExpress, not from the article.
The object was made by inst/scripts/make_incov_pbmc_subset.R,
which checks the size and the SHA-256 of every input file and carries
out the steps described above.
Su Y, Chen D, Yuan D, et al. (2020). Multi-omics resolves a sharp disease-state shift between mild and moderate COVID-19. Cell, 183(6), 1479-1495.e20. doi:10.1016/j.cell.2020.10.037
x <- readRDS(system.file("extdata", "incov_pbmc_subset.rds", package = "exposomeSC")) x table(x$cell_type) exposureData(x)[1:3, 1:6] SingleCellExperiment::altExp(x, "CITE") dim(S4Vectors::metadata(x)$plasma_metabolites) S4Vectors::metadata(x)$source$single_cells$licencex <- readRDS(system.file("extdata", "incov_pbmc_subset.rds", package = "exposomeSC")) x table(x$cell_type) exposureData(x)[1:3, 1:6] SingleCellExperiment::altExp(x, "CITE") dim(S4Vectors::metadata(x)$plasma_metabolites) S4Vectors::metadata(x)$source$single_cells$licence
Extract the parts of a CelltypeNetworkResult
(returned by run_celltype_network and
run_exposure_network) and of a
NetworkComparison (returned by
run_comparative_network).
networkPrecision(x) networkAdjacency(x) networkStability(x) networkNodes(x) networkCelltype(x) networkMethod(x) diffEdges(x) sharedEdges(x) celltypeSpecificEdges(x) comparisonSummary(x) ## S4 method for signature 'CelltypeNetworkResult' networkPrecision(x) ## S4 method for signature 'CelltypeNetworkResult' networkAdjacency(x) ## S4 method for signature 'CelltypeNetworkResult' networkStability(x) ## S4 method for signature 'CelltypeNetworkResult' networkNodes(x) ## S4 method for signature 'CelltypeNetworkResult' networkCelltype(x) ## S4 method for signature 'CelltypeNetworkResult' networkMethod(x) ## S4 method for signature 'CelltypeNetworkResult' metadata(x, ...) ## S4 method for signature 'NetworkComparison' diffEdges(x) ## S4 method for signature 'NetworkComparison' sharedEdges(x) ## S4 method for signature 'NetworkComparison' celltypeSpecificEdges(x) ## S4 method for signature 'NetworkComparison' comparisonSummary(x)networkPrecision(x) networkAdjacency(x) networkStability(x) networkNodes(x) networkCelltype(x) networkMethod(x) diffEdges(x) sharedEdges(x) celltypeSpecificEdges(x) comparisonSummary(x) ## S4 method for signature 'CelltypeNetworkResult' networkPrecision(x) ## S4 method for signature 'CelltypeNetworkResult' networkAdjacency(x) ## S4 method for signature 'CelltypeNetworkResult' networkStability(x) ## S4 method for signature 'CelltypeNetworkResult' networkNodes(x) ## S4 method for signature 'CelltypeNetworkResult' networkCelltype(x) ## S4 method for signature 'CelltypeNetworkResult' networkMethod(x) ## S4 method for signature 'CelltypeNetworkResult' metadata(x, ...) ## S4 method for signature 'NetworkComparison' diffEdges(x) ## S4 method for signature 'NetworkComparison' sharedEdges(x) ## S4 method for signature 'NetworkComparison' celltypeSpecificEdges(x) ## S4 method for signature 'NetworkComparison' comparisonSummary(x)
x |
A |
... |
Ignored by |
networkPrecision()Numeric feature-by-feature precision matrix.
networkAdjacency()Feature-by-feature matrix of edge indicators (1 = edge, 0 = no edge).
networkStability()Feature-by-feature matrix of edge selection frequencies, or a 0 by 0 matrix when none were stored.
networkNodes()DataFrame with one row per feature,
in the order of the matrix rows.
networkCelltype()Character scalar: the cell type.
networkMethod()Character scalar: the estimation method.
metadata()List of parameters and summaries, for example
n_donors, transform and edge_counts.
diffEdges()DataFrame of edges that are unique to
one cell type or present in some but not all networks.
sharedEdges()DataFrame of edges present in every
network.
celltypeSpecificEdges()Named list of DataFrames,
one per cell type with edges found only in that cell type.
comparisonSummary()List with the compared cell types, edge counts and pairwise Jaccard overlap.
features <- c("G1", "G2", "M1") make_network <- function(celltype, cross_weight) { precision <- diag(3) precision[1, 3] <- precision[3, 1] <- cross_weight adjacency <- (precision != 0) * 1L diag(adjacency) <- 0L dimnames(precision) <- dimnames(adjacency) <- list(features, features) CelltypeNetworkResult( precision = precision, adjacency = adjacency, node_info = S4Vectors::DataFrame( feature = features, omic_layer = c("transcript", "transcript", "metabolite")), celltype = celltype, metadata = list(n_donors = 20L)) } mono <- make_network("Monocyte", -0.45) networkCelltype(mono) networkAdjacency(mono) networkNodes(mono) metadata(mono)$n_donors comparison <- run_comparative_network(mono, make_network("B cell", 0)) diffEdges(comparison) celltypeSpecificEdges(comparison) comparisonSummary(comparison)$jaccardfeatures <- c("G1", "G2", "M1") make_network <- function(celltype, cross_weight) { precision <- diag(3) precision[1, 3] <- precision[3, 1] <- cross_weight adjacency <- (precision != 0) * 1L diag(adjacency) <- 0L dimnames(precision) <- dimnames(adjacency) <- list(features, features) CelltypeNetworkResult( precision = precision, adjacency = adjacency, node_info = S4Vectors::DataFrame( feature = features, omic_layer = c("transcript", "transcript", "metabolite")), celltype = celltype, metadata = list(n_donors = 20L)) } mono <- make_network("Monocyte", -0.45) networkCelltype(mono) networkAdjacency(mono) networkNodes(mono) metadata(mono)$n_donors comparison <- run_comparative_network(mono, make_network("B cell", 0)) diffEdges(comparison) celltypeSpecificEdges(comparison) comparisonSummary(comparison)$jaccard
Builds a NetworkComparison from edge tables. Most
users obtain one from run_comparative_network instead.
NetworkComparison( diff_edges = S4Vectors::DataFrame(), shared_edges = S4Vectors::DataFrame(), celltype_specific = list(), summary = list() )NetworkComparison( diff_edges = S4Vectors::DataFrame(), shared_edges = S4Vectors::DataFrame(), celltype_specific = list(), summary = list() )
diff_edges, shared_edges
|
|
celltype_specific |
Named list of |
summary |
List with, for example, |
A valid NetworkComparison.
shared <- S4Vectors::DataFrame(node_i = "G1", node_j = "M1", category = "shared", max_diff = 0.1) differential <- S4Vectors::DataFrame(node_i = "G2", node_j = "M1", category = "differential", max_diff = 0.5) NetworkComparison( diff_edges = differential, shared_edges = shared, summary = list(celltypes = c("Monocyte", "B cell")))shared <- S4Vectors::DataFrame(node_i = "G1", node_j = "M1", category = "shared", max_diff = 0.1) differential <- S4Vectors::DataFrame(node_i = "G2", node_j = "M1", category = "differential", max_diff = 0.5) NetworkComparison( diff_edges = differential, shared_edges = shared, summary = list(celltypes = c("Monocyte", "B cell")))
Stores results from run_comparative_network,
including differential, shared, and cell-type-specific edges. Use the
accessors in network-accessors to extract them.
## S4 method for signature 'NetworkComparison' show(object)## S4 method for signature 'NetworkComparison' show(object)
object |
A |
The show method prints a summary and returns
NULL invisibly.
diff_edgesDataFrame. Edges present in some but not all
of the compared networks (including edges unique to one cell type),
with the range of their partial correlations.
shared_edgesDataFrame. Edges present in all
compared cell types.
celltype_specificNamed list of DataFrames. Edges
unique to each cell type.
summaryList. Summary statistics: Jaccard similarity, edge counts, cell types compared.
network-accessors,
NetworkComparison
showClass("NetworkComparison")showClass("NetworkComparison")
Renders a cell-type network graph with nodes coloured by omic layer and edges weighted by the absolute entries of the precision matrix or by stability.
plot_celltype_network( network, layout = c("fr", "circle", "grid", "bipartite"), color_by = c("omic_layer", "stability", "community"), highlight_cross_omic = TRUE, label_top = 10L, edge_alpha_by = c("weight", "stability") )plot_celltype_network( network, layout = c("fr", "circle", "grid", "bipartite"), color_by = c("omic_layer", "stability", "community"), highlight_cross_omic = TRUE, label_top = 10L, edge_alpha_by = c("weight", "stability") )
network |
|
layout |
Character; graph layout algorithm.
|
color_by |
Character; node colouring scheme.
|
highlight_cross_omic |
Logical; emphasize transcript-metabolite edges. Default TRUE. |
label_top |
Integer; label top N nodes by degree. Default 10. |
edge_alpha_by |
Character; |
A ggplot object (requires ggraph
and igraph).
features <- c("G1", "G2", "M1") precision <- diag(3) precision[1, 3] <- precision[3, 1] <- -0.4 adjacency <- (precision != 0) * 1L diag(adjacency) <- 0L dimnames(precision) <- dimnames(adjacency) <- list(features, features) network <- CelltypeNetworkResult( precision = precision, adjacency = adjacency, node_info = S4Vectors::DataFrame( feature = features, omic_layer = c("transcript", "transcript", "metabolite") ), celltype = "Monocyte", metadata = list(n_donors = 20L) ) plot_packages <- c("igraph", "ggraph", "ggplot2", "tidygraph") if (all(vapply(plot_packages, requireNamespace, logical(1), quietly = TRUE))) { network_plot <- plot_celltype_network( network, layout = "circle", label_top = 3L ) inherits(network_plot, "ggplot") }features <- c("G1", "G2", "M1") precision <- diag(3) precision[1, 3] <- precision[3, 1] <- -0.4 adjacency <- (precision != 0) * 1L diag(adjacency) <- 0L dimnames(precision) <- dimnames(adjacency) <- list(features, features) network <- CelltypeNetworkResult( precision = precision, adjacency = adjacency, node_info = S4Vectors::DataFrame( feature = features, omic_layer = c("transcript", "transcript", "metabolite") ), celltype = "Monocyte", metadata = list(n_donors = 20L) ) plot_packages <- c("igraph", "ggraph", "ggplot2", "tidygraph") if (all(vapply(plot_packages, requireNamespace, logical(1), quietly = TRUE))) { network_plot <- plot_celltype_network( network, layout = "circle", label_top = 3L ) inherits(network_plot, "ggplot") }
Plots the stability-selection frequency of the most stable edges
(up to 50) at the selected penalty, coloured by whether the edge
joins two omic layers. The network object stores frequencies at
the selected penalty only, so this is not a stability surface over
the tuning grid; keep the grid from the estimator if one is
needed. A reference line is drawn only when threshold is
given.
plot_edge_stability(network, threshold = NULL)plot_edge_stability(network, threshold = NULL)
network |
|
threshold |
A single number between 0 and 1, or |
A ggplot object.
features <- c("G1", "G2", "M1") stability <- matrix(0, 3, 3, dimnames = list(features, features)) stability[1, 3] <- stability[3, 1] <- 0.85 precision <- diag(3) dimnames(precision) <- list(features, features) network <- CelltypeNetworkResult( precision = precision, adjacency = (stability > 0) * 1L, stability = stability, node_info = S4Vectors::DataFrame( feature = features, omic_layer = c("transcript", "transcript", "metabolite") ), celltype = "Monocyte", metadata = list(n_donors = 20L) ) if (requireNamespace("ggplot2", quietly = TRUE)) { stability_plot <- plot_edge_stability(network, threshold = 0.8) inherits(stability_plot, "ggplot") }features <- c("G1", "G2", "M1") stability <- matrix(0, 3, 3, dimnames = list(features, features)) stability[1, 3] <- stability[3, 1] <- 0.85 precision <- diag(3) dimnames(precision) <- list(features, features) network <- CelltypeNetworkResult( precision = precision, adjacency = (stability > 0) * 1L, stability = stability, node_info = S4Vectors::DataFrame( feature = features, omic_layer = c("transcript", "transcript", "metabolite") ), celltype = "Monocyte", metadata = list(n_donors = 20L) ) if (requireNamespace("ggplot2", quietly = TRUE)) { stability_plot <- plot_edge_stability(network, threshold = 0.8) inherits(stability_plot, "ggplot") }
Plots, for the selected edge set, how much each edge's partial
correlation varies across the compared cell types
(max_diff), with the per-cell-type edge counts and pairwise
Jaccard overlap in the subtitle. Up to 50 edges are shown.
plot_network_comparison( comparison, highlight = c("differential", "shared", "all") )plot_network_comparison( comparison, highlight = c("differential", "shared", "all") )
comparison |
|
highlight |
Character; which edges to plot:
|
A ggplot object.
shared_edge <- S4Vectors::DataFrame( node_i = "G1", node_j = "M1", category = "shared", max_diff = 0.1 ) differential_edge <- S4Vectors::DataFrame( node_i = "G2", node_j = "M1", category = "differential", max_diff = 0.5 ) comparison <- NetworkComparison( diff_edges = differential_edge, shared_edges = shared_edge, celltype_specific = list(), summary = list( celltypes = c("Monocyte", "B cell"), n_edges = c(Monocyte = 2L, `B cell` = 1L), n_shared = 1L, n_differential = 1L, jaccard = list(Monocyte_vs_B_cell = 0.5) ) ) if (requireNamespace("ggplot2", quietly = TRUE)) { comparison_plot <- plot_network_comparison( comparison, highlight = "differential" ) inherits(comparison_plot, "ggplot") }shared_edge <- S4Vectors::DataFrame( node_i = "G1", node_j = "M1", category = "shared", max_diff = 0.1 ) differential_edge <- S4Vectors::DataFrame( node_i = "G2", node_j = "M1", category = "differential", max_diff = 0.5 ) comparison <- NetworkComparison( diff_edges = differential_edge, shared_edges = shared_edge, celltype_specific = list(), summary = list( celltypes = c("Monocyte", "B cell"), n_edges = c(Monocyte = 2L, `B cell` = 1L), n_shared = 1L, n_differential = 1L, jaccard = list(Monocyte_vs_B_cell = 0.5) ) ) if (requireNamespace("ggplot2", quietly = TRUE)) { comparison_plot <- plot_network_comparison( comparison, highlight = "differential" ) inherits(comparison_plot, "ggplot") }
Computes within-donor Spearman partial correlations between gene expression and protein abundance at the single-cell level, then uses random-effects meta-regression to test whether coupling strength varies with a donor-level exposure.
run_cell_coupling( x, genes, proteins, exposure, celltype, celltype_col = "cell_type", altexp_name = "CITE", confounders = NULL, min_cells = 30L, min_donors = 10L, meta_moderators = NULL, var_method = c("asymptotic", "bootstrap"), n_boot = 200L )run_cell_coupling( x, genes, proteins, exposure, celltype, celltype_col = "cell_type", altexp_name = "CITE", confounders = NULL, min_cells = 30L, min_donors = 10L, meta_moderators = NULL, var_method = c("asymptotic", "bootstrap"), n_boot = 200L )
x |
A |
genes |
Character vector of gene names to test. |
proteins |
Character vector of protein names to test
(must be present in |
exposure |
Character; name of the exposure variable
in |
celltype |
Character; cell type to analyse. |
celltype_col |
Character; column in |
altexp_name |
Character; name of the altExp containing
protein data. Default |
confounders |
Character vector of column names in
|
min_cells |
Integer; minimum cells per donor to include. Default 30. |
min_donors |
Integer; minimum number of donors with enough cells
(at least |
meta_moderators |
Character vector or one-sided formula of
additional donor-level moderators for the meta-regression
(e.g., |
var_method |
Character. Method for estimating the
sampling variance of Fisher z-transformed correlations.
|
n_boot |
Integer. Number of bootstrap replicates
per donor when |
For each gene-protein pair, the method proceeds in two stages:
Stage 1 (within-donor): For each donor with
at least min_cells cells of the specified cell type,
compute the Spearman partial correlation between gene
expression and protein abundance, controlling for library
sizes and any user-specified confounders:
Then apply Fisher's z-transform:
where is the number of conditioning variables
(2 + length of confounders, less any that are constant
within the donor and therefore dropped). The factor 1.06
corrects for the efficiency loss of rank-based correlation
(Fieller et al. 1957).
Stage 2 (across-donor meta-regression): Fit a random-effects model via REML with Knapp-Hartung adjustment:
where (known sampling
variance) and (between-donor
heterogeneity). The Knapp-Hartung adjustment provides
more accurate confidence intervals for small numbers of
studies (donors), using a t-distribution with
degrees of freedom rather than a
z-distribution.
Confounder control: Cell-level confounders (cell cycle, mitochondrial content, ambient RNA scores) are partialed out in Stage 1, ensuring that the correlation reflects genuine gene-protein coupling rather than shared technical or biological confounds. Donor-level moderators (age, sex) are included in Stage 2.
A DataFrame with one row per gene-protein pair
(zero rows when too few donors qualify). A pair whose exposure does
not vary among its donors, or is collinear with the moderators, is
not tested, with a warning that counts such pairs:
Feature names.
Number of donors in the meta-regression: donors with enough cells, a partial correlation and values of the exposure and of every moderator.
Intercept (baseline coupling).
Exposure coefficient: the slope, across donors, of the Fisher z of the coupling on the exposure.
Between-donor heterogeneity variance (REML).
Heterogeneity percentage.
Mean partial correlation across donors.
Mean cells per donor.
Number of conditioning variables requested (library sizes plus confounders); variables constant within a donor are dropped for that donor.
Viechtbauer W (2010). Conducting meta-analyses in R with the metafor package. J Stat Softw, 36(3), 1-48. doi:10.18637/jss.v036.i03
Fieller EC, Hartley HO, Pearson ES (1957). Tests for rank correlation coefficients. I. Biometrika, 44, 470-481.
Kim S (2015). ppcor: An R Package for a Fast Calculation to Semi-partial Correlation Coefficients. Commun Stat Appl Methods, 22(6), 665-674.
set.seed(1) donors <- sprintf("D%02d", 1:12) donor <- rep(donors, each = 60) gene <- matrix(stats::rpois(2 * length(donor), 10), nrow = 2, dimnames = list(c("Gene1", "Gene2"), paste0("c", seq_along(donor)))) protein <- matrix(stats::rpois(2 * length(donor), 5), nrow = 2, dimnames = list(c("Prot1", "Prot2"), colnames(gene))) sce <- SingleCellExperiment::SingleCellExperiment( assays = list(counts = gene), colData = S4Vectors::DataFrame(donor_id = donor, cell_type = "T")) SingleCellExperiment::altExp(sce, "CITE") <- SummarizedExperiment::SummarizedExperiment( assays = list(counts = protein)) exp_mat <- matrix(seq(0, 2, length.out = 12), ncol = 1, dimnames = list(donors, "exposure")) scee <- build_scee(sce, exp_mat, sample_col = "donor_id") if (requireNamespace("metafor", quietly = TRUE) && requireNamespace("ppcor", quietly = TRUE)) { run_cell_coupling(scee, genes = "Gene1", proteins = "Prot1", exposure = "exposure", celltype = "T", min_cells = 20L, min_donors = 10L) }set.seed(1) donors <- sprintf("D%02d", 1:12) donor <- rep(donors, each = 60) gene <- matrix(stats::rpois(2 * length(donor), 10), nrow = 2, dimnames = list(c("Gene1", "Gene2"), paste0("c", seq_along(donor)))) protein <- matrix(stats::rpois(2 * length(donor), 5), nrow = 2, dimnames = list(c("Prot1", "Prot2"), colnames(gene))) sce <- SingleCellExperiment::SingleCellExperiment( assays = list(counts = gene), colData = S4Vectors::DataFrame(donor_id = donor, cell_type = "T")) SingleCellExperiment::altExp(sce, "CITE") <- SummarizedExperiment::SummarizedExperiment( assays = list(counts = protein)) exp_mat <- matrix(seq(0, 2, length.out = 12), ncol = 1, dimnames = list(donors, "exposure")) scee <- build_scee(sce, exp_mat, sample_col = "donor_id") if (requireNamespace("metafor", quietly = TRUE) && requireNamespace("ppcor", quietly = TRUE)) { run_cell_coupling(scee, genes = "Gene1", proteins = "Prot1", exposure = "exposure", celltype = "T", min_cells = 20L, min_donors = 10L) }
Given a SCEE with pseudobulk transcriptomics and donor-level metabolomics, constructs a block-calibrated conditional independence network for a specified cell type.
run_celltype_network( x, metabolites = NULL, celltype, celltype_col = "cell_type", exposure = NULL, covariates = NULL, method = c("coglasso", "block_glasso"), stability = TRUE, nlambda_w = 15L, nlambda_b = 15L, subsample_ratio = 0.8, rep_num = 20L, min_cells = 10L, top_var_genes = NULL, lambda_w = 0.3, lambda_b = 0.5, precomputed_network = NULL, transform = c("vst", "log_cpm"), genes = NULL )run_celltype_network( x, metabolites = NULL, celltype, celltype_col = "cell_type", exposure = NULL, covariates = NULL, method = c("coglasso", "block_glasso"), stability = TRUE, nlambda_w = 15L, nlambda_b = 15L, subsample_ratio = 0.8, rep_num = 20L, min_cells = 10L, top_var_genes = NULL, lambda_w = 0.3, lambda_b = 0.5, precomputed_network = NULL, transform = c("vst", "log_cpm"), genes = NULL )
x |
|
metabolites |
Numeric matrix; rows = donors,
cols = metabolites. Row names must be donor IDs. A matrix without
columns, or a missing or infinite value for an analysed donor, is an
error, and so is a column with the name of another column or of a
gene that becomes a node: two nodes cannot have the same name.
The matrix is needed to estimate a network; the default,
|
celltype |
Character; which cell type to build the network for. |
celltype_col |
Character; column in |
exposure |
Character or NULL; exposure variable to
condition on (regressed out), a column of |
covariates |
Character vector or NULL; adjustment
covariates, columns of |
method |
Character; |
stability |
Logical; for |
nlambda_w |
Integer; within-omic lambda grid size. Default 15. |
nlambda_b |
Integer; between-omic lambda grid size. Default 15. |
subsample_ratio |
Numeric strictly between 0 and 1;
proportion of donors drawn in each XStARS subsample, passed to
|
rep_num |
Integer, at least 2; number of XStARS subsamples.
Default 20, as in |
min_cells |
Integer; minimum cells per pseudobulk sample. Default 10. |
top_var_genes |
Integer or NULL; restrict to top N most variable genes for dimensionality reduction. Default NULL (all genes). Recommended: 50-200. |
lambda_w |
Numeric; graphical-lasso penalty for pairs of features in the same omic layer, on the correlation scale, for the block_glasso method. Default 0.3. |
lambda_b |
Numeric; graphical-lasso penalty for pairs of features in different omic layers, on the correlation scale, for the block_glasso method. Default 0.5. |
precomputed_network |
Optional named list holding a
pre-estimated network to wrap into a CelltypeNetworkResult
without re-estimation, with elements |
transform |
Character; the transform of the pseudobulk counts.
|
genes |
Character vector or |
The workflow proceeds as follows:
Pseudobulk aggregation for the specified cell type, reusing existing exposomeSC infrastructure.
Transformation of the pseudobulk counts, chosen by
transform: DESeq2's variance-stabilising transformation or
log-CPM. The transform is recorded in
metadata(result)$transform.
Constant features: a transcript or metabolite that takes one
value in every donor (for example a gene with no counts in the
cell type) is left out, with a message that names up to five
transcripts and five metabolites; all are recorded
in metadata(result)$constant_features; the call stops when
every transcript or every metabolite is constant. Networks of
different cell types can therefore differ in their features, which
run_comparative_network does not accept. For a
comparison, name the genes with genes and leave a gene that
is constant in one of the cell types out of genes for all of
them. top_var_genes on its own selects different genes in
different cell types.
Adjustment: if exposure or
covariates are specified, regresses them out
from both transcriptomic and metabolomic matrices.
The resulting network captures the exposure-adjusted
conditional dependency structure.
Column-binding of the transcript values and the metabolite values (the residuals of both, where something was regressed out), each column scaled to unit variance.
Block-calibrated graphical lasso estimation.
With coglasso: collaborative graphical lasso
with separate within/between-omic penalties and
XStARS stability selection. With block_glasso: the
graphical lasso (glasso::glasso()) on the correlation
matrix, with the fixed penalties lambda_w within and
lambda_b between omic layers, the diagonal unpenalised
and no stability selection; it needs the glasso
package.
Returns a CelltypeNetworkResult object.
A CelltypeNetworkResult object.
Albanese A, Kohlen W, Behrouzi P (2026). Multi-omics network reconstruction with collaborative graphical lasso. Bioinformatics 42(7):btag477. doi:10.1093/bioinformatics/btag477
Friedman J, Hastie T, Tibshirani R (2008). Sparse inverse covariance estimation with the graphical lasso. Biostatistics 9(3):432–441. doi:10.1093/biostatistics/kxm045
Liu H, Roeder K, Wasserman L (2010). Stability approach to regularization selection (StARS) for high dimensional graphical models. Advances in Neural Information Processing Systems, 23.
donor_ids <- paste0("D", seq_len(8L)) cell_donor <- rep(donor_ids, each = 10L) cell_ids <- paste0("cell", seq_along(cell_donor)) counts <- outer( seq_len(4L), seq_along(cell_ids), function(gene, cell) 2L + ((5L * gene + 3L * cell) %% 9L) ) storage.mode(counts) <- "integer" dimnames(counts) <- list(paste0("G", seq_len(4L)), cell_ids) sce <- SingleCellExperiment::SingleCellExperiment( assays = list(counts = counts), colData = S4Vectors::DataFrame( cell_id = cell_ids, donor_id = cell_donor, cell_type = "Monocyte" ) ) exposure <- matrix(seq_len(8L), ncol = 1L, dimnames = list(donor_ids, "exposure")) scee <- build_scee(sce, exposure, sample_col = "donor_id") metabolites <- outer( seq_len(8L), seq_len(2L), function(donor, feature) (donor + feature)^2 / 10 ) dimnames(metabolites) <- list(donor_ids, c("M1", "M2")) if (requireNamespace("glasso", quietly = TRUE)) { network <- run_celltype_network( scee, metabolites, celltype = "Monocyte", method = "block_glasso", stability = FALSE, min_cells = 5L, top_var_genes = 3L, transform = "log_cpm" ) network }donor_ids <- paste0("D", seq_len(8L)) cell_donor <- rep(donor_ids, each = 10L) cell_ids <- paste0("cell", seq_along(cell_donor)) counts <- outer( seq_len(4L), seq_along(cell_ids), function(gene, cell) 2L + ((5L * gene + 3L * cell) %% 9L) ) storage.mode(counts) <- "integer" dimnames(counts) <- list(paste0("G", seq_len(4L)), cell_ids) sce <- SingleCellExperiment::SingleCellExperiment( assays = list(counts = counts), colData = S4Vectors::DataFrame( cell_id = cell_ids, donor_id = cell_donor, cell_type = "Monocyte" ) ) exposure <- matrix(seq_len(8L), ncol = 1L, dimnames = list(donor_ids, "exposure")) scee <- build_scee(sce, exposure, sample_col = "donor_id") metabolites <- outer( seq_len(8L), seq_len(2L), function(donor, feature) (donor + feature)^2 / 10 ) dimnames(metabolites) <- list(donor_ids, c("M1", "M2")) if (requireNamespace("glasso", quietly = TRUE)) { network <- run_celltype_network( scee, metabolites, celltype = "Monocyte", method = "block_glasso", stability = FALSE, min_cells = 5L, top_var_genes = 3L, transform = "log_cpm" ) network }
Classifies the union of edges from two or more cell-type-specific networks estimated on the same features as shared, unique to one cell type or differential, and reports pairwise Jaccard overlap. The comparison is descriptive: no edge is tested and no p-value is reported.
run_comparative_network(...)run_comparative_network(...)
... |
Two or more |
Partial correlations are computed from each precision matrix
as .
This is the single-cell analogue of the temporal edge comparison in Cheng et al. (ES&T 2024).
A NetworkComparison object. Its edge
tables contain max_diff, the range of the edge's partial
correlation across networks.
Cheng SL et al. (2024). Multiomic signatures of traffic-related air pollution in London reveal potential short-term perturbations in gut microbiome-related pathways. Environ Sci Technol 58:8771-8782. doi:10.1021/acs.est.3c09148
features <- c("G1", "G2", "M1") make_network <- function(celltype, cross_weight) { precision <- diag(3) precision[1, 3] <- precision[3, 1] <- cross_weight adjacency <- (precision != 0) * 1L diag(adjacency) <- 0L dimnames(precision) <- dimnames(adjacency) <- list(features, features) CelltypeNetworkResult( precision = precision, adjacency = adjacency, node_info = S4Vectors::DataFrame( feature = features, omic_layer = c("transcript", "transcript", "metabolite") ), celltype = celltype, metadata = list(n_donors = 20L) ) } monocyte_network <- make_network("Monocyte", -0.45) b_cell_network <- make_network("B cell", -0.15) comparison <- run_comparative_network(monocyte_network, b_cell_network) comparisonfeatures <- c("G1", "G2", "M1") make_network <- function(celltype, cross_weight) { precision <- diag(3) precision[1, 3] <- precision[3, 1] <- cross_weight adjacency <- (precision != 0) * 1L diag(adjacency) <- 0L dimnames(precision) <- dimnames(adjacency) <- list(features, features) CelltypeNetworkResult( precision = precision, adjacency = adjacency, node_info = S4Vectors::DataFrame( feature = features, omic_layer = c("transcript", "transcript", "metabolite") ), celltype = celltype, metadata = list(n_donors = 20L) ) } monocyte_network <- make_network("Monocyte", -0.45) b_cell_network <- make_network("B cell", -0.15) comparison <- run_comparative_network(monocyte_network, b_cell_network) comparison
Fits linear and polynomial dose-response models for each gene within a cell type, testing whether the exposure-expression relationship is nonlinear. Linear exposure-response models are common, but some exposures, such as endocrine-disrupting chemicals, show non-monotonic dose responses (Vandenberg et al. 2012).
run_dose_response( x, exposure, celltype, celltype_col = "cell_type", target_genes = NULL, max_degree = 3L, min_cells = 10L )run_dose_response( x, exposure, celltype, celltype_col = "cell_type", target_genes = NULL, max_degree = 3L, min_cells = 10L )
x |
A |
exposure |
Character. Exposure variable name. |
celltype |
Character. Target cell type. |
celltype_col |
Character. |
target_genes |
Character vector (optional). Genes to test. Default: top 50 most variable genes. |
max_degree |
Integer. Maximum polynomial degree to test. Default 3 (cubic). Higher values risk overfitting with small sample sizes. |
min_cells |
Integer. Minimum cells per donor. Default 10. |
For each gene, the function fits:
y ~ exposure (linear)
y ~ poly(exposure, 2) (quadratic)
y ~ poly(exposure, 3) (cubic, if max_degree
>= 3)
on pseudobulk log-CPM values. best_model is the model
with the lowest AIC and is descriptive.
p_nonlinear is an F-test of the highest-degree
polynomial that could be fitted (cubic when
max_degree = 3 and at least six donors are available,
otherwise quadratic) against the linear model. It is fixed in
advance and does not depend on the AIC selection, because
testing the model chosen by AIC would overstate the evidence
for nonlinearity.
A DataFrame with columns: gene, best_model
("linear", "quadratic", "cubic"), linear_coef, AIC_linear,
AIC_best, p_nonlinear (F-test of nonlinear_model
against the linear model), nonlinear_model, celltype,
n_donors (donors with at least min_cells cells and a
non-missing exposure; donors with a missing exposure are left out,
with a message).
Vandenberg LN et al. (2012). Hormones and endocrine- disrupting chemicals: low-dose effects and nonmonotonic dose responses. Endocr Rev 33:378-455. doi:10.1210/er.2011-1050
library(SingleCellExperiment); library(S4Vectors) set.seed(1) counts <- matrix(rpois(5000, 8), nrow = 50, dimnames = list(paste0("G", 1:50), paste0("c", 1:100))) sce <- SingleCellExperiment(assays = list(counts = counts), colData = DataFrame(cell_id = paste0("c", 1:100), donor_id = rep(paste0("D", 1:10), each = 10), cell_type = rep(c("Mono", "NK"), 50))) exp_mat <- matrix(rnorm(20), nrow = 10, dimnames = list(paste0("D", 1:10), c("E1", "E2"))) scee <- build_scee(sce, exp_mat, sample_col = "donor_id") dr <- run_dose_response(scee, exposure = "E1", celltype = "Mono", celltype_col = "cell_type", min_cells = 3L, max_degree = 2L) head(dr)library(SingleCellExperiment); library(S4Vectors) set.seed(1) counts <- matrix(rpois(5000, 8), nrow = 50, dimnames = list(paste0("G", 1:50), paste0("c", 1:100))) sce <- SingleCellExperiment(assays = list(counts = counts), colData = DataFrame(cell_id = paste0("c", 1:100), donor_id = rep(paste0("D", 1:10), each = 10), cell_type = rep(c("Mono", "NK"), 50))) exp_mat <- matrix(rnorm(20), nrow = 10, dimnames = list(paste0("D", 1:10), c("E1", "E2"))) scee <- build_scee(sce, exp_mat, sample_col = "donor_id") dr <- run_dose_response(scee, exposure = "E1", celltype = "Mono", celltype_col = "cell_type", min_cells = 3L, max_degree = 2L) head(dr)
Fits generalized additive models (GAMs) for cell-type-
specific dose-response curves, allowing the data to
determine the shape of the exposure-expression
relationship without pre-specifying a polynomial degree.
Unlike run_dose_response, the shape is not
restricted to a polynomial.
run_dose_response_gam( x, exposure, celltype, celltype_col = "cell_type", target_genes = NULL, k = NULL, min_cells = 10L, loocv = TRUE )run_dose_response_gam( x, exposure, celltype, celltype_col = "cell_type", target_genes = NULL, k = NULL, min_cells = 10L, loocv = TRUE )
x |
A |
exposure |
Character. Exposure variable name. |
celltype |
Character. Target cell type. |
celltype_col |
Character. |
target_genes |
Character vector (optional). Genes to test. Default: top 50 most variable. |
k |
Integer. Maximum basis dimension for the smooth
term, at least 4 and at most the number of distinct exposure
values. Default |
min_cells |
Integer. Min cells per donor. Default 10. |
loocv |
Logical. If |
For each gene, two models are fit:
Linear: y ~ exposure (OLS)
GAM: y ~ s(exposure, k = k) (penalized
thin-plate regression spline via mgcv::gam)
The GAM smooth is estimated using restricted maximum likelihood (REML), which selects the smoothness penalty. The effective degrees of freedom (edf) indicate the complexity: edf close to 1 means approximately linear, and larger values mean more curvature.
p_nonlinear comes from a third model,
y ~ exposure + s(exposure, bs = "tp", m = c(2, 0)),
whose smooth has no unpenalised null space, so the linear
trend is carried by the parametric term and the smooth can
only represent departures from linearity. Its p-value is the
approximate Wald-type test for smooth terms of Wood (2013).
Comparing the linear and GAM fits by an F-test on their
residual deviances is not valid here: the GAM's effective
degrees of freedom are estimated and often close to one.
Leave-one-out cross-validated R² (loocv) provides an honest estimate of out-of-sample prediction accuracy, unlike apparent R² which inflates with model complexity. This is critical for small-sample dose-response where overfitting is a real risk.
Why GAM over polynomial:
Polynomials impose a global parametric form
GAMs adapt locally – can capture threshold effects, plateaus, U-shapes
Penalised smoothness selection limits overfitting
edf provides an interpretable complexity measure
A DataFrame with columns: gene, edf
(effective degrees of freedom for smooth term),
p_smooth (significance of smooth term vs intercept),
p_nonlinear (approximate test that a fully penalised smooth
added to a linear exposure term is zero, that is, of
departure from linearity; see Details),
AIC_linear, AIC_gam, R2_linear, R2_gam,
R2_loocv_linear (if loocv=TRUE), R2_loocv_gam,
deviance_explained, celltype, n_donors (donors with at least
min_cells cells and a non-missing exposure; donors with a
missing exposure are left out, with a message).
Wood SN (2017). Generalized Additive Models: An Introduction with R. 2nd ed. Chapman and Hall/CRC.
Wood SN (2013). On p-values for smooth components of an extended generalized additive model. Biometrika 100:221-228. doi:10.1093/biomet/ass048
Vandenberg LN et al. (2012). Hormones and endocrine- disrupting chemicals: low-dose effects and nonmonotonic dose responses. Endocr Rev 33:378-455. doi:10.1210/er.2011-1050
library(SingleCellExperiment); library(S4Vectors) set.seed(1) counts <- matrix(rpois(5000, 8), nrow = 50, dimnames = list(paste0("G", 1:50), paste0("c", 1:100))) sce <- SingleCellExperiment(assays = list(counts = counts), colData = DataFrame(cell_id = paste0("c", 1:100), donor_id = rep(paste0("D", 1:10), each = 10), cell_type = rep(c("Mono", "NK"), 50))) exp_mat <- matrix(rnorm(20), nrow = 10, dimnames = list(paste0("D", 1:10), c("E1", "E2"))) scee <- build_scee(sce, exp_mat, sample_col = "donor_id") if (requireNamespace("mgcv", quietly = TRUE)) { dr <- run_dose_response_gam(scee, exposure = "E1", celltype = "Mono", celltype_col = "cell_type", min_cells = 3L, target_genes = paste0("G", 1:3)) head(dr) }library(SingleCellExperiment); library(S4Vectors) set.seed(1) counts <- matrix(rpois(5000, 8), nrow = 50, dimnames = list(paste0("G", 1:50), paste0("c", 1:100))) sce <- SingleCellExperiment(assays = list(counts = counts), colData = DataFrame(cell_id = paste0("c", 1:100), donor_id = rep(paste0("D", 1:10), each = 10), cell_type = rep(c("Mono", "NK"), 50))) exp_mat <- matrix(rnorm(20), nrow = 10, dimnames = list(paste0("D", 1:10), c("E1", "E2"))) scee <- build_scee(sce, exp_mat, sample_col = "donor_id") if (requireNamespace("mgcv", quietly = TRUE)) { dr <- run_dose_response_gam(scee, exposure = "E1", celltype = "Mono", celltype_col = "cell_type", min_cells = 3L, target_genes = paste0("G", 1:3)) head(dr) }
Tests whether an exposure is associated with the joint cell-composition profile while retaining donors, rather than cells or repeated biological samples, as the independent units of inference.
run_exposure_composition( x, exposure, celltype_col = "cell_type", replicate_col = NULL, covariates = NULL, min_cells = 10L, support_min_donors = 10L, support_min_total_cells = 100L, celltype_universe = NULL, exclude_celltypes = character(), zero_prior = 0.5, replicate_aggregation = c("equal_replicate", "pooled_counts"), n_permutations = 0L, permutation_strata = NULL, seed = NULL )run_exposure_composition( x, exposure, celltype_col = "cell_type", replicate_col = NULL, covariates = NULL, min_cells = 10L, support_min_donors = 10L, support_min_total_cells = 100L, celltype_universe = NULL, exclude_celltypes = character(), zero_prior = 0.5, replicate_aggregation = c("equal_replicate", "pooled_counts"), n_permutations = 0L, permutation_strata = NULL, seed = NULL )
x |
A |
exposure |
Character scalar naming the exposure variable. |
celltype_col |
Character scalar naming the cell-type column in
|
replicate_col |
Optional character scalar naming biological samples
nested within donors. If |
covariates |
Character vector naming numeric design columns in
|
min_cells |
Minimum number of cells from the retained universe per biological sample. |
support_min_donors |
Minimum number of donors in which a cell type must be observed. Support is evaluated without reference to exposure values. |
support_min_total_cells |
Minimum total number of cells required for a cell type, also evaluated without reference to exposure values. |
celltype_universe |
Optional pre-specified character vector of cell types eligible for analysis. |
exclude_celltypes |
Character vector of annotation labels excluded before support filtering. |
zero_prior |
Positive symmetric Dirichlet prior. The default 0.5 is the Jeffreys prior. |
replicate_aggregation |
Either |
n_permutations |
Number of Freedman–Lane residual permutations for the omnibus test. Zero reports the asymptotic partial Pillai test only. |
permutation_strata |
Optional exchangeability strata for permutation. Supply a named vector indexed by donor ID for study-stratified inference. |
seed |
|
Counts are formed for every biological sample by supported cell type. Zeros
are handled through posterior expected log proportions under a symmetric
Dirichlet(1/2) prior. Orthonormal isometric log-ratio coordinates define a
basis-invariant partial Pillai omnibus test. Repeated samples are averaged
within donor in log-ratio space, giving every donor equal regression weight.
Cell-type contrasts are exposure coefficients for
log2(cell type / geometric mean of all other supported types) with
HC3 heteroscedasticity-consistent standard errors.
Nominal 95 percent confidence intervals and Bonferroni simultaneous
95 percent family-wise intervals are both returned and labelled explicitly.
The method estimates relative composition within the supported, retained cell-type universe. It does not identify absolute cell abundance, and the Dirichlet prior handles observed zeros but does not model dissociation, capture, annotation, or tissue-sampling selection mechanisms.
Relation to other methods. speckle::propeller()
(Phipson et al. 2022) transforms the cell-type proportions of each sample
(logit or arcsine square root) and fits a limma linear model for
each cell type to compare groups of samples. crumblr::crumblr()
(Hoffman and Roussos 2026) returns centred log-ratio transformed counts
with observation-level precision weights for weighted linear or linear
mixed models. sccomp (Mangiola et al. 2023) fits a Bayesian
beta-binomial model of composition and variability. voomCLR (Assefa et
al. 2026), distributed outside Bioconductor, applies the centred
log-ratio transform with observation-level variances from a voom-type
mean-variance trend and offers a bias correction of the fitted
coefficients. run_exposure_composition() differs from these in
three respects: by default (replicate_aggregation =
"equal_replicate") repeated samples of a donor are averaged in log-ratio
space, so that each donor carries equal weight; the omnibus test of the
whole composition uses orthonormal isometric log-ratio coordinates and
does not depend on which basis is chosen; and the permutation test can be
restricted to exchangeability strata such as studies
(permutation_strata). Its per-cell-type contrasts use HC3
standard errors, without precision weights or empirical Bayes moderation
of the variances.
A DataFrame with one HC3-adjusted cell-type-versus-rest
log-ratio contrast per supported cell type. metadata(result) stores
the partial Pillai omnibus test, support audit, design diagnostics, and the
donor-level model matrices used for inference. padj is the Holm
family-wise adjusted p-value; padj_bh is supplied as a secondary
false-discovery-rate summary.
Aitchison J (1986). The Statistical Analysis of Compositional Data. Chapman and Hall.
Freedman D, Lane D (1983). A nonstochastic interpretation of reported significance levels. Journal of Business and Economic Statistics, 1, 292–298.
Phipson B, Sim CB, Porrello ER, Hewitt AW, Powell J, Oshlack A (2022). propeller: testing for differences in cell type proportions in single cell data. Bioinformatics 38(20):4720–4726. doi:10.1093/bioinformatics/btac582
Hoffman GE, Roussos P (2026). Fast, flexible analysis of differences in cellular composition with crumblr. Nat Commun 17:9598. doi:10.1038/s41467-026-75681-7
Mangiola S, Roth-Schulze AJ, Trussart M, et al. (2023). sccomp: robust differential composition and variability analysis for single-cell data. Proc Natl Acad Sci USA 120(33):e2203828120. doi:10.1073/pnas.2203828120
Assefa AT, Verbist B, Van den Berge K (2026). Assessing differential cell composition in single-cell studies using voomCLR. Bioinformatics 42(1):btaf637. doi:10.1093/bioinformatics/btaf637
library(SingleCellExperiment) library(S4Vectors) set.seed(1) donors <- paste0("D", seq_len(12)) donor_type_counts <- t(rmultinom( length(donors), size = 30, prob = c(A = 0.3, B = 0.4, C = 0.3) )) rownames(donor_type_counts) <- donors cell_donor <- rep(donors, each = 30) cell_type <- unlist( lapply(seq_along(donors), function(i) { rep(colnames(donor_type_counts), donor_type_counts[i, ]) }), use.names = FALSE ) counts <- matrix(rpois(20 * length(cell_donor), 5), nrow = 20, dimnames = list(paste0("G", seq_len(20)), paste0("c", seq_along(cell_donor)))) sce <- SingleCellExperiment( assays = list(counts = counts), colData = DataFrame( cell_id = colnames(counts), donor_id = cell_donor, cell_type = cell_type)) exp_mat <- cbind(X1 = rep(0:1, 6), age = seq(40, 62, by = 2)) rownames(exp_mat) <- donors scee <- build_scee(sce, exp_mat, sample_col = "donor_id") run_exposure_composition( scee, exposure = "X1", covariates = "age", min_cells = 10L, support_min_donors = 3L, support_min_total_cells = 10L )library(SingleCellExperiment) library(S4Vectors) set.seed(1) donors <- paste0("D", seq_len(12)) donor_type_counts <- t(rmultinom( length(donors), size = 30, prob = c(A = 0.3, B = 0.4, C = 0.3) )) rownames(donor_type_counts) <- donors cell_donor <- rep(donors, each = 30) cell_type <- unlist( lapply(seq_along(donors), function(i) { rep(colnames(donor_type_counts), donor_type_counts[i, ]) }), use.names = FALSE ) counts <- matrix(rpois(20 * length(cell_donor), 5), nrow = 20, dimnames = list(paste0("G", seq_len(20)), paste0("c", seq_along(cell_donor)))) sce <- SingleCellExperiment( assays = list(counts = counts), colData = DataFrame( cell_id = colnames(counts), donor_id = cell_donor, cell_type = cell_type)) exp_mat <- cbind(X1 = rep(0:1, 6), age = seq(40, 62, by = 2)) rownames(exp_mat) <- donors scee <- build_scee(sce, exp_mat, sample_col = "donor_id") run_exposure_composition( scee, exposure = "X1", covariates = "age", min_cells = 10L, support_min_donors = 3L, support_min_total_cells = 10L )
Pre-selects the transcripts and metabolites associated with an exposure, by stability selection or univariate testing, and estimates a cross-omic network among the selected features only. Cheng et al. (2024) analysed transcriptomic and metabolomic signatures of air pollution in two such stages: features associated with the exposures were identified first, and conditional multi-omic networks estimated afterwards.
run_exposure_network( x, metabolites, celltype, exposure, celltype_col = "cell_type", covariates = NULL, selection_method = c("stability", "univariate"), fdr_threshold = 0.05, pi_threshold = 0.6, stability_q = NULL, min_cells = 10L, network_method = c("coglasso", "block_glasso"), lambda_w = 0.3, lambda_b = 0.5, transform = c("vst", "log_cpm"), genes = NULL )run_exposure_network( x, metabolites, celltype, exposure, celltype_col = "cell_type", covariates = NULL, selection_method = c("stability", "univariate"), fdr_threshold = 0.05, pi_threshold = 0.6, stability_q = NULL, min_cells = 10L, network_method = c("coglasso", "block_glasso"), lambda_w = 0.3, lambda_b = 0.5, transform = c("vst", "log_cpm"), genes = NULL )
x |
|
metabolites |
Numeric matrix, or a data frame of numeric columns; rows = donors, cols = metabolites. Row names must be donor IDs. A matrix without columns, or a missing or infinite value for an analysed donor, is an error, and so is a column with the name of another column or of a candidate gene: two nodes cannot have the same name. Leave the exposure itself out of the columns: a column that holds the values of the exposure, or a monotone transform of them, has a rank correlation of 1 or -1 with it, is always selected and becomes a node. |
celltype |
Character; cell type to analyse. |
exposure |
Character; exposure variable name, a column of
|
celltype_col |
Character; cell type column.
Default |
covariates |
Character vector or NULL; columns of
|
selection_method |
Character; |
fdr_threshold |
Numeric; FDR threshold for univariate selection. Default 0.05. |
pi_threshold |
Numeric in (0.5, 1]; minimum proportion of
subsamples in which a feature must be selected under
|
stability_q |
Integer or |
min_cells |
Integer; minimum cells per pseudobulk. |
network_method |
Character; |
lambda_w |
Numeric; graphical-lasso penalty for pairs of
features in the same omic layer, on the correlation scale, for the
block graphical lasso ( |
lambda_b |
Numeric; graphical-lasso penalty for pairs of features in different omic layers, on the correlation scale, for the block graphical lasso. Default 0.5. |
transform |
Character; the transform of the pseudobulk counts,
|
genes |
Character vector or |
Stage 1: Feature selection, among the donors with a value of the
exposure. Each transcript and metabolite is screened by its Spearman
correlation with the exposure. With covariates it is the partial
rank correlation: the ranks of the covariates are regressed out of the
ranks of the feature and of the exposure, and the residuals are
correlated.
A feature without variation across these donors, such as a gene without
a count in the cell type, is neither tested nor ranked by either method,
and below counts the features that vary.
"univariate" tests the correlation (asymptotic t
approximation, with one degree of freedom fewer for each covariate that
is not constant or a combination of the others among these donors) with
BH correction over these features.
The approximation is poor when both the exposure and a feature take one
value in all but a few donors, as an exposure that only a few donors
have, or that is above its limit of detection in a few, and a gene with
a count in one or two donors: the p-value of such a gene is far too
small whenever its donors are among those few, and with many such genes
among the candidates some pass the BH correction together. For an
exposure of this kind, name the candidate genes with genes and
leave out those with a count in few donors.
"stability" applies stability selection (Meinshausen and
Buhlmann 2010) to a marginal screen: in each of 100 random
subsamples of half the donors with an observed exposure, the
stability_q features with the largest absolute
correlation with the exposure are selected, and features selected
in a proportion of at least pi_threshold of subsamples are
retained. The screen remains defined when features outnumber
donors. Under the exchangeability and better-than-random-guessing
assumptions of Meinshausen and Buhlmann, the expected number of
falsely selected features is at most
, reported as pfer_bound.
Candidates with a count in very few donors are hardly ever among the
stability_q highest of a subsample, which the exchangeability
assumption does not allow for; with many of them among the candidates
the bound is too small. genes can leave them out.
At least three features must be selected.
Transcript values are log-CPM or VST values and therefore relative to each donor's library size. When the exposure strongly changes genes that carry a large share of the counts, the remaining genes shift in the opposite direction and can pass the screen; with few measured genes this can dominate the univariate screen.
Stage 2: Network estimation on the selected features only, with
collaborative graphical lasso model selection by XStARS
("coglasso") or the block graphical lasso
("block_glasso"). It is one network for all the donors analysed.
The exposure is not regressed out of the features and is not a node, so
an edge can reflect the association that two features share with the
exposure, and the network does not estimate how the dependence between
features changes with the exposure.
A CelltypeNetworkResult
restricted to exposure-associated features. Its metadata record
the expression transform, the covariates, the donors of the network
(donors) and the number of them with a value of the exposure
(n_donors_exposure), on whom the selection was made, the
selection settings, for stability selection pfer_bound, in
constant_features the candidates that are constant across the
donors with a value of the exposure and so could not be selected, and
in selection the penalties of the network:
lambda_w and lambda_b for the block graphical lasso, or
the size of the grid and the selected_lambda_w,
selected_lambda_b and selected_c that coglasso
selected, with stars_variability.
Cheng SL et al. (2024). Multiomic signatures of traffic-related air pollution in London reveal potential short-term perturbations in gut microbiome-related pathways. Environ Sci Technol 58:8771-8782. doi:10.1021/acs.est.3c09148
Meinshausen N, Buhlmann P (2010). Stability selection. J R Stat Soc Series B, 72(4):417-473.
set.seed(3) donors <- sprintf("D%02d", 1:20) donor <- rep(donors, each = 40) exposure <- stats::setNames(stats::rnorm(20), donors) counts <- matrix(stats::rpois(20 * length(donor), 20), nrow = 20, dimnames = list(paste0("G", 1:20), paste0("c", seq_along(donor)))) ## two genes rise and two fall with the exposure effect <- c(0.8, 0.8, -0.8, -0.8) for (g in 1:4) counts[g, ] <- stats::rpois(length(donor), 20 * exp(effect[g] * exposure[donor])) sce <- SingleCellExperiment::SingleCellExperiment( assays = list(counts = counts), colData = S4Vectors::DataFrame(donor_id = donor, cell_type = "Mono")) scee <- build_scee(sce, matrix(exposure, ncol = 1, dimnames = list(donors, "PM2.5")), sample_col = "donor_id") metabolites <- matrix(stats::rnorm(20 * 3), nrow = 20, dimnames = list(donors, paste0("M", 1:3))) metabolites[, "M1"] <- metabolites[, "M1"] + 1.5 * exposure if (requireNamespace("glasso", quietly = TRUE)) { net <- run_exposure_network(scee, metabolites, celltype = "Mono", exposure = "PM2.5", selection_method = "univariate", network_method = "block_glasso", transform = "log_cpm") net }set.seed(3) donors <- sprintf("D%02d", 1:20) donor <- rep(donors, each = 40) exposure <- stats::setNames(stats::rnorm(20), donors) counts <- matrix(stats::rpois(20 * length(donor), 20), nrow = 20, dimnames = list(paste0("G", 1:20), paste0("c", seq_along(donor)))) ## two genes rise and two fall with the exposure effect <- c(0.8, 0.8, -0.8, -0.8) for (g in 1:4) counts[g, ] <- stats::rpois(length(donor), 20 * exp(effect[g] * exposure[donor])) sce <- SingleCellExperiment::SingleCellExperiment( assays = list(counts = counts), colData = S4Vectors::DataFrame(donor_id = donor, cell_type = "Mono")) scee <- build_scee(sce, matrix(exposure, ncol = 1, dimnames = list(donors, "PM2.5")), sample_col = "donor_id") metabolites <- matrix(stats::rnorm(20 * 3), nrow = 20, dimnames = list(donors, paste0("M", 1:3))) metabolites[, "M1"] <- metabolites[, "M1"] + 1.5 * exposure if (requireNamespace("glasso", quietly = TRUE)) { net <- run_exposure_network(scee, metabolites, celltype = "Mono", exposure = "PM2.5", selection_method = "univariate", network_method = "block_glasso", transform = "log_cpm") net }
Runs fast gene set enrichment analysis (fgsea) on the
ranked gene list from run_sc_exwas, separately
for each cell type and exposure.
run_gsea( exwas_result, gene_sets, rank_by = "statistic", min_size = 10L, max_size = 500L )run_gsea( exwas_result, gene_sets, rank_by = "statistic", min_size = 10L, max_size = 500L )
exwas_result |
A |
gene_sets |
A named list of character vectors, one gene set
each. The genes are named as in the |
rank_by |
Character scalar naming the numeric column used to rank
genes. Default |
min_size |
Integer. Minimum gene set size. Default 10. |
max_size |
Integer. Maximum gene set size. Default 500. |
This function requires the fgsea package
(Bioconductor). Gene sets can come from any source, for example from
MSigDB via msigdbr::msigdbr(), as long as they use the identifiers
of the result.
Genes are ranked by the backend-specific association statistic (default) within each cell type, then fgsea is run per cell type. For edgeR QL this is the signed square root of the QL F statistic and is not a Wald z statistic. Results are combined with a final cross-cell-type FDR adjustment.
Ranking by the signed statistic preserves direction and
within-backend evidence ordering. Statistic magnitudes are not calibrated
for comparison across different backends; use
rank_by = "log2FC" when an effect-size ranking is the scientific
target.
fgsea estimates p-values by Monte Carlo sampling, so they depend on
the random number generator state. run_gsea() runs fgsea
serially, so calling set.seed() beforehand makes them reproducible.
When a gene appears more than once in a stratum, its largest ranking value
is kept.
A DataFrame with the fgsea columns pathway,
pval, padj (within cell type and exposure), log2err, ES, NES,
size and leadingEdge (semicolon-separated), plus celltype,
exposure and padj_global (Benjamini-Hochberg across all
cell types and exposures).
Korotkevich G et al. (2021). Fast gene set enrichment analysis. bioRxiv. doi:10.1101/060012
Subramanian A et al. (2005). Gene set enrichment analysis. PNAS 102:15545-15550. doi:10.1073/pnas.0506580102
set.seed(1) genes <- paste0("G", 1:200) exwas <- S4Vectors::DataFrame(gene = genes, celltype = "Mono", exposure = "PM2.5", statistic = c(stats::rnorm(20, mean = 3), stats::rnorm(180))) gene_sets <- list(shifted = genes[1:20], random = sample(genes, 25)) if (requireNamespace("fgsea", quietly = TRUE)) { run_gsea(exwas, gene_sets, min_size = 10L) }set.seed(1) genes <- paste0("G", 1:200) exwas <- S4Vectors::DataFrame(gene = genes, celltype = "Mono", exposure = "PM2.5", statistic = c(stats::rnorm(20, mean = 3), stats::rnorm(180))) gene_sets <- list(shifted = genes[1:20], random = sample(genes, 25)) if (requireNamespace("fgsea", quietly = TRUE)) { run_gsea(exwas, gene_sets, min_size = 10L) }
Formally tests whether an exposure effect differs across cell types using a pseudobulk interaction model. This prevents the common mistake of concluding "the exposure affects cell type A but not B" based on separate per- celltype p-values (Gelman & Stern 2006).
run_interaction_test( x, exposure, celltype_col = "cell_type", target_genes = NULL, covariates = NULL, min_cells = 10L, min_donors = 5L )run_interaction_test( x, exposure, celltype_col = "cell_type", target_genes = NULL, covariates = NULL, min_cells = 10L, min_donors = 5L )
x |
A |
exposure |
Character. Exposure variable name. |
celltype_col |
Character. |
target_genes |
Character vector (optional). Genes to test. Default: top 50 most variable genes across all cell types. |
covariates |
Character vector (optional). Columns of
|
min_cells |
Integer. Min cells per donor per celltype. Default 10. |
min_donors |
Integer. Min donors per celltype. Default 5. |
For each gene, pseudobulk log-CPM values of all cell types are stacked, one row per donor and cell type, and two linear models are compared with an F-test:
reduced: y ~ donor + celltype + covariates:celltype full: y ~ donor + celltype + covariates:celltype + exposure:celltype
Donor fixed effects absorb every donor-level quantity, including the exposure and covariate main effects, and the shared donor component of expression in different cell types, so the test compares exposure slopes between cell types through within-donor contrasts rather than treating cell types from the same donor as independent. Covariate-by-cell-type terms allow covariate effects to differ between cell types. Donors observed in only one cell type do not inform the interaction.
Comparing significance levels across cell types is not the same as testing for a difference between them (Gelman & Stern 2006, Nieuwenhuis et al. 2011); this function tests the difference directly.
A DataFrame with columns: gene,
p_interaction (F-test for the exposure-by-cell-type terms),
df_interaction (numerator degrees of freedom),
padj_interaction (BH-corrected), n_celltypes, n_donors.
Gelman A, Stern H (2006). The difference between 'significant' and 'not significant' is not itself statistically significant. Am Stat 60:328-331.
Nieuwenhuis S et al. (2011). Erroneous analyses of interactions in neuroscience. Nat Neurosci 14:1105-1107. doi:10.1038/nn.2886
library(SingleCellExperiment); library(S4Vectors) set.seed(1) counts <- matrix(rpois(5000, 8), nrow = 50, dimnames = list(paste0("G", 1:50), paste0("c", 1:100))) sce <- SingleCellExperiment(assays = list(counts = counts), colData = DataFrame(cell_id = paste0("c", 1:100), donor_id = rep(paste0("D", 1:10), each = 10), cell_type = rep(c("Mono", "NK"), 50))) exp_mat <- matrix(rnorm(20), nrow = 10, dimnames = list(paste0("D", 1:10), c("E1", "E2"))) scee <- build_scee(sce, exp_mat, sample_col = "donor_id") ix <- run_interaction_test(scee, exposure = "E1", celltype_col = "cell_type", min_cells = 3L, min_donors = 3L) head(ix)library(SingleCellExperiment); library(S4Vectors) set.seed(1) counts <- matrix(rpois(5000, 8), nrow = 50, dimnames = list(paste0("G", 1:50), paste0("c", 1:100))) sce <- SingleCellExperiment(assays = list(counts = counts), colData = DataFrame(cell_id = paste0("c", 1:100), donor_id = rep(paste0("D", 1:10), each = 10), cell_type = rep(c("Mono", "NK"), 50))) exp_mat <- matrix(rnorm(20), nrow = 10, dimnames = list(paste0("D", 1:10), c("E1", "E2"))) scee <- build_scee(sce, exp_mat, sample_col = "donor_id") ix <- run_interaction_test(scee, exposure = "E1", celltype_col = "cell_type", min_cells = 3L, min_donors = 3L) head(ix)
Combines independent-cohort sc-ExWAS estimates using inverse-variance weighted fixed-effect synthesis or random-effects synthesis. Keys are matched exactly on gene, cell type, and exposure.
run_meta_exwas( results_list, cohort_names = NULL, method = c("fixed", "random"), effect_col = NULL, se_col = NULL )run_meta_exwas( results_list, cohort_names = NULL, method = c("fixed", "random"), effect_col = NULL, se_col = NULL )
results_list |
A list of |
cohort_names |
Character vector with one unique name per cohort.
Defaults to |
method |
Character. |
effect_col |
Optional character scalar naming the effect column. When
|
se_col |
Optional character scalar naming the standard-error column.
When |
Fixed-effect synthesis uses
Random-effects synthesis uses restricted maximum likelihood for
and Hartung–Knapp small-sample inference. It is deliberately
unavailable for only two cohorts. The and Cochran Q statistics are
reported as heterogeneity diagnostics; they do not establish transportability
or independence of the contributing cohorts.
The function never maps gene identifiers or cell-type labels. Harmonisation
must occur before calling it. Within-cohort duplicate keys are an error,
preventing accidental double weighting after label aggregation.
Inverse-variance synthesis also rejects edgeR QL results from
run_sc_exwas, recognised by their method label or
their metadata, because the QL F test supplies no coefficient standard
errors. Use a backend that estimates valid coefficient standard errors for
each independent cohort before meta-analysis.
A DataFrame with one row per exact key and columns
meta_effect, meta_se, meta_statistic,
meta_df, meta_pvalue, meta_padj, I2,
Q_pvalue, tau2, n_cohorts, cohorts,
direction, and method. Under Hartung–Knapp inference
meta_statistic is a t statistic with meta_df degrees of
freedom; under fixed-effect synthesis it is a z statistic and
meta_df is Inf.
Borenstein M et al. (2009). Introduction to Meta-Analysis. Wiley.
Viechtbauer W (2010). Conducting meta-analyses in R with the metafor package. Journal of Statistical Software 36:1–48. doi:10.18637/jss.v036.i03
library(S4Vectors) r1 <- DataFrame( gene = c("A", "B"), celltype = "Mono", log2FC = c(0.5, -0.3), se = c(0.1, 0.15), exposure = "PM2.5" ) r2 <- DataFrame( gene = c("A", "B", "C"), celltype = "Mono", log2FC = c(0.4, -0.1, 0.2), se = c(0.12, 0.2, 0.1), exposure = "PM2.5" ) meta <- run_meta_exwas( list(r1, r2), cohort_names = c("CohortA", "CohortB") ) metalibrary(S4Vectors) r1 <- DataFrame( gene = c("A", "B"), celltype = "Mono", log2FC = c(0.5, -0.3), se = c(0.1, 0.15), exposure = "PM2.5" ) r2 <- DataFrame( gene = c("A", "B", "C"), celltype = "Mono", log2FC = c(0.4, -0.1, 0.2), se = c(0.12, 0.2, 0.1), exposure = "PM2.5" ) meta <- run_meta_exwas( list(r1, r2), cohort_names = c("CohortA", "CohortB") ) meta
Wraps qgcomp::qgcomp.noboot() or
qgcomp::qgcomp.boot() on pseudobulk data for
cell-type-specific exposure mixture analysis. Unlike
run_sc_mixture (simplified screening), it
reports a confidence interval and p-value for the overall
mixture effect and, without bootstrapping, the positive and
negative exposure weights estimated by qgcomp.
run_mixture_qgcomp( x, exposures, celltype, celltype_col = "cell_type", target_genes = NULL, covariates = NULL, q = 4L, bootstrap = FALSE, B = 200L, min_cells = 10L )run_mixture_qgcomp( x, exposures, celltype, celltype_col = "cell_type", target_genes = NULL, covariates = NULL, q = 4L, bootstrap = FALSE, B = 200L, min_cells = 10L )
x |
A |
exposures |
Character vector. Exposure variable names, distinct.
Each name must be a syntactic R name (see
|
celltype |
Character. Target cell type. |
celltype_col |
Character. |
target_genes |
Character vector (optional). Genes to summarise. Default: top 20 most variable. |
covariates |
Character vector (optional). Columns of
|
q |
Integer. Number of quantile bins. Default 4. |
bootstrap |
Logical. If |
B |
Integer. Number of bootstrap replicates (only if
|
min_cells |
Integer. Default 10. |
Quantile g-computation (Keil et al. 2020) estimates the overall effect of jointly increasing all exposures by one quantile, and without bootstrapping decomposes it into positive and negative contributions. The weights are interpretable only when the exposure effects are of a similar shape (Keil et al. 2020).
The pseudobulk response is the mean log-CPM of the target genes over donors with complete exposure and covariate data.
Without bootstrapping, mixture_pvalue is a two-sided t test of
on the residual degrees of freedom of the fitted model, and
ci_lower and ci_upper are the matching t interval.
qgcomp.noboot() itself uses the null degrees of freedom minus the
number of exposures for its p-value, which leaves the covariates out, and
a normal interval; its own values are kept in
metadata(result)$fit. With bootstrap = TRUE the p-value
and the interval are those of qgcomp.boot(); the call stops when
qgcomp.boot() returns no p-value for .
Comparison with run_sc_mixture:
| Feature | run_sc_mixture | run_mixture_qgcomp |
| CI for overall effect | No | Yes (t interval or bootstrap) |
| Pos/neg weights | No | Yes (without bootstrap) |
| P-value for overall effect | No | Yes |
| Speed | Fast | Moderate |
| Minimum n | 5 | 10+ recommended |
A one-row DataFrame with columns celltype,
mixture_effect (the overall mixture effect ),
mixture_se, ci_lower and ci_upper (95%
confidence interval for ), mixture_pvalue (for the
interval and the p-value see Details),
n_donors, n_genes and method
("qgcomp.noboot" or "qgcomp.boot").
metadata(result) holds:
Named numeric. Exposures that
increase the response, with relative weights;
NULL when bootstrap = TRUE, because
qgcomp.boot() does not estimate weights.
Named numeric. Exposures that
decrease the response; NULL when
bootstrap = TRUE.
The genes whose mean log-CPM is the response.
The qgcomp model object (for
plotting and further analysis).
Keil AP et al. (2020). A quantile-based g-computation approach to addressing the effects of exposure mixtures. Environ Health Perspect 128:047004. doi:10.1289/EHP5838
# Requires the qgcomp package library(SingleCellExperiment); library(S4Vectors) set.seed(1) counts <- matrix(rpois(5000, 8), nrow = 50, dimnames = list(paste0("G", 1:50), paste0("c", 1:100))) sce <- SingleCellExperiment(assays = list(counts = counts), colData = DataFrame(cell_id = paste0("c", 1:100), donor_id = rep(paste0("D", 1:10), each = 10), cell_type = rep(c("Mono", "NK"), 50))) exp_mat <- matrix(rnorm(30), nrow = 10, dimnames = list(paste0("D", 1:10), c("E1", "E2", "E3"))) scee <- build_scee(sce, exp_mat, sample_col = "donor_id") if (requireNamespace("qgcomp", quietly = TRUE)) { mix <- run_mixture_qgcomp(scee, exposures = c("E1", "E2", "E3"), celltype = "Mono", celltype_col = "cell_type", min_cells = 3L) mix metadata(mix)$positive_weights metadata(mix)$negative_weights }# Requires the qgcomp package library(SingleCellExperiment); library(S4Vectors) set.seed(1) counts <- matrix(rpois(5000, 8), nrow = 50, dimnames = list(paste0("G", 1:50), paste0("c", 1:100))) sce <- SingleCellExperiment(assays = list(counts = counts), colData = DataFrame(cell_id = paste0("c", 1:100), donor_id = rep(paste0("D", 1:10), each = 10), cell_type = rep(c("Mono", "NK"), 50))) exp_mat <- matrix(rnorm(30), nrow = 10, dimnames = list(paste0("D", 1:10), c("E1", "E2", "E3"))) scee <- build_scee(sce, exp_mat, sample_col = "donor_id") if (requireNamespace("qgcomp", quietly = TRUE)) { mix <- run_mixture_qgcomp(scee, exposures = c("E1", "E2", "E3"), celltype = "Mono", celltype_col = "cell_type", min_cells = 3L) mix metadata(mix)$positive_weights metadata(mix)$negative_weights }
Convenience wrapper that runs run_sc_exwas
for each exposure and combines results with a final
global FDR correction across all exposures and cell types.
run_multi_exwas( x, exposures = NULL, celltype_col = "cell_type", covariates = NULL, min_cells = 10L, min_donors = 5L, filter_genes = TRUE, ... )run_multi_exwas( x, exposures = NULL, celltype_col = "cell_type", covariates = NULL, min_cells = 10L, min_donors = 5L, filter_genes = TRUE, ... )
x |
A |
exposures |
Character vector. Exposure names to test.
Default: all exposures in |
celltype_col |
Character. |
covariates |
Character vector (optional). Columns of
|
min_cells |
Integer. Default 10. |
min_donors |
Integer. Default 5. |
filter_genes |
Logical. Default TRUE. |
... |
Further arguments of |
If run_sc_exwas stops for one of the exposures, the call stops
too, with an error that names the exposure, instead of leaving that
exposure out of padj_all. A cell type that run_sc_exwas
skips for an exposure with a warning, for example for too few donors
with complete data, adds no tests to padj_all; the diagnostics
in metadata(result)$per_exposure list the cell types fitted for
each exposure.
A DataFrame with all results combined and
padj_all for global FDR across all tests. The se and
statistic fields retain the selected backend's semantics: edgeR QL
has numeric-NA coefficient standard errors and a signed square-root
QL F statistic, whereas DESeq2 and voom-dream return their coefficient
standard errors with Wald and moderated t statistics, respectively.
The columns are those of run_sc_exwas followed by
padj_all; metadata(result)$per_exposure keeps the
metadata() (parameters and diagnostics) of each exposure's
run_sc_exwas result.
library(SingleCellExperiment); library(S4Vectors) set.seed(1) counts <- matrix(rpois(5000, 8), nrow = 50, dimnames = list(paste0("G", 1:50), paste0("c", 1:100))) sce <- SingleCellExperiment(assays = list(counts = counts), colData = DataFrame(cell_id = paste0("c", 1:100), donor_id = rep(paste0("D", 1:5), each = 20), cell_type = rep(c("Mono", "NK"), 50))) exp_mat <- matrix(rnorm(15), nrow = 5, dimnames = list(paste0("D", 1:5), c("E1", "E2", "E3"))) scee <- build_scee(sce, exp_mat, sample_col = "donor_id") multi <- run_multi_exwas(scee, exposures = c("E1", "E2"), celltype_col = "cell_type", min_cells = 5L, min_donors = 3L) head(multi)library(SingleCellExperiment); library(S4Vectors) set.seed(1) counts <- matrix(rpois(5000, 8), nrow = 50, dimnames = list(paste0("G", 1:50), paste0("c", 1:100))) sce <- SingleCellExperiment(assays = list(counts = counts), colData = DataFrame(cell_id = paste0("c", 1:100), donor_id = rep(paste0("D", 1:5), each = 20), cell_type = rep(c("Mono", "NK"), 50))) exp_mat <- matrix(rnorm(15), nrow = 5, dimnames = list(paste0("D", 1:5), c("E1", "E2", "E3"))) scee <- build_scee(sce, exp_mat, sample_col = "donor_id") multi <- run_multi_exwas(scee, exposures = c("E1", "E2"), celltype_col = "cell_type", min_cells = 5L, min_donors = 3L) head(multi)
Performs pseudobulk differential expression analysis with a continuous exposure variable as covariate. Aggregates counts within each donor-celltype stratum to avoid pseudoreplication, then uses an empirical-Bayes pseudobulk model for inference.
run_sc_exwas(x, ...) ## S4 method for signature 'SingleCellExposomeExperiment' run_sc_exwas( x, exposure, celltype_col = "cell_type", celltypes = NULL, covariates = NULL, min_cells = 10L, min_donors = 5L, filter_genes = TRUE, method = c("edgeR", "DESeq2", "voom_dream"), min_group_donors = 5L, filter_min_count = 10L, filter_min_total_count = 15L, filter_method = c("fixed_support", "filterByExpr"), filter_min_cpm = 1, filter_min_donors = 5L, test_features = NULL, robust = TRUE, ... )run_sc_exwas(x, ...) ## S4 method for signature 'SingleCellExposomeExperiment' run_sc_exwas( x, exposure, celltype_col = "cell_type", celltypes = NULL, covariates = NULL, min_cells = 10L, min_donors = 5L, filter_genes = TRUE, method = c("edgeR", "DESeq2", "voom_dream"), min_group_donors = 5L, filter_min_count = 10L, filter_min_total_count = 15L, filter_method = c("fixed_support", "filterByExpr"), filter_min_cpm = 1, filter_min_donors = 5L, test_features = NULL, robust = TRUE, ... )
x |
A |
... |
Must be empty. Any further argument is an error, so that a misspelled argument name cannot silently change the analysis. |
exposure |
Character. Name of the exposure variable
(column in |
celltype_col |
Character. Column in |
celltypes |
Character vector (optional). Which cell types to test. Default: all. |
covariates |
Character vector (optional). Additional
covariates from |
min_cells |
Integer. Minimum cells per donor-celltype stratum. Default 10. |
min_donors |
Integer. Minimum donors per cell type. Default 5, and at least 3, for every backend. Cell types with fewer valid donors are skipped with a warning. |
filter_genes |
Logical. If |
method |
Character. Backend for differential expression.
|
min_group_donors |
Integer. For a binary exposure, minimum complete donors required in each group for the edgeR backend, at least 2. Default 5. |
filter_min_count |
Numeric. Minimum count passed to
|
filter_min_total_count |
Numeric. Minimum total pseudobulk count for either edgeR filtering method. |
filter_method |
Character. edgeR expression-filtering rule.
|
filter_min_cpm |
Numeric. CPM threshold for
|
filter_min_donors |
Integer. Minimum number of independent donors
meeting |
test_features |
Optional character vector of feature identifiers that defines the reported hypothesis family. Library-size calculation, expression filtering, normalisation and dispersion estimation still use all available features; subsetting occurs only after model fitting. Every requested feature must pass the pre-specified expression filter in every tested cell type, otherwise the call fails rather than silently changing the requested hypothesis family. Currently supported only by the edgeR backend; other backends fail explicitly rather than ignoring it. |
robust |
Logical. For the edgeR backend, moderate the
quasi-likelihood dispersions with robust empirical Bayes
( |
The pseudobulk approach aggregates single-cell counts
within each (donor x cell type) stratum, creating one
observation per donor per cell type. This correctly
treats cells from the same donor as non-independent,
avoiding the inflated Type I error rates that plague
cell-level analyses (Squair et al. 2021, Nat Commun).
The pseudobulk counts that enter the models are available as
SummarizedExperiment objects from donor_pseudobulk.
The exposure variable and specified covariates enter one donor-level design
matrix. The default edgeR backend fits the edgeR v4 quasi-likelihood
model, glmQLFit(legacy = FALSE), which sets the negative-binomial
dispersion internally from the most highly expressed genes and moderates
the quasi-likelihood dispersions by empirical Bayes; the exposure
coefficient is tested with a quasi-likelihood F-test (Chen et al. 2025).
No separate estimateDisp() step is run: from edgeR 4.10.0 the
method gives the same result whether or not the data hold such estimates,
whereas earlier edgeR 4.x releases did not. The edgeR version and
legacy = FALSE are recorded in metadata(result)$parameters.
Complete-transcriptome library sizes are retained when expression
filtering or test_features restricts the reported hypothesis
family.
edgeR::glmQLFTest does not return a coefficient standard error.
Consequently, the edgeR backend never reconstructs se from the ratio
of the log-fold change to the QL statistic. Its statistic field is a
directional ranking representation of the QL F statistic, not a Wald z or
t statistic, and must not be used to derive a coefficient confidence
interval. The edgeR result metadata records
se_method = "not_available_edgeR_QL" and
statistic_type = "signed_sqrt_qlf".
What is delegated and what is kept. The raw counts of each
donor and cell type are summed with
scrapper::aggregateAcrossCells(), and the models are fitted by
edgeR, DESeq2 or variancePartition and limma.
Four choices are made by exposomeSC itself, on purpose, because
they define the hypotheses of an exposome-wide study:
The exposure is a donor-level variable from
exposureData(x), continuous or binary, and enters the design
matrix together with the covariates; cells are never grouped by
exposure.
Gene filtering does not use the exposure. The default edgeR rule
(filter_method = "fixed_support") keeps genes with at least
filter_min_cpm CPM in filter_min_donors donors, and the
DESeq2 and voom-dream backends keep genes detected in at least 20%
of donors (and in at least two); which genes are tested therefore
does not depend on the exposure values. By contrast,
scran::pseudoBulkDGE(), for example, filters each label with
edgeR::filterByExpr() using the design matrix.
In the edgeR backend the library sizes are the column sums of the
complete pseudobulk transcriptome, computed before filtering, and are
kept when filtering or test_features reduces the tested genes.
The voom-dream backend computes library sizes from the retained genes
and DESeq2 uses its own size factors.
padj_global applies the Benjamini-Hochberg procedure once
across all tested gene-by-cell-type hypotheses, next to the
within-cell-type padj.
A DataFrame with one row per tested gene and cell type and
the same columns, in the same order, for every backend: gene,
celltype, log2FC, se, statistic,
pvalue, pvalue_underflow_clamped (TRUE where a
p-value of exactly zero was replaced by the smallest positive double),
padj (BH within the cell type), padj_global (BH across all
tested gene-by-cell-type hypotheses), logCPM, exposure,
n_donors, n_unexposed and n_exposed (group sizes
when the exposure takes two values, otherwise NA),
min_cells and median_cells (cells per donor in the
cell type), and method. Rows are ordered by padj_global,
then pvalue.
logCPM is the average log2 count per million reported by the
backend: edgeR's logCPM for the edgeR backend, the mean of the
voom log-CPM values for voom-dream, and edgeR::aveLogCPM() of the
filtered pseudobulk counts for DESeq2.
Uncertainty fields are backend-specific: edgeR QL reports se as
numeric NA and statistic as the directional signed square
root of the QL F statistic; DESeq2 reports its coefficient standard error
and Wald statistic; voom-dream reports the moderated standard error
(|log2FC / t|) and the moderated t statistic.
metadata(result)$parameters records the settings, the backend and
its package version, se_method and statistic_type;
metadata(result)$diagnostics holds, for each fitted cell type,
the donors used, the numbers of genes before and after filtering and the
design columns; for the edgeR backend also dropped_design_columns,
the covariate columns left out of the design as collinear (each is also
reported in a warning), and residual_df, the smallest adjusted
residual degrees of freedom over the fitted genes
(df.residual.adj).
Squair JW et al. (2021). Confronting false discoveries in single-cell differential expression. Nat Commun 12:5692. doi:10.1038/s41467-021-25960-2
Chen Y, Chen L, Lun ATL, Baldoni PL, Smyth GK (2025). edgeR v4: powerful differential analysis of sequencing data with expanded functionality and improved support for small counts and larger datasets. Nucleic Acids Research 53(2):gkaf018. doi:10.1093/nar/gkaf018
Hoffman GE, Roussos P (2021). Dream: powerful differential expression analysis for repeated measures designs. Bioinformatics 37(2):192–201. doi:10.1093/bioinformatics/btaa687
Hoffman GE, Schadt EE (2016). variancePartition: interpreting drivers of variation in complex gene expression studies. BMC Bioinformatics 17:483. doi:10.1186/s12859-016-1323-z
donor_pseudobulk for the pseudobulk counts,
run_multi_exwas for several exposures.
library(SingleCellExperiment) library(S4Vectors) set.seed(1) counts <- matrix(rpois(5000, 8), nrow = 50, dimnames = list(paste0("G", 1:50), paste0("c", 1:100))) sce <- SingleCellExperiment(assays = list(counts = counts), colData = DataFrame(cell_id = paste0("c", 1:100), donor_id = rep(paste0("D", 1:5), each = 20), cell_type = rep(c("Mono", "NK"), 50))) exp_mat <- matrix(rnorm(15), nrow = 5, dimnames = list(paste0("D", 1:5), c("E1", "E2", "E3"))) scee <- build_scee(sce, exp_mat, sample_col = "donor_id") result <- run_sc_exwas(scee, exposure = "E1", celltype_col = "cell_type", min_cells = 5L) head(result) metadata(result)$parameters$statistic_typelibrary(SingleCellExperiment) library(S4Vectors) set.seed(1) counts <- matrix(rpois(5000, 8), nrow = 50, dimnames = list(paste0("G", 1:50), paste0("c", 1:100))) sce <- SingleCellExperiment(assays = list(counts = counts), colData = DataFrame(cell_id = paste0("c", 1:100), donor_id = rep(paste0("D", 1:5), each = 20), cell_type = rep(c("Mono", "NK"), 50))) exp_mat <- matrix(rnorm(15), nrow = 5, dimnames = list(paste0("D", 1:5), c("E1", "E2", "E3"))) scee <- build_scee(sce, exp_mat, sample_col = "donor_id") result <- run_sc_exwas(scee, exposure = "E1", celltype_col = "cell_type", min_cells = 5L) head(result) metadata(result)$parameters$statistic_type
Fits, per gene, the cell-level model
y ~ exposure * celltype + covariates + (1 | donor) +
(1 | donor:celltype) and reports
cell-type-specific exposure effects. For family = "gaussian" the
model is a linear mixed model fitted by lmerTest::lmer with
REML = TRUE (mandatory), and p-values are referred to a finite
denominator degrees of freedom – Satterthwaite (default) or
Kenward-Roger – via lmerTest::contest1D. A Wald test
referred to the normal distribution would be anticonservative with few
donors.
run_sc_exwas_glmm( x, exposure, celltype_col = "cell_type", covariates = NULL, target_genes = NULL, ddf = c("Satterthwaite", "Kenward-Roger"), family = c("gaussian", "nbinom"), BPPARAM = BiocParallel::SerialParam() )run_sc_exwas_glmm( x, exposure, celltype_col = "cell_type", covariates = NULL, target_genes = NULL, ddf = c("Satterthwaite", "Kenward-Roger"), family = c("gaussian", "nbinom"), BPPARAM = BiocParallel::SerialParam() )
x |
A |
exposure |
Character; a donor-level column of |
celltype_col |
Character. Column in |
covariates |
Character vector; donor covariate columns in
|
target_genes |
Character; genes to test (default: all rows of
|
ddf |
Denominator degrees-of-freedom method for
|
family |
|
BPPARAM |
A |
Why REML. Maximum likelihood biases the variance components
downward, which shrinks the residual scale and inflates the exposure
-statistic; the Kenward-Roger adjusted covariance and the
Satterthwaite degrees-of-freedom approximation are both defined only on the
REML fit. The function therefore forces REML = TRUE and does not
expose a switch.
Random effects. The exposure varies between donors, so the
replicates for a cell-type-specific exposure effect are donor-by-cell-type
units, not cells. The model therefore includes a donor-by-cell-type random
intercept as well as a donor random intercept; without it, variation shared
by the cells of one donor and cell type is treated as independent and the
cell-type-specific tests are anticonservative. With a single cell type the
model reduces to y ~ exposure + covariates + (1 | donor). A variance
component estimated at zero (a singular fit) is expected when that source
of variation is absent and is not reported.
Cell-type-specific effects. Under treatment contrasts the
exposure coefficient is the effect at the reference cell type and each
exposure:celltype coefficient is a difference from it. Each cell
type's effect is therefore a linear combination of fixed effects, tested with
contest1D so that the degrees of freedom and standard error account
for the covariance between the main effect and the interaction.
family = "nbinom". Satterthwaite and Kenward-Roger are linear
-mixed-model constructions and do not extend to a generalised LMM, so the
negative-binomial path fits lme4::glmer.nb on an equivalent
cell-type-nested reparametrisation of exposure * celltype (one
exposure slope column per cell type) and tests each cell type's effect by a
likelihood-ratio test (anova of the full versus the column-dropped
model) – again not a Wald-normal test. This path is markedly more expensive
(one glmer.nb refit per cell type per gene); for count data prefer the
donor-level run_sc_exwas_pb_offset, which is calibration-
equivalent and far faster (Lee & Han 2024). The ddf argument is
ignored for family = "nbinom".
Missing values. The cells of a donor whose exposure or a covariate is missing, and cells without a cell-type label, are left out, with a message, before either family is fitted, so that the full and reduced models of a likelihood-ratio test use the same cells.
A DataFrame, one row per gene x cell type: gene,
celltype, log2FC, se, statistic (Satterthwaite
/KR for gaussian, LR for nbinom), df (finite
denominator df; 1 for the nbinom LRT), pvalue, padj_global
(BH across all gene-by-cell-type strata, as in
run_sc_exwas; there is no within-cell-type padj),
and method. Rows ordered by padj_global, then
pvalue. A gene-by-cell-type stratum that cannot be fitted is
left out of the result; with family = "nbinom", a stratum whose
likelihood-ratio test cannot be computed is kept with NA
pvalue and padj_global. Its statistic is NA
when the reduced model or anova() fails, and close to 0 when the
test has no degrees of freedom, as when a covariate is a linear
function of the exposure. padj_global adjusts over the strata
with a p-value, and the function stops when no stratum can be fitted.
Calibrate against a donor-permutation null, with the exposure permuted across donors, before quoting any type-I rate; Satterthwaite/KR control the finite-sample error only under the working model, so the empirical check is the headline.
Kuznetsova A, Brockhoff PB & Christensen RHB (2017). lmerTest package: tests in linear mixed effects models. J Stat Softw 82(13).
Kenward MG & Roger JH (1997). Small sample inference for fixed effects from restricted maximum likelihood. Biometrics 53:983-997.
Halekoh U & Hojsgaard S (2014). A Kenward-Roger approximation and parametric bootstrap methods for tests in linear mixed models – the R package pbkrtest. J Stat Softw 59(9).
run_sc_exwas_pb_offset for the donor-level default.
donor_ids <- paste0("D", seq_len(10L)) exposure <- rep(c(0, 1), each = 5L) cell_donor <- rep(donor_ids, each = 12L) cell_type <- rep( rep(c("TypeA", "TypeB"), each = 6L), times = length(donor_ids) ) cell_ids <- paste0("cell", seq_along(cell_donor)) counts <- outer( seq_len(2L), seq_along(cell_ids), function(gene, cell) 2L + ((7L * gene + 5L * cell) %% 11L) ) exposed_type_a <- exposure[match(cell_donor, donor_ids)] == 1 & cell_type == "TypeA" counts[1L, exposed_type_a] <- counts[1L, exposed_type_a] + 3L storage.mode(counts) <- "integer" dimnames(counts) <- list(c("G1", "G2"), cell_ids) sce <- SingleCellExperiment::SingleCellExperiment( assays = list(counts = counts), colData = S4Vectors::DataFrame( cell_id = cell_ids, donor_id = cell_donor, cell_type = cell_type ) ) donor_design <- matrix(exposure, ncol = 1L, dimnames = list(donor_ids, "exposure")) scee <- build_scee(sce, donor_design, sample_col = "donor_id") if (requireNamespace("lme4", quietly = TRUE) && requireNamespace("lmerTest", quietly = TRUE)) { mixed_result <- run_sc_exwas_glmm( scee, exposure = "exposure", celltype_col = "cell_type", target_genes = "G1", family = "gaussian", BPPARAM = BiocParallel::SerialParam() ) mixed_result }donor_ids <- paste0("D", seq_len(10L)) exposure <- rep(c(0, 1), each = 5L) cell_donor <- rep(donor_ids, each = 12L) cell_type <- rep( rep(c("TypeA", "TypeB"), each = 6L), times = length(donor_ids) ) cell_ids <- paste0("cell", seq_along(cell_donor)) counts <- outer( seq_len(2L), seq_along(cell_ids), function(gene, cell) 2L + ((7L * gene + 5L * cell) %% 11L) ) exposed_type_a <- exposure[match(cell_donor, donor_ids)] == 1 & cell_type == "TypeA" counts[1L, exposed_type_a] <- counts[1L, exposed_type_a] + 3L storage.mode(counts) <- "integer" dimnames(counts) <- list(c("G1", "G2"), cell_ids) sce <- SingleCellExperiment::SingleCellExperiment( assays = list(counts = counts), colData = S4Vectors::DataFrame( cell_id = cell_ids, donor_id = cell_donor, cell_type = cell_type ) ) donor_design <- matrix(exposure, ncol = 1L, dimnames = list(donor_ids, "exposure")) scee <- build_scee(sce, donor_design, sample_col = "donor_id") if (requireNamespace("lme4", quietly = TRUE) && requireNamespace("lmerTest", quietly = TRUE)) { mixed_result <- run_sc_exwas_glmm( scee, exposure = "exposure", celltype_col = "cell_type", target_genes = "G1", family = "gaussian", BPPARAM = BiocParallel::SerialParam() ) mixed_result }
A donor-level negative-binomial alternative to run_sc_exwas.
Per cell type and per gene, aggregates cells to a donor pseudobulk count and
fits a negative-binomial GLM with a library-size offset
. Lee and Han (2024) report
that pseudobulk models with proper offsets have the same statistical
properties as generalised linear mixed models in single-cell case-control
studies, without the pseudoreplication that inflates cell-level tests.
P-values are Wald tests with an estimated dispersion and can be
anticonservative when there are few donors. The function has no threshold
on the number of cells: every donor with at least one cell of a cell type
enters the model of that cell type, where run_sc_exwas
leaves out a donor with fewer than min_cells cells.
run_sc_exwas_pb_offset( x, exposure, celltype_col = "cell_type", covariates = NULL, target_genes = NULL, BPPARAM = BiocParallel::SerialParam() )run_sc_exwas_pb_offset( x, exposure, celltype_col = "cell_type", covariates = NULL, target_genes = NULL, BPPARAM = BiocParallel::SerialParam() )
x |
A |
exposure |
Character; a donor-level column of |
celltype_col |
Character. Column in |
covariates |
Character vector; donor covariate columns in
|
target_genes |
Character; genes to test (default: all rows of
|
BPPARAM |
A |
A DataFrame, one row per gene x cell type:
gene, celltype, log2FC (exposure effect on the
rate scale), se (on the same scale), statistic
(donor-level Wald z from the NB GLM), pvalue, and
padj_global (BH across all tested gene-by-cell-type strata, as
in run_sc_exwas; there is no within-cell-type
padj). Rows ordered by padj_global, then pvalue.
A gene whose GLM cannot be fitted gets NA estimates; the
function stops when no cell type has at least three donors with cells.
Report empirical calibration from a donor-permutation null, with the exposure permuted across donors, before quoting any type-I rate.
Lee H & Han B (2024). Pseudobulk with proper offsets has the same statistical properties as generalized linear mixed models in single-cell case-control studies. Bioinformatics 40(8):btae498. doi:10.1093/bioinformatics/btae498
Squair JW et al. (2021). Confronting false discoveries in single-cell differential expression. Nat Commun 12:5692.
run_sc_exwas_glmm for the cell-level LMM reference.
donor_ids <- paste0("D", seq_len(10L)) exposure <- rep(c(0, 1), each = 5L) cell_donor <- rep(donor_ids, each = 10L) cell_type <- rep("TypeA", length(cell_donor)) cell_ids <- paste0("cell", seq_along(cell_donor)) pb_targets <- rbind( G1 = c(30, 140, 50, 180, 40, 110, 260, 70, 220, 130), G2 = c(200, 40, 240, 60, 300, 50, 270, 80, 330, 70), G3 = c(100, 120, 90, 150, 110, 130, 170, 100, 160, 140), G4 = c(250, 200, 300, 180, 270, 220, 320, 210, 290, 230) ) counts <- matrix(0L, nrow = 4L, ncol = length(cell_ids)) for (donor in seq_along(donor_ids)) { counts[, cell_donor == donor_ids[donor]] <- pb_targets[, donor] / 10L } storage.mode(counts) <- "integer" dimnames(counts) <- list(paste0("G", seq_len(4L)), cell_ids) sce <- SingleCellExperiment::SingleCellExperiment( assays = list(counts = counts), colData = S4Vectors::DataFrame( cell_id = cell_ids, donor_id = cell_donor, cell_type = cell_type ) ) donor_design <- matrix(exposure, ncol = 1L, dimnames = list(donor_ids, "exposure")) scee <- build_scee(sce, donor_design, sample_col = "donor_id") offset_result <- run_sc_exwas_pb_offset( scee, exposure = "exposure", celltype_col = "cell_type", target_genes = c("G1", "G2"), BPPARAM = BiocParallel::SerialParam() ) head(offset_result)donor_ids <- paste0("D", seq_len(10L)) exposure <- rep(c(0, 1), each = 5L) cell_donor <- rep(donor_ids, each = 10L) cell_type <- rep("TypeA", length(cell_donor)) cell_ids <- paste0("cell", seq_along(cell_donor)) pb_targets <- rbind( G1 = c(30, 140, 50, 180, 40, 110, 260, 70, 220, 130), G2 = c(200, 40, 240, 60, 300, 50, 270, 80, 330, 70), G3 = c(100, 120, 90, 150, 110, 130, 170, 100, 160, 140), G4 = c(250, 200, 300, 180, 270, 220, 320, 210, 290, 230) ) counts <- matrix(0L, nrow = 4L, ncol = length(cell_ids)) for (donor in seq_along(donor_ids)) { counts[, cell_donor == donor_ids[donor]] <- pb_targets[, donor] / 10L } storage.mode(counts) <- "integer" dimnames(counts) <- list(paste0("G", seq_len(4L)), cell_ids) sce <- SingleCellExperiment::SingleCellExperiment( assays = list(counts = counts), colData = S4Vectors::DataFrame( cell_id = cell_ids, donor_id = cell_donor, cell_type = cell_type ) ) donor_design <- matrix(exposure, ncol = 1L, dimnames = list(donor_ids, "exposure")) scee <- build_scee(sce, donor_design, sample_col = "donor_id") offset_result <- run_sc_exwas_pb_offset( scee, exposure = "exposure", celltype_col = "cell_type", target_genes = c("G1", "G2"), BPPARAM = BiocParallel::SerialParam() ) head(offset_result)
Estimates the relative contribution of multiple correlated exposures to gene expression within a specific cell type using a simplified quantile-scored linear model on pseudobulk data.
run_sc_mixture( x, exposures, celltype, celltype_col = "cell_type", target_genes = NULL, covariates = NULL, q = 4L, min_cells = 10L )run_sc_mixture( x, exposures, celltype, celltype_col = "cell_type", target_genes = NULL, covariates = NULL, q = 4L, min_cells = 10L )
x |
A |
exposures |
Character vector. Exposure variable names, distinct.
Each name must be a syntactic R name (see
|
celltype |
Character. Which cell type to analyse. |
celltype_col |
Character. |
target_genes |
Character vector (optional). Genes to test. Default: top 20 most variable genes. |
covariates |
Character vector (optional). Additional
covariates from |
q |
Integer. Number of quantile bins, at least 2. Default 4. Tied exposure values (for example at a limit of detection) can give fewer bins. |
min_cells |
Integer. Minimum cells per donor. Default 10. |
This is a simplified screening method, not a formal quantile-based g-computation (Keil et al. 2020) or weighted quantile sum regression (Carrico et al. 2015). The approach:
Donors with a missing exposure or covariate are
removed, and exposures are scored into quantile bins
(1 to q; fewer when quantiles are tied).
For each target gene, a linear model is fit on pseudobulk log-CPM with all quantile-scored exposures and covariates as predictors.
Weights are the absolute coefficients of the exposures that
have one, averaged across target genes and normalised to sum to 1;
an exposure without an estimable coefficient gets the weight
NA (see Value).
Because every exposure is on the same quantile scale,
the coefficients are directly comparable.
Limitations:
No bootstrap confidence intervals on weights.
Does not separate positive/negative weight directions as in formal qgcomp.
Log-CPM may have heteroscedasticity at low counts.
For rigorous mixture analyses suitable for publication,
consider qgcomp::qgcomp.noboot() or
gWQS::gwqs() applied to the pseudobulk counts
returned by donor_pseudobulk, or
run_mixture_qgcomp.
A DataFrame with one row per target gene with a fitted
model: gene and mixture_effect (the sum of that gene's
estimable quantile-scored exposure coefficients; NA when none
is estimable).
metadata(result) holds:
Named numeric vector. Relative contribution
of each exposure (the weights that are not NA sum to 1):
the mean over target genes of the absolute coefficients of the
quantile-scored exposures, normalised. When the quantile scores of
exposures are collinear, for example for two exposures with the
same ranks, lm() estimates a coefficient only for the one
listed first in exposures; it carries their joint effect,
and the later ones get the weight NA, with a warning. When
no coefficient can be estimated, every weight is NA.
Overall mixture coefficient (sum of
quantile-scored exposure coefficients, averaged across
target genes); NA when no coefficient can be estimated.
Character. Always "quantile_linear".
Character. Cell type analysed.
Integer. Donors with complete exposure and covariate data used in the analysis.
Integer. Genes with a fitted model.
Keil AP et al. (2020). A quantile-based g-computation approach to addressing the effects of exposure mixtures. Environ Health Perspect 128:047004. doi:10.1289/EHP5838
Carrico C et al. (2015). Characterization of weighted quantile sum regression for highly correlated data in a risk analysis setting. J Agric Biol Environ Stat 20:100-120.
library(SingleCellExperiment); library(S4Vectors) set.seed(1) counts <- matrix(rpois(5000, 8), nrow = 50, dimnames = list(paste0("G", 1:50), paste0("c", 1:100))) sce <- SingleCellExperiment(assays = list(counts = counts), colData = DataFrame(cell_id = paste0("c", 1:100), donor_id = rep(paste0("D", 1:10), each = 10), cell_type = rep(c("Mono", "NK"), 50))) exp_mat <- matrix(rnorm(30), nrow = 10, dimnames = list(paste0("D", 1:10), c("E1", "E2", "E3"))) scee <- build_scee(sce, exp_mat, sample_col = "donor_id") mix <- run_sc_mixture(scee, exposures = c("E1", "E2", "E3"), celltype = "Mono", celltype_col = "cell_type", min_cells = 3L) metadata(mix)$weightslibrary(SingleCellExperiment); library(S4Vectors) set.seed(1) counts <- matrix(rpois(5000, 8), nrow = 50, dimnames = list(paste0("G", 1:50), paste0("c", 1:100))) sce <- SingleCellExperiment(assays = list(counts = counts), colData = DataFrame(cell_id = paste0("c", 1:100), donor_id = rep(paste0("D", 1:10), each = 10), cell_type = rep(c("Mono", "NK"), 50))) exp_mat <- matrix(rnorm(30), nrow = 10, dimnames = list(paste0("D", 1:10), c("E1", "E2", "E3"))) scee <- build_scee(sce, exp_mat, sample_col = "donor_id") mix <- run_sc_mixture(scee, exposures = c("E1", "E2", "E3"), celltype = "Mono", celltype_col = "cell_type", min_cells = 3L) metadata(mix)$weights
Extracts donor-level metadata from a Seurat object's
meta.data and formats it as an exposure matrix
for build_scee.
seurat_to_exposure(seurat_meta, sample_col, exposure_cols)seurat_to_exposure(seurat_meta, sample_col, exposure_cols)
seurat_meta |
A data.frame (from
|
sample_col |
Character. Column with donor IDs. |
exposure_cols |
Character vector. Columns to use as exposures. |
A numeric matrix (donors x exposures). Each value is the mean over the donor's cells; a warning names columns whose values vary within a donor, and non-numeric columns are an error.
meta <- data.frame( donor = rep(c("D1","D2","D3"), each = 10), PM2.5 = rep(c(12, 25, 8), each = 10), age = rep(c(45, 32, 67), each = 10)) exp_mat <- seurat_to_exposure(meta, sample_col = "donor", exposure_cols = c("PM2.5", "age")) dim(exp_mat)meta <- data.frame( donor = rep(c("D1","D2","D3"), each = 10), PM2.5 = rep(c(12, 25, 8), each = 10), age = rep(c(45, 32, 67), each = 10)) exp_mat <- seurat_to_exposure(meta, sample_col = "donor", exposure_cols = c("PM2.5", "age")) dim(exp_mat)
Generates donor-level metabolite data and cell-type-specific transcript pseudobulk counts whose latent log-expression follows a known Gaussian graphical model, with cell-type heterogeneity and optional exposure-dependent composition. Intended for benchmarking edge recovery and false-positive control.
simulate_crossomic_network( n_donors = 100L, n_celltypes = 4L, n_transcripts = 30L, n_metabolites = 10L, n_cells_per_donor = 200L, edge_density = 0.1, shared_edge_frac = 0.6, cross_omic_frac = 0.2, exposure_effect = 0.5, composition_confounding = TRUE, seed = NULL )simulate_crossomic_network( n_donors = 100L, n_celltypes = 4L, n_transcripts = 30L, n_metabolites = 10L, n_cells_per_donor = 200L, edge_density = 0.1, shared_edge_frac = 0.6, cross_omic_frac = 0.2, exposure_effect = 0.5, composition_confounding = TRUE, seed = NULL )
n_donors |
Integer; number of donors. Default 100. |
n_celltypes |
Integer; number of cell types. Default 4. |
n_transcripts |
Integer; number of transcript features. Default 30. |
n_metabolites |
Integer; number of metabolite features. Default 10. |
n_cells_per_donor |
Integer; cells per donor, allocated to cell types by the composition. Pseudobulk depth scales with the number of cells. Default 200. |
edge_density |
Numeric; proportion of possible edges present in the base network. Default 0.1. |
shared_edge_frac |
Numeric; fraction of base-network edges kept by cell types 1 and 2, each of which also gains the same number of new edges. Default 0.6. |
cross_omic_frac |
Numeric; fraction of edges that are cross-omic. Default 0.2. |
exposure_effect |
Numeric; effect of the exposure on the mean of affected features and on composition. Default 0.5. |
composition_confounding |
Logical; make the proportions of cell types 1 and 2 depend on the exposure. Default TRUE. |
seed |
Integer or NULL; random seed. The caller's random number generator state is restored on return. Default NULL. |
Simulation design:
A sparse positive-definite base precision matrix
is generated over transcripts and metabolites with
within-omic and cross-omic edges.
Cell types 1 and 2 keep a fraction shared_edge_frac of
the base edges and gain as many new edges; cell type 3 has an
independently generated precision matrix; cell types 4 and above
have no transcript-transcript or cross-omic edges.
Metabolites are drawn once per donor from a multivariate normal
distribution whose precision is the metabolite block of the base
matrix, .
For each cell type, latent transcript log-expression is drawn
from its conditional distribution given the metabolites,
. The joint
precision of transcripts and metabolites is then
, and
; it is returned in
true_networks, so its metabolite block can contain edges
induced by the cross-omic edges.
The exposure shifts the mean of the first 30% of metabolites and, in cell types 1 and 2, of the first 20% of transcripts; it does not change any network.
Pseudobulk counts are Poisson with mean equal to the number of
cells times , which makes them
overdispersed relative to a Poisson with a fixed mean.
If composition_confounding = TRUE, the proportions of
cell types 1 and 2 increase with the exposure, so pseudobulk depth
varies with the exposure.
List with:
List of count matrices (donors x transcripts), one per cell type.
Metabolite matrix (donors x metabolites), shared by all cell types.
Named numeric vector of exposure values.
Donor-by-cell-type matrix of proportions.
Donor-by-cell-type matrix of simulated cell numbers.
List of precision matrices, one per cell type, of the latent transcript log-expression and the metabolites conditional on the exposure.
List of the corresponding adjacency matrices.
Character vector of cell type names.
DataFrame of feature metadata.
List of simulation parameters.
sim <- simulate_crossomic_network( n_donors = 50, n_transcripts = 20, n_metabolites = 5, seed = 42) names(sim) sim$true_adjacency[[1]][1:5, 1:5]sim <- simulate_crossomic_network( n_donors = 50, n_transcripts = 20, n_metabolites = 5, seed = 42) names(sim) sim$true_adjacency[[1]][1:5, 1:5]
Extends SingleCellExperiment with
sample-level environmental exposure measurements. This enables
cell-type-specific exposome-wide association studies (sc-ExWAS).
## S4 method for signature 'SingleCellExposomeExperiment,ANY,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'SingleCellExposomeExperiment' cbind(..., deparse.level = 1) ## S4 method for signature 'SingleCellExposomeExperiment' rbind(..., deparse.level = 1) ## S4 replacement method for signature 'SingleCellExposomeExperiment,DataFrame' colData(x, ...) <- value ## S4 replacement method for signature 'SingleCellExposomeExperiment,NULL' colData(x, ...) <- value ## S4 replacement method for signature 'SingleCellExposomeExperiment,list' dimnames(x) <- value ## S4 replacement method for signature 'SingleCellExposomeExperiment,NULL' dimnames(x) <- value ## S4 method for signature 'SingleCellExposomeExperiment' show(object)## S4 method for signature 'SingleCellExposomeExperiment,ANY,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'SingleCellExposomeExperiment' cbind(..., deparse.level = 1) ## S4 method for signature 'SingleCellExposomeExperiment' rbind(..., deparse.level = 1) ## S4 replacement method for signature 'SingleCellExposomeExperiment,DataFrame' colData(x, ...) <- value ## S4 replacement method for signature 'SingleCellExposomeExperiment,NULL' colData(x, ...) <- value ## S4 replacement method for signature 'SingleCellExposomeExperiment,list' dimnames(x) <- value ## S4 replacement method for signature 'SingleCellExposomeExperiment,NULL' dimnames(x) <- value ## S4 method for signature 'SingleCellExposomeExperiment' show(object)
x |
A SingleCellExposomeExperiment. |
i |
Row (gene) subscript. |
j |
Column (cell) subscript. |
... |
Additional arguments. |
drop |
Logical. Ignored (kept for S4 compatibility). |
deparse.level |
Ignored. |
value |
The replacement |
object |
A SingleCellExposomeExperiment. |
The donor of each cell is read from one column of colData, whose
name is stored in the object (see sampleColumn). The
cell-to-donor mapping is not stored a second time, so renaming cells,
combining objects and editing colData cannot leave two copies out
of step. The object is valid when every donor in that column has exactly
one row in exposureData and every row of exposureData
belongs to at least one cell.
Replacing colData, or a column of it with $<- or
[[<-, checks validity again, so an edit that removes the donor
column or introduces a donor without exposure data is an error; so does
replacing the cell names with colnames<-. To change donor
identifiers, edit exposureData and colData together and
rebuild the object with build_scee.
The subsetting method returns a valid
SingleCellExposomeExperiment. When cells are subset, its
exposureData is restricted to the donors that keep at least one
cell; feature subsetting leaves the donor-level slots unchanged.
cbind combines objects with the same exposure variables, exposure
metadata and sample column; donors present in more than one object must
have identical exposure values. Every argument to cbind or
rbind must be a SingleCellExposomeExperiment: when a plain
SingleCellExperiment comes first, R dispatches to the
SingleCellExperiment method, which returns a
SingleCellExperiment without the exposure data (with only a
warning about ambiguous dispatch), so convert such objects with
build_scee first. rbind combines objects with the
same cells and different features; they must have the same sample
column and exposureInfo, and the same exposure values for each
donor. The replacement methods return the modified object. The
show method is called for its display side effect and returns
NULL invisibly.
exposureDataNumeric matrix. Rows = samples (donors), columns = exposure variables.
exposureInfoDataFrame. Metadata for each
exposure (family, unit, LOD).
sampleColumnCharacter scalar. Name of the colData column
holding each cell's sample (donor) identifier.
Donor (n=50-1000)
|-- Exposures (PM2.5, Pb, BPA, ...) <- sample level
+-- Cells x Genes matrix
|-- T cells (1000 cells)
|-- NK cells (500 cells) <- cell level
+-- Monocytes (800 cells)
van der Wijst MGP et al. (2020). The single-cell eQTLGen consortium. eLife 9:e52155. doi:10.7554/eLife.52155
showClass("SingleCellExposomeExperiment")showClass("SingleCellExposomeExperiment")