| Title: | Single-Cell Disease-Relevance Score |
|---|---|
| Description: | A native R implementation of the Python package scDRS (single-cell disease-relevance score; Zhang, Hou et al., Nature Genetics 2022; <https://github.com/martinjzhang/scDRS>). scDRS links single-cell RNA-seq data to polygenic disease risk by scoring each cell for excess expression of a GWAS-derived disease gene set relative to matched control gene sets, and provides downstream tests for cell-type association and heterogeneity. The package works on SingleCellExperiment objects. |
| Authors: | Sina Ravanbakhsh [aut, cre] (ORCID: <https://orcid.org/0009-0002-9624-1898>), Martin Jinye Zhang [cph] (Author of the original Python scDRS), Kangcheng Hou [cph] (Author of the original Python scDRS) |
| Maintainer: | Sina Ravanbakhsh <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.99.0 |
| Built: | 2026-11-26 20:54:41 UTC |
| Source: | https://github.com/BiocStaging/RscDRS |
Builds the nearest-neighbour graph that the scDRS heterogeneity test
(scdrsTestGroups()) uses, in the same way as scdrs perform-downstream does with scanpy (sc.pp.pca(n_comps = 20) and
sc.pp.neighbors(n_neighbors = 15)): a PCA of the gene-centered
expression, exact Euclidean nearest neighbours in PCA space, and UMAP
connectivities (fuzzy simplicial set) as edge weights.
scdrsBuildGraph( sce, assay = "logcounts", nNeighbors = 15L, nPCs = 20L, name = "connectivities" )scdrsBuildGraph( sce, assay = "logcounts", nNeighbors = 15L, nPCs = 20L, name = "connectivities" )
sce |
|
assay |
Expression assay to use (log-normalized). |
nNeighbors |
Number of neighbours per cell, the cell itself included (as in scanpy). |
nPCs |
Number of principal components; at most
|
name |
Name under which the graph is stored in |
The PCA uses BiocSingular (exact SVD for up to 2e7
matrix entries, IRLBA otherwise) and the exact neighbour search uses
BiocNeighbors; the edge weights are UMAP connectivities, as in
scanpy and scDRS. Any other graph, e.g. from bluster or
scran, can be used instead by storing it in colPair(sce) or
passing it to scdrsTestGroups(). The graph is close to scanpy's but
not always identical, because PCA and neighbour search differ slightly
between implementations.
sce with the graph in colPair(sce, name) (a symmetric
weighted graph) and the PCA in reducedDim(sce, "scdrs_pca").
sce <- scdrsBuildGraph(scdrsLoadToyData()) sce g <- SingleCellExperiment::colPair(sce, "connectivities", asSparse = TRUE) summary(Matrix::rowSums(g > 0))sce <- scdrsBuildGraph(scdrsLoadToyData()) sce g <- SingleCellExperiment::colPair(sce, "connectivities", asSparse = TRUE) summary(Matrix::rowSums(g > 0))
Computes Geary's C, a measure of spatial autocorrelation, of one or
several cell-level variables on a cell-cell graph. Small values mean
that neighbouring cells have similar values. This is the R port of
scdrs.method.gearys_c().
scdrsComputeGearysC(graph, x)scdrsComputeGearysC(graph, x)
graph |
A cells x cells matrix of edge weights (sparse or dense),
e.g. from |
x |
A numeric vector with one value per cell, or a matrix with one row per cell (one statistic per column). |
with . It is computed for all columns at once
from (row sums , column sums ), on the
centered values.
A numeric vector with one value per column of x.
g <- Matrix::sparseMatrix(i = c(1, 2, 2, 3), j = c(2, 1, 3, 2), x = 1, dims = c(3, 3)) scdrsComputeGearysC(g, cbind(smooth = c(1, 2, 3), rough = c(1, 3, 1)))g <- Matrix::sparseMatrix(i = c(1, 2, 2, 3), j = c(2, 1, 3, 2), x = 1, dims = c(3, 3)) scdrsComputeGearysC(g, cbind(smooth = c(1, 2, 3), rough = c(1, 3, 1)))
Computes the gene-level statistics used to match control genes (mean,
variance, technical variance and mean-variance bins) and the cell-level
mean and variance. This is the R port of scdrs.pp.compute_stats().
Most users call scdrsPreprocess(), which runs this function.
scdrsComputeGeneStats( sce, assay = "logcounts", implicit = FALSE, cellWeight = NULL, nMeanBin = 20L, nVarBin = 20L, nChunk = 20L )scdrsComputeGeneStats( sce, assay = "logcounts", implicit = FALSE, cellWeight = NULL, nMeanBin = 20L, nVarBin = 20L, nChunk = 20L )
sce |
A SingleCellExperiment::SingleCellExperiment with log-normalized expression (genes in rows, cells in columns). |
assay |
Name of the assay to use. |
implicit |
Logical. If |
cellWeight |
|
nMeanBin, nVarBin
|
Number of mean-expression bins and of
variance bins within each mean bin. If either is larger than
|
nChunk |
Number of chunks used in implicit mode (controls memory use only; the results do not depend on it). |
Variances use the population formula (divisor n). Technical
variance follows the Seurat v3 recipe: a LOESS fit (span 0.3, degree 2)
of log10(ct_var) on log10(ct_mean), and
var_tech = var * ct_var_tech / ct_var. Bins are quantile bins as
pandas.qcut(), labelled from 0.
A list of two S4Vectors::DataFrames:
geneOne row per gene: mean, var (log scale), var_tech
(technical variance, log scale), ct_mean, ct_var, ct_var_tech
(the same on the expm1() scale) and mean_var (mean-variance bin,
e.g. "3.12").
cellOne row per cell: mean and var (log scale,
unweighted).
Zhang MJ, Hou K, et al. (2022). Polygenic enrichment distinguishes disease associations of individual cells in single-cell RNA-seq data. Nature Genetics 54, 1572-1580.
sce <- scdrsLoadToyData() stats <- scdrsComputeGeneStats(sce) head(stats$gene) head(stats$cell)sce <- scdrsLoadToyData() stats <- scdrsComputeGeneStats(sce) head(stats$gene) head(stats$cell)
Preprocesses the data if needed (scdrsPreprocess()) and scores every
gene set with at least minGenes genes in the data
(scdrsScoreCells()). This is the R port of the scdrs compute-score
command, with the same defaults.
scdrsComputeScore( sce, geneSets, assay = "logcounts", cov = NULL, adjProp = NULL, ctrlMatchKey = "mean_var", weightOpt = "vs", nCtrl = 1000L, returnCtrlRawScore = FALSE, returnCtrlNormScore = TRUE, minGenes = 10L )scdrsComputeScore( sce, geneSets, assay = "logcounts", cov = NULL, adjProp = NULL, ctrlMatchKey = "mean_var", weightOpt = "vs", nCtrl = 1000L, returnCtrlRawScore = FALSE, returnCtrlNormScore = TRUE, minGenes = 10L )
sce |
A SingleCellExperiment::SingleCellExperiment with
log-normalized data (see |
geneSets |
A named list of gene sets as returned by
|
assay |
Assay to use. |
cov, adjProp
|
Covariates and cell-group column for
|
ctrlMatchKey, weightOpt, nCtrl
|
See |
returnCtrlRawScore, returnCtrlNormScore
|
Return the control scores? The normalized ones are returned by default, because the downstream analyses need them. |
minGenes |
Gene sets with fewer genes in |
A named S4Vectors::SimpleList of score tables (see
scdrsScoreCells()), one per scored gene set.
scdrsWriteScores(), scdrsPerformDownstream().
sce <- scdrsLoadToyData() gs <- scdrsReadGeneSets(system.file("extdata", "toydata_human.gs", package = "RscDRS"), srcSpecies = "human", dstSpecies = "mouse") set.seed(1) res <- scdrsComputeScore(sce, gs, cov = "covariate", nCtrl = 100) names(res) head(res[[1]][, 1:6])sce <- scdrsLoadToyData() gs <- scdrsReadGeneSets(system.file("extdata", "toydata_human.gs", package = "RscDRS"), srcSpecies = "human", dstSpecies = "mouse") set.seed(1) res <- scdrsComputeScore(sce, gs, cov = "covariate", nCtrl = 100) names(res) head(res[[1]][, 1:6])
Returns the mouse-human gene symbol map shipped with scDRS (16,466
pairs, system.file("extdata", "mouse_human_homologs.txt", package = "RscDRS")). This is the R port of scdrs.util.load_homolog_mapping().
scdrsGetHomologs(src, dst)scdrsGetHomologs(src, dst)
src, dst
|
Source and destination species: |
A named character vector: names are src gene symbols, values
the dst homologs.
map <- scdrsGetHomologs("human", "mouse") map[c("ACADM", "APOE")]map <- scdrsGetHomologs("human", "mouse") map[c("ACADM", "APOE")]
Loads the small example data set shipped with the original scDRS (a
subset of Tabula Muris Senis: 2,500 mouse genes and 30 cells, 10
"causal" and 20 "non-causal") as a SingleCellExperiment.
scdrsLoadToyData()scdrsLoadToyData()
A SingleCellExperiment::SingleCellExperiment with a sparse
logcounts assay (size-factor normalized, log1p), cell metadata
in colData (label, cell_type, causal_variable,
non_causal_variable, covariate) and gene metadata in rowData
(label). The files are in system.file("extdata", package = "RscDRS"), including the disease gene sets toydata_mouse.gs and
toydata_human.gs; see inst/scripts/python/README.md for their
origin.
sce <- scdrsLoadToyData() sce table(sce$cell_type)sce <- scdrsLoadToyData() sce table(sce$cell_type)
Fixed-effect or DerSimonian-Laird random-effects meta-analysis, e.g. to
combine scDRS results across data sets. This is the R port of
scdrs.util.meta_analysis().
scdrsMetaAnalyze(effects, se, method = c("random", "fixed"), weights = NULL)scdrsMetaAnalyze(effects, se, method = c("random", "fixed"), weights = NULL)
effects |
Numeric vector of effect sizes. |
se |
Numeric vector of their standard errors. |
method |
|
weights |
Optional weights to use instead of the inverse variances. |
With , the between-study variance
is ,
where is Cochran's Q. Random-effects weights are
.
A named numeric vector: summary (the combined effect) and
se (its standard error).
scdrsMetaAnalyze(c(0.2, 0.5, -0.1), c(0.1, 0.2, 0.15)) scdrsMetaAnalyze(c(0.2, 0.5, -0.1), c(0.1, 0.2, 0.15), method = "fixed")scdrsMetaAnalyze(c(0.2, 0.5, -0.1), c(0.1, 0.2, 0.15)) scdrsMetaAnalyze(c(0.2, 0.5, -0.1), c(0.1, 0.2, 0.15), method = "fixed")
For each trait, selects the disease genes with the smallest gene-level
p-values (e.g. from MAGMA) and weights them by their z-scores. This is
the R port of the scdrs munge-gs command.
scdrsMungeGeneSets( pvals = NULL, zscores = NULL, weight = c("zscore", "uniform"), fdr = NULL, fwer = NULL, nMin = 100L, nMax = 1000L, file = NULL )scdrsMungeGeneSets( pvals = NULL, zscores = NULL, weight = c("zscore", "uniform"), fdr = NULL, fwer = NULL, nMin = 100L, nMax = 1000L, file = NULL )
pvals, zscores
|
Exactly one of: gene-level p-values or one-sided
z-scores, as a |
weight |
|
fdr, fwer
|
At most one of them: the FDR or FWER level used to choose the number of genes. |
nMin, nMax
|
Minimum and maximum number of genes per trait. |
file |
Optional path: also write the gene sets to this |
The number of genes per trait is the number of discoveries at
fdr (Benjamini-Hochberg) or fwer (Bonferroni), or nMax if neither
is given, and is then restricted to [nMin, nMax].
A named list (traits in sorted order) of named numeric vectors
(names = genes, ordered by p-value; values = weights rounded to 5
significant digits, as in the file), like scdrsReadGeneSets().
set.seed(1) p <- data.frame(BMI = runif(500)^4, HEIGHT = runif(500)^2, row.names = paste0("GENE", seq_len(500))) gs <- scdrsMungeGeneSets(pvals = p, fdr = 0.05, nMin = 10, nMax = 100) lengths(gs) head(gs$BMI)set.seed(1) p <- data.frame(BMI = runif(500)^4, HEIGHT = runif(500)^2, row.names = paste0("GENE", seq_len(500))) gs <- scdrsMungeGeneSets(pvals = p, fdr = 0.05, nMin = 10, nMax = 100) lengths(gs) head(gs$BMI)
Optionally removes cells with fewer than minGenes expressed genes and
then genes expressed in fewer than minCells cells, and normalizes each
cell to 10,000 total counts followed by a natural-log log1p. This
copies what scdrs compute-score does with --flag-filter-data and
--flag-raw-count (scanpy's filter_cells, filter_genes,
normalize_per_cell(counts_per_cell_after = 1e4) and log1p; R port
of scdrs.util.load_h5ad()).
scdrsNormalize( sce, assay = "counts", filter = TRUE, minGenes = 250L, minCells = 50L, normalize = TRUE, name = "logcounts" )scdrsNormalize( sce, assay = "counts", filter = TRUE, minGenes = 250L, minCells = 50L, normalize = TRUE, name = "logcounts" )
sce |
A SingleCellExperiment::SingleCellExperiment with raw counts. |
assay |
Name of the counts assay. |
filter |
Filter cells and genes first? |
minGenes, minCells
|
Filtering thresholds. |
normalize |
Normalize and log-transform? If |
name |
Name of the new assay. |
Note that scuttle::logNormCounts() gives different values (log2 and
centred size factors); scDRS expects natural-log data.
sce, possibly with fewer cells and genes, with the normalized
data in assay name (sparse if the counts are sparse). Cells
without any counts are removed when normalizing, as in scanpy.
set.seed(1) counts <- matrix(rpois(2000, 2), 50, 40, dimnames = list(paste0("g", 1:50), paste0("c", 1:40))) sce <- SingleCellExperiment::SingleCellExperiment(list(counts = counts)) sce <- scdrsNormalize(sce, minGenes = 10, minCells = 5) sceset.seed(1) counts <- matrix(rpois(2000, 2), 50, 40, dimnames = list(paste0("g", 1:50), paste0("c", 1:40))) sce <- SingleCellExperiment::SingleCellExperiment(list(counts = counts)) sce <- scdrsNormalize(sce, minGenes = 10, minCells = 5) sce
Runs the group-level analysis (scdrsTestGroups()), the correlation
analysis (scdrsTestCorrelation()) and the gene analysis
(scdrsRankGenes()) for one or several traits. This is the R port of
the scdrs perform-downstream command.
scdrsPerformDownstream( sce, scores, groupCols = NULL, varCols = NULL, geneAnalysis = FALSE, graph = "connectivities", assay = "logcounts" )scdrsPerformDownstream( sce, scores, groupCols = NULL, varCols = NULL, geneAnalysis = FALSE, graph = "connectivities", assay = "logcounts" )
sce |
A SingleCellExperiment::SingleCellExperiment with the
annotations in |
scores |
One score table, or a named list of them (e.g. from
|
groupCols, varCols
|
|
geneAnalysis |
Run the gene analysis? |
graph |
Name of a |
assay |
Assay used by the gene analysis. |
For one score table, a list with elements group, corr and
gene (NULL for analyses not run); for a list of score tables, a
named list of such lists.
sce <- scdrsBuildGraph(scdrsLoadToyData()) gs <- scdrsReadGeneSets(system.file("extdata", "toydata_mouse.gs", package = "RscDRS")) set.seed(1) res <- scdrsComputeScore(sce, gs, cov = "covariate", nCtrl = 100) out <- scdrsPerformDownstream(sce, res, groupCols = "cell_type", varCols = "causal_variable") out$toydata_gs_mouse$group$cell_typesce <- scdrsBuildGraph(scdrsLoadToyData()) gs <- scdrsReadGeneSets(system.file("extdata", "toydata_mouse.gs", package = "RscDRS")) set.seed(1) res <- scdrsComputeScore(sce, gs, cov = "covariate", nCtrl = 100) out <- scdrsPerformDownstream(sce, res, groupCols = "cell_type", varCols = "causal_variable") out$toydata_gs_mouse$group$cell_type
Regresses covariates out of the expression data (adding back each gene's
mean), then computes the gene- and cell-level statistics that scDRS uses
to choose control genes. This is the R port of scdrs.preprocess().
scdrsPreprocess( sce, assay = "logcounts", cov = NULL, adjProp = NULL, nMeanBin = 20L, nVarBin = 20L, nChunk = NULL, implicit = NULL )scdrsPreprocess( sce, assay = "logcounts", cov = NULL, adjProp = NULL, nMeanBin = 20L, nVarBin = 20L, nChunk = NULL, implicit = NULL )
sce |
A SingleCellExperiment::SingleCellExperiment. The assay
must be size-factor normalized and |
assay |
Name of the assay to use. It is never modified. |
cov |
Covariates to regress out, or |
adjProp |
|
nMeanBin, nVarBin
|
Number of mean-expression bins and of variance bins within each mean bin, used to match control genes. |
nChunk |
Number of chunks for implicit covariate correction
(memory use only). |
implicit |
Use implicit covariate correction? |
The corrected data is
where is the covariate matrix, the least-squares
coefficients and the gene means. Python's COV_BETA is
, so
X~ = X + scdrs_cov_beta %*% t(scdrs_cov) + scdrs_cov_gene_mean.
sce, with:
rowData(sce)scdrs_mean, scdrs_var, scdrs_var_tech,
scdrs_ct_mean, scdrs_ct_var, scdrs_ct_var_tech,
scdrs_mean_var (see scdrsComputeGeneStats()); with covariates
also scdrs_cov_beta (a genes x covariates matrix, the negated
regression coefficients, Python's COV_BETA) and
scdrs_cov_gene_mean.
colData(sce)scdrs_mean, scdrs_var.
reducedDim(sce, "scdrs_cov")The covariate matrix (cells x covariates), with covariates only.
assay(sce, "scdrs_corrected")The covariate-corrected data,
with covariates and implicit = FALSE only.
metadata(sce)$scdrsA list of flags and settings (assay is
the assay that later steps should score).
Results of an earlier run of scdrsPreprocess() are replaced.
Zhang MJ, Hou K, et al. (2022). Polygenic enrichment distinguishes disease associations of individual cells in single-cell RNA-seq data. Nature Genetics 54, 1572-1580.
sce <- scdrsLoadToyData() sce <- scdrsPreprocess(sce, cov = "covariate") rowData(sce)[1:3, c("scdrs_mean", "scdrs_var", "scdrs_mean_var")] head(reducedDim(sce, "scdrs_cov")) str(metadata(sce)$scdrs)sce <- scdrsLoadToyData() sce <- scdrsPreprocess(sce, cov = "covariate") rowData(sce)[1:3, c("scdrs_mean", "scdrs_var", "scdrs_mean_var")] head(reducedDim(sce, "scdrs_cov")) str(metadata(sce)$scdrs)
Computes the Pearson correlation across cells between each gene's
expression and the normalized disease score, to prioritize genes. This
is the R port of scdrs.method.downstream_gene_analysis().
scdrsRankGenes(sce, scores, assay = "logcounts")scdrsRankGenes(sce, scores, assay = "logcounts")
sce |
A SingleCellExperiment::SingleCellExperiment with the
annotations in |
scores |
A score table with normalized control scores: the output
of |
assay |
Expression assay to use. As in Python, this is the log-normalized data, not the covariate-corrected data. |
A S4Vectors::DataFrame with one row per gene (row names),
sorted by decreasing correlation, with columns CORR and RANK
(1 = highest correlation; Python's RANK starts at 0).
sce <- scdrsPreprocess(scdrsLoadToyData(), cov = "covariate") gs <- scdrsReadGeneSets(system.file("extdata", "toydata_mouse.gs", package = "RscDRS")) set.seed(1) res <- scdrsScoreCells(sce, gs[[1]], nCtrl = 100) head(scdrsRankGenes(sce, res))sce <- scdrsPreprocess(scdrsLoadToyData(), cov = "covariate") gs <- scdrsReadGeneSets(system.file("extdata", "toydata_mouse.gs", package = "RscDRS")) set.seed(1) res <- scdrsScoreCells(sce, gs[[1]], nCtrl = 100) head(scdrsRankGenes(sce, res))
scdrsReadGeneSets() reads a .gs file: a tab-separated file with
columns TRAIT and GENESET, where GENESET is a comma-separated
list of genes ("g1,g2,g3") or of genes and weights
("g1:w1,g2:w2"). Genes can be mapped between mouse and human and
intersected with the genes of a data set. scdrsWriteGeneSets() writes
such a file. These are the R ports of scdrs.util.load_gs() and
scdrs.util.save_gs().
scdrsReadGeneSets(file, srcSpecies = NULL, dstSpecies = NULL, intersect = NULL) scdrsWriteGeneSets(geneSets, file)scdrsReadGeneSets(file, srcSpecies = NULL, dstSpecies = NULL, intersect = NULL) scdrsWriteGeneSets(geneSets, file)
file |
Path of the |
srcSpecies, dstSpecies
|
|
intersect |
|
geneSets |
A named list of gene sets: named numeric vectors (genes
and weights, written as |
scdrsReadGeneSets(): a named list (one element per trait) of
named numeric vectors (names = genes, values = weights; 1 for an
unweighted gene set). A gene listed twice keeps its first position
and its last weight, as in Python.
scdrsWriteGeneSets(): file, invisibly.
scdrsMungeGeneSets() to make gene sets from GWAS gene
statistics, scdrsComputeScore().
f <- system.file("extdata", "toydata_human.gs", package = "RscDRS") sce <- scdrsLoadToyData() gs <- scdrsReadGeneSets(f, srcSpecies = "human", dstSpecies = "mouse", intersect = rownames(sce)) lengths(gs) out <- tempfile(fileext = ".gs") scdrsWriteGeneSets(gs, out) identical(scdrsReadGeneSets(out), gs)f <- system.file("extdata", "toydata_human.gs", package = "RscDRS") sce <- scdrsLoadToyData() gs <- scdrsReadGeneSets(f, srcSpecies = "human", dstSpecies = "mouse", intersect = rownames(sce)) lengths(gs) out <- tempfile(fileext = ".gs") scdrsWriteGeneSets(gs, out) identical(scdrsReadGeneSets(out), gs)
For one disease gene set, computes each cell's raw disease score (a
weighted mean of the covariate-corrected expression of the disease
genes), the same score for nCtrl matched control gene sets, the
normalized score, and a cell-level p-value from the empirical
distribution of the control scores pooled over all cells. This is the R
port of scdrs.score_cell().
scdrsScoreCells( sce, genes, weights = NULL, ctrlMatchKey = "mean_var", nCtrl = 1000L, nGeneBin = 200L, weightOpt = c("vs", "uniform", "inv_std", "od"), returnCtrlRawScore = FALSE, returnCtrlNormScore = FALSE, controlSets = NULL )scdrsScoreCells( sce, genes, weights = NULL, ctrlMatchKey = "mean_var", nCtrl = 1000L, nGeneBin = 200L, weightOpt = c("vs", "uniform", "inv_std", "od"), returnCtrlRawScore = FALSE, returnCtrlNormScore = FALSE, controlSets = NULL )
sce |
A SingleCellExperiment::SingleCellExperiment processed by
|
genes |
Disease genes: a character vector, or a named numeric
vector of weights (names = genes), e.g. one element of
|
weights |
Optional gene weights when |
ctrlMatchKey |
Gene statistic used to match control genes
( |
nCtrl |
Number of control gene sets. |
nGeneBin |
Number of quantile bins for a continuous |
weightOpt |
How the raw score weights genes: |
returnCtrlRawScore, returnCtrlNormScore
|
Also return the raw /
normalized control scores? The normalized control scores are needed
by the downstream analyses ( |
controlSets |
Optional precomputed control gene sets, either a
list of named numeric vectors as returned by
|
Run scdrsPreprocess() first. Control gene sets are drawn at random
(see scdrsSelectControlGenes()); call set.seed() first for
reproducible results.
Let be the raw disease score of cell and
that of control set . The scores are centered per
gene set, the control scores are scaled to the same variance as the
disease score (assuming independent genes), each cell is standardized
by the mean and SD of its control scores, and the scores are centered
again. Cells with a raw score of exactly 0 get the smallest score. The
p-value is .
A S4Vectors::DataFrame with one row per cell (row names = cell names) and columns
raw_scoreRaw disease score.
norm_scoreNormalized disease score.
mc_pvalMonte Carlo p-value from the cell's own control scores.
pvalscDRS cell-level p-value (control scores pooled over all cells).
nlog10_pval-log10(pval).
zscoreOne-sided z-score of pval, clipped to
[-10, 10].
ctrl_raw_score, ctrl_norm_score
Only if requested: cells x
nCtrl matrices of control scores (matrix columns, columns named
0, 1, ... as in Python's ctrl_norm_score_0, ...).
metadata() of the result holds the disease genes and weights used
(genes), the control sets (controlSets) and the settings.
Zhang MJ, Hou K, et al. (2022). Polygenic enrichment distinguishes disease associations of individual cells in single-cell RNA-seq data. Nature Genetics 54, 1572-1580.
scdrsPreprocess(), scdrsComputeScore() to score several
gene sets, scdrsTestGroups().
sce <- scdrsPreprocess(scdrsLoadToyData(), cov = "covariate") gs <- scdrsReadGeneSets(system.file("extdata", "toydata_mouse.gs", package = "RscDRS")) set.seed(1) res <- scdrsScoreCells(sce, gs[["toydata_gs_mouse"]], nCtrl = 100) head(res) tapply(res$norm_score, sce$cell_type, mean)sce <- scdrsPreprocess(scdrsLoadToyData(), cov = "covariate") gs <- scdrsReadGeneSets(system.file("extdata", "toydata_mouse.gs", package = "RscDRS")) set.seed(1) res <- scdrsScoreCells(sce, gs[["toydata_gs_mouse"]], nCtrl = 100) head(res) tapply(res$norm_score, sce$cell_type, mean)
Draws nCtrl control gene sets that match the disease gene set gene by
gene: within each bin of ctrlMatchKey (by default the mean-variance
bins made by scdrsPreprocess()) that contains disease genes,
each control set gets genes drawn at random, without
replacement, from all genes of that bin (disease genes included). A
control gene takes the weight of a disease gene of the same bin. This is
the R port of scdrs.method._select_ctrl_geneset().
scdrsSelectControlGenes( geneStats, genes, weights = NULL, ctrlMatchKey = "mean_var", nCtrl = 1000L, nGeneBin = 200L )scdrsSelectControlGenes( geneStats, genes, weights = NULL, ctrlMatchKey = "mean_var", nCtrl = 1000L, nGeneBin = 200L )
geneStats |
A SingleCellExperiment::SingleCellExperiment
processed by |
genes |
Disease genes: a character vector, or a named numeric
vector of weights (names = genes), as returned by
|
weights |
Optional gene weights when |
ctrlMatchKey |
Gene statistic used for matching, e.g. |
nCtrl |
Number of control gene sets. |
nGeneBin |
Number of quantile bins for a continuous |
Random numbers come from R's generator, so call set.seed() first for
reproducible results. The control sets are not the same as the ones
Python draws with the same seed (see the vignette).
A list of nCtrl named numeric vectors (names = control genes,
values = weights).
Zhang MJ, Hou K, et al. (2022). Polygenic enrichment distinguishes disease associations of individual cells in single-cell RNA-seq data. Nature Genetics 54, 1572-1580.
sce <- scdrsPreprocess(scdrsLoadToyData()) gs <- scdrsReadGeneSets(system.file("extdata", "toydata_mouse.gs", package = "RscDRS")) set.seed(1) ctrl <- scdrsSelectControlGenes(sce, gs[[1]], nCtrl = 5) lengths(ctrl) head(ctrl[[1]])sce <- scdrsPreprocess(scdrsLoadToyData()) gs <- scdrsReadGeneSets(system.file("extdata", "toydata_mouse.gs", package = "RscDRS")) set.seed(1) ctrl <- scdrsSelectControlGenes(sce, gs[[1]], nCtrl = 5) lengths(ctrl) head(ctrl[[1]])
For each continuous cell-level variable (e.g. a T cell effector
gradient), tests the Pearson correlation between the variable and the
normalized disease score against the correlations with the control
scores. This is the R port of
scdrs.method.downstream_corr_analysis().
scdrsTestCorrelation(sce, scores, varCols)scdrsTestCorrelation(sce, scores, varCols)
sce |
A SingleCellExperiment::SingleCellExperiment with the
annotations in |
scores |
A score table with normalized control scores: the output
of |
varCols |
Names of numeric |
A S4Vectors::DataFrame with one row per variable and columns
n_ctrl, corr_mcp (Monte Carlo p-value) and corr_mcz (z-score
against the control correlations).
sce <- scdrsPreprocess(scdrsLoadToyData(), cov = "covariate") gs <- scdrsReadGeneSets(system.file("extdata", "toydata_mouse.gs", package = "RscDRS")) set.seed(1) res <- scdrsScoreCells(sce, gs[[1]], nCtrl = 100, returnCtrlNormScore = TRUE) scdrsTestCorrelation(sce, res, c("causal_variable", "non_causal_variable"))sce <- scdrsPreprocess(scdrsLoadToyData(), cov = "covariate") gs <- scdrsReadGeneSets(system.file("extdata", "toydata_mouse.gs", package = "RscDRS")) set.seed(1) res <- scdrsScoreCells(sce, gs[[1]], nCtrl = 100, returnCtrlNormScore = TRUE) scdrsTestCorrelation(sce, res, c("causal_variable", "non_causal_variable"))
For each group of cells, computes Geary's C of the normalized disease
score on the group's part of the cell-cell graph and compares it with
null statistics, to test whether disease scores are more similar among
neighbouring cells than expected (heterogeneity within the group). This
is the R port of scdrs.method.test_gearysc().
scdrsTestGearysC( graph, scores, groups, method = c("control_distribution_match", "permutation", "control") )scdrsTestGearysC( graph, scores, groups, method = c("control_distribution_match", "permutation", "control") )
graph |
A cells x cells matrix of edge weights, with the cells in
the order of the rows of |
scores |
A score table with normalized control scores, from
|
groups |
A vector with the group of each cell (rows of |
method |
How the null statistics are made:
|
A S4Vectors::DataFrame with one row per group (sorted):
pval (; small values mean
heterogeneity), trait (Geary's C of the disease score),
ctrl_mean, ctrl_std (mean and sample SD of the null statistics)
and zsc ().
scdrsTestGroups(), which calls this function.
sce <- scdrsPreprocess(scdrsBuildGraph(scdrsLoadToyData())) gs <- scdrsReadGeneSets(system.file("extdata", "toydata_mouse.gs", package = "RscDRS")) set.seed(1) res <- scdrsScoreCells(sce, gs[[1]], nCtrl = 100, returnCtrlNormScore = TRUE) g <- SingleCellExperiment::colPair(sce, "connectivities", asSparse = TRUE) scdrsTestGearysC(g, res, sce$cell_type)sce <- scdrsPreprocess(scdrsBuildGraph(scdrsLoadToyData())) gs <- scdrsReadGeneSets(system.file("extdata", "toydata_mouse.gs", package = "RscDRS")) set.seed(1) res <- scdrsScoreCells(sce, gs[[1]], nCtrl = 100, returnCtrlNormScore = TRUE) g <- SingleCellExperiment::colPair(sce, "connectivities", asSparse = TRUE) scdrsTestGearysC(g, res, sce$cell_type)
For each annotation in groupCols (e.g. cell types) and each group of
cells, counts the significant cells and tests whether the group as a
whole is associated with the disease (association) and whether
disease scores vary among the group's cells beyond chance
(heterogeneity). This is the R port of
scdrs.method.downstream_group_analysis().
scdrsTestGroups( sce, scores, groupCols, fdrThresholds = c(0.05, 0.1, 0.2), graph = "connectivities" )scdrsTestGroups( sce, scores, groupCols, fdrThresholds = c(0.05, 0.1, 0.2), graph = "connectivities" )
sce |
A SingleCellExperiment::SingleCellExperiment with the
annotations in |
scores |
A score table with normalized control scores: the output
of |
groupCols |
Names of |
fdrThresholds |
FDR levels at which significant cells are counted. |
graph |
Name of a |
A named S4Vectors::SimpleList with one S4Vectors::DataFrame
per element of groupCols, with one row per group (sorted) and
columns:
n_cell, n_ctrl
Numbers of cells and of control sets.
assoc_mcp, assoc_mcz
Association: Monte Carlo p-value and z-score of the 95% quantile of the group's disease scores against the same quantile of each control score.
hetero_mcp, hetero_mcz
Heterogeneity: p-value and z-score
of Geary's C (see scdrsTestGearysC()).
n_fdr_<t>Number of cells with FDR (Benjamini-Hochberg, over
all cells) below t, for each of fdrThresholds.
Zhang MJ, Hou K, et al. (2022). Polygenic enrichment distinguishes disease associations of individual cells in single-cell RNA-seq data. Nature Genetics 54, 1572-1580.
scdrsTestCorrelation(), scdrsRankGenes(),
scdrsPerformDownstream().
sce <- scdrsBuildGraph(scdrsLoadToyData()) sce <- scdrsPreprocess(sce, cov = "covariate") gs <- scdrsReadGeneSets(system.file("extdata", "toydata_mouse.gs", package = "RscDRS")) set.seed(1) res <- scdrsScoreCells(sce, gs[[1]], nCtrl = 100, returnCtrlNormScore = TRUE) scdrsTestGroups(sce, res, "cell_type")[["cell_type"]]sce <- scdrsBuildGraph(scdrsLoadToyData()) sce <- scdrsPreprocess(sce, cov = "covariate") gs <- scdrsReadGeneSets(system.file("extdata", "toydata_mouse.gs", package = "RscDRS")) set.seed(1) res <- scdrsScoreCells(sce, gs[[1]], nCtrl = 100, returnCtrlNormScore = TRUE) scdrsTestGroups(sce, res, "cell_type")[["cell_type"]]
Fisher's exact test for the overlap of two gene sets within a
background, with the sample odds ratio and its 95% confidence interval.
This is the R port of scdrs.util.test_overlap().
scdrsTestOverlap(set1, set2, background)scdrsTestOverlap(set1, set2, background)
set1, set2
|
Character vectors of genes. |
background |
Character vector of all genes considered. |
The table counts background genes in neither set, in only one
of them, and in both. Unlike stats::fisher.test(), the odds ratio is
the sample odds ratio (as scipy.stats.fisher_exact()), not the
conditional maximum likelihood estimate.
A named numeric vector: pval (two-sided Fisher's exact test),
odds_ratio (sample odds ratio), or_ub and or_lb (upper and
lower 95% Wald limits on the log scale; both 0 if a cell of the 2 x
2 table is 0, as in Python).
bg <- paste0("g", seq_len(100)) scdrsTestOverlap(bg[1:30], bg[21:45], bg)bg <- paste0("g", seq_len(100)) scdrsTestOverlap(bg[1:30], bg[21:45], bg)
scdrsWriteScores() writes score tables in the format of scdrs compute-score: <trait>.score.gz (the six main columns) and, if the
tables contain control scores, <trait>.full_score.gz (all columns,
with ctrl_raw_score_0, ..., ctrl_norm_score_0, ...).
scdrsReadScores() reads such files, written by R or by Python, back
into score tables that the downstream functions accept. This is the R
port of scdrs.util.load_scdrs_score().
scdrsWriteScores(scores, dir) scdrsReadScores(file, cells = NULL)scdrsWriteScores(scores, dir) scdrsReadScores(file, cells = NULL)
scores |
A named list of score tables (e.g. from
|
dir |
Output directory (created if needed). |
file |
Path of a |
cells |
Optional cell names: files containing fewer than 10% of them are skipped, with a message. |
scdrsWriteScores(): the paths of the files written,
invisibly.
scdrsReadScores(): a named list (traits from the file names)
of S4Vectors::DataFrames with cell names as row names; control
scores are returned as the matrix columns ctrl_raw_score and
ctrl_norm_score.
sce <- scdrsLoadToyData() gs <- scdrsReadGeneSets(system.file("extdata", "toydata_mouse.gs", package = "RscDRS")) set.seed(1) res <- scdrsComputeScore(sce, gs, nCtrl = 20) dir <- file.path(tempdir(), "scdrs_out") scdrsWriteScores(res, dir) list.files(dir) back <- scdrsReadScores(file.path(dir, "@.full_score.gz")) all.equal(back$toydata_gs_mouse$norm_score, res[[1]]$norm_score)sce <- scdrsLoadToyData() gs <- scdrsReadGeneSets(system.file("extdata", "toydata_mouse.gs", package = "RscDRS")) set.seed(1) res <- scdrsComputeScore(sce, gs, nCtrl = 20) dir <- file.path(tempdir(), "scdrs_out") scdrsWriteScores(res, dir) list.files(dir) back <- scdrsReadScores(file.path(dir, "@.full_score.gz")) all.equal(back$toydata_gs_mouse$norm_score, res[[1]]$norm_score)
scdrsZToP() returns and scdrsPToZ() returns
, accurate far in the tails. These are the R
ports of scdrs.util.zsc2pval() and scdrs.util.pval2zsc().
scdrsZToP(z) scdrsPToZ(p)scdrsZToP(z) scdrsPToZ(p)
z |
Numeric vector of z-scores. |
p |
Numeric vector of p-values. |
A numeric vector of the same length.
scdrsZToP(c(0, 1.96, 10)) scdrsPToZ(c(0.5, 0.025, 1e-30))scdrsZToP(c(0, 1.96, 10)) scdrsPToZ(c(0.5, 0.025, 1e-30))