Skip to content

Differential Cell Abundance

A larger monocyte fraction does not tell you whether a tissue gained monocytes. The fraction can rise because monocytes increased, another population decreased, or the experiment recovered the populations differently. Differential cell abundance starts with a measurement and a denominator, then asks how that measurement differs across biological samples.

This lesson begins after quality control and cell annotation. It compares an invented paired experiment in R and Python. The analysis describes all captured cell fractions, then estimates changes in three cell ratios against a prespecified T-cell reference. Each donor contributes one difference to each comparison.

Define the comparison before counting cells

Section titled “Define the comparison before counting cells”

The simulated experiment contains one control aliquot and one treated aliquot from each donor. Retained singlets receive one of six mutually exclusive labels. The labels include Unassigned, because dropping those cells would change the denominator whenever annotation succeeds at a different rate. The label pDC denotes plasmacytoid dendritic cells.

The descriptive fraction is the number of cells with a label divided by all retained cells in that sample. The inferential quantity is different: the treated-to-control change in the ratio of a target population to T cells. The three targets are B cells, NK cells, and monocytes. T cells are the reference, and pDCs remain descriptive because their simulated counts are sparse.

The reference is part of the analysis plan. In this simulation, treatment changes only the latent monocyte weight before the weights become capture probabilities. The T-cell weight is unchanged by construction. In a real experiment, a stable reference needs evidence from the biology or a separate measurement; the count table cannot prove it. Without that evidence, the result still describes a target-to-reference ratio, but it cannot attribute the change to the target alone.

Twenty donors give twenty independent pairs. Thousands of cells within one aliquot refine its measured composition; they do not create thousands of independent treatment assignments. The pseudobulk lesson uses the same distinction for gene expression.

Download cell_abundance_samples.csv and cell_abundance_counts.csv into your working directory. Both files contain simulated data, and no donor is a real person. The sample table records the retained total independently of the count table. The count table has one row for every sample and label, including observed zeros.

The simulation source varies donor composition and capture depth before it draws cell counts. It records the latent reference ratios separately from the observed counts, so the known intervention does not enter the fitted model.

For your own data, count each retained cell barcode once within its sample and annotation. A zero means that an assayed sample contains no retained cell with that label. An absent sample, a failed library, or an unmeasured population must not become a zero row. These checks require the complete sample-by-label grid before a matrix operation can fill absent entries silently.

library(ggplot2)
library(jsonlite)
samples <- read.csv("cell_abundance_samples.csv")
counts <- read.csv("cell_abundance_counts.csv")
cell_types <- c("T_cells", "B_cells", "NK_cells", "Monocytes",
"pDC", "Unassigned")
conditions <- c("Control", "Treated")
stopifnot(!anyNA(samples), !anyNA(counts))
stopifnot(!anyDuplicated(samples$sample_id))
stopifnot(!anyDuplicated(samples[c("donor_id", "condition")]))
stopifnot(setequal(samples$condition, conditions))
stopifnot(all(table(samples$donor_id, samples$condition) == 1))
stopifnot(all(samples$retained_cells > 0))
keys <- paste(counts$sample_id, counts$cell_type, sep = "|")
expected <- as.vector(outer(samples$sample_id, cell_types,
paste, sep = "|"))
stopifnot(!anyDuplicated(keys), setequal(keys, expected))
stopifnot(all(counts$cell_count >= 0))
stopifnot(all(counts$cell_count == floor(counts$cell_count)))
count_matrix <- xtabs(cell_count ~ sample_id + cell_type, data = counts)
count_matrix <- count_matrix[samples$sample_id, cell_types]
stopifnot(all(rowSums(count_matrix) == samples$retained_cells))
dir.create("outputs", showWarnings = FALSE)
cat(sprintf("%d donors, %d samples, %d population rows\n",
length(unique(samples$donor_id)), nrow(samples), nrow(counts)))
cat(sprintf("Retained cells per sample: %d to %d\n",
min(samples$retained_cells), max(samples$retained_cells)))
cat(sprintf("Observed pDC zeros: %d samples\n",
sum(count_matrix[, "pDC"] == 0)))
20 donors, 40 samples, 240 population rows
Retained cells per sample: 741 to 4419
Observed pDC zeros: 31 samples

Describe fractions with the same denominator

Section titled “Describe fractions with the same denominator”

Every fraction uses all retained cells, including pDCs and unassigned cells. The sample totals vary, so pooling the counts would give more weight to donors with more captured cells. The table below instead averages each donor’s fraction with equal weight.

fractions <- sweep(count_matrix, 1, samples$retained_cells, "/")
stopifnot(all(abs(rowSums(fractions) - 1) < 1e-12))
fraction_summary <- data.frame(
cell_type = cell_types,
control_pct = 100 * colMeans(fractions[samples$condition == "Control", ]),
treated_pct = 100 * colMeans(fractions[samples$condition == "Treated", ])
)
fraction_summary$change_pp <- fraction_summary$treated_pct -
fraction_summary$control_pct
print(fraction_summary, digits = 4, row.names = FALSE)
long <- merge(counts, samples, by = "sample_id")
long$percent <- 100 * long$cell_count / long$retained_cells
long$condition <- factor(long$condition, levels = conditions)
long$cell_type <- factor(long$cell_type, levels = cell_types)
fraction_plot <- ggplot(long, aes(condition, percent, group = donor_id)) +
geom_line(color = "#85949a", alpha = 0.6) +
geom_point(aes(color = condition), size = 1.5) +
facet_wrap(~cell_type, scales = "free_y", ncol = 3) +
scale_color_manual(values = c(Control = "#28536b", Treated = "#c36b38")) +
labs(x = NULL, y = "Percent of all retained cells",
title = "One line connects the two samples from one donor",
subtitle = "The vertical scale differs between populations") +
theme_bw(base_size = 11) +
theme(legend.position = "none")
ggsave("outputs/cell_abundance_fractions_r.png", fraction_plot,
width = 11, height = 6.5, dpi = 150)
write.csv(fraction_summary, "outputs/cell_abundance_fractions_r.csv",
row.names = FALSE)
cell_type control_pct treated_pct change_pp
T_cells 49.82170 45.22190 -4.599799
B_cells 15.49471 14.38440 -1.110315
NK_cells 12.67421 11.33573 -1.338481
Monocytes 19.07498 26.29593 7.220946
pDC 0.01005 0.01643 0.006386
Unassigned 2.92434 2.74561 -0.178737

Six panels show paired simulated cell fractions. Each line joins the control and treated samples from one donor, and each panel uses its own vertical scale.

The monocyte fraction rises while several other fractions fall. That pattern is expected when the simulation increases only the monocyte weight and then divides every weight by their new sum. A negative percentage point change in another population does not establish that its absolute cell number fell.

Unassigned cells remain visible for another reason. If treatment changes marker expression, a classification method can move cells between labels without any population expanding. Inspect the annotation and recovery process before giving a biological explanation to a composition change.

For target population k in donor d, calculate the log2 target-to-T-cell ratio in each sample. Subtract control from treated. The result is the log2 of a ratio of ratios; the total captured count cancels within each sample.

The analysis fixes B cells, NK cells, and monocytes as one family of three comparisons. All four populations needed for these ratios have positive counts in every simulated sample. The code stops if that requirement fails. It does not add a pseudocount to make a zero disappear, and it does not remove a donor after inspecting the direction of the change.

targets <- c("B_cells", "NK_cells", "Monocytes")
reference <- "T_cells"
stopifnot(all(count_matrix[, c(reference, targets)] > 0))
log_ratios <- log2(sweep(count_matrix[, targets], 1,
count_matrix[, reference], "/"))
donors <- sort(unique(samples$donor_id))
control_ids <- samples$sample_id[samples$condition == "Control"]
control_donors <- samples$donor_id[samples$condition == "Control"]
treated_ids <- samples$sample_id[samples$condition == "Treated"]
treated_donors <- samples$donor_id[samples$condition == "Treated"]
control_ids <- control_ids[match(donors, control_donors)]
treated_ids <- treated_ids[match(donors, treated_donors)]
changes <- log_ratios[treated_ids, ] - log_ratios[control_ids, ]
rownames(changes) <- donors
print(round(head(changes, 4), 4))
cat(sprintf("Independent paired differences per target: %d\n",
nrow(changes)))
cell_type
sample_id B_cells NK_cells Monocytes
D01 0.3116 0.0147 0.4960
D02 -0.0983 -0.0994 0.6070
D03 -0.0454 -0.0899 0.5277
D04 0.3319 0.1624 0.2096
Independent paired differences per target: 20

A positive value means that the target-to-T-cell ratio is larger in the treated sample. It does not mean that the target gained that many cells. A change of one on this scale means that the ratio doubled, whether the target doubled, the reference halved, or both populations changed together.

Estimate the paired effect and its uncertainty

Section titled “Estimate the paired effect and its uncertainty”

The model estimates the mean log2 ratio change across donors. A paired t-test is a one-sample t-test on those donor differences. Its interval assumes independent donors and approximately normal differences; a large number of captured cells cannot repair a poor donor-level model. Inspect the paired values and the difference distribution before using this model on another experiment.

The exponentiated mean is a geometric mean fold change in the target-to-reference ratio. Each donor has equal weight. It is neither a fold change in absolute cell number nor the ratio obtained by pooling cells across donors.

results <- data.frame(cell_type = targets, donors = nrow(changes),
mean_log2 = NA_real_, low_log2 = NA_real_,
high_log2 = NA_real_, p_value = NA_real_)
for (i in seq_along(targets)) {
test <- t.test(changes[, targets[i]], mu = 0)
results$mean_log2[i] <- mean(changes[, targets[i]])
results$low_log2[i] <- test$conf.int[1]
results$high_log2[i] <- test$conf.int[2]
results$p_value[i] <- test$p.value
}
results$p_holm <- p.adjust(results$p_value, method = "holm")
results$ratio_fold <- 2^results$mean_log2
results$fold_low <- 2^results$low_log2
results$fold_high <- 2^results$high_log2
shown <- results[c("cell_type", "donors", "ratio_fold", "fold_low",
"fold_high", "p_value", "p_holm")]
print(shown, digits = 4, row.names = FALSE)
write.csv(results, "outputs/cell_abundance_results_r.csv", row.names = FALSE)
summary_values <- list(donors = nrow(changes), tested_targets = nrow(results))
for (i in seq_along(targets)) {
prefix <- targets[i]
summary_values[[paste0(prefix, "_mean_log2")]] <- results$mean_log2[i]
summary_values[[paste0(prefix, "_low_log2")]] <- results$low_log2[i]
summary_values[[paste0(prefix, "_high_log2")]] <- results$high_log2[i]
summary_values[[paste0(prefix, "_p_holm")]] <- results$p_holm[i]
}
write_json(summary_values, "outputs/cell_abundance_summary_r.json",
auto_unbox = TRUE, digits = 15, pretty = TRUE)
cell_type donors ratio_fold fold_low fold_high p_value p_holm
B_cells 20 1.024 0.9737 1.077 3.384e-01 6.768e-01
NK_cells 20 0.993 0.9523 1.035 7.272e-01 7.272e-01
Monocytes 20 1.528 1.4237 1.639 1.163e-10 3.489e-10

Holm adjustment controls the chance of at least one false rejection across the three planned tests, provided each test supplies a valid p-value. It does not require independence among the tests. That matters here because every ratio shares the same reference population. The displayed intervals are ordinary pointwise 95% intervals; they do not provide simultaneous 95% coverage for the whole family.

The monocyte-to-T-cell ratio increases in the simulated experiment. The B-cell and NK-cell ratio intervals include no change, even though both raw fractions declined. The result follows the chosen denominator; it does not identify absolute losses in those populations.

The CSV keeps the estimates, intervals, and adjusted p-values together. The JSON contains named summaries for a report. Preserve the reference label and subtraction direction with these files, because a ratio without its denominator is ambiguous.

Show the effect beside the donor differences

Section titled “Show the effect beside the donor differences”

The first panel keeps every donor difference visible. The second panel places the interval on the fold-change scale, where one means no average log ratio change. Both panels describe the same comparison.

plot_data <- data.frame(
donor_id = rep(donors, times = length(targets)),
cell_type = rep(targets, each = length(donors)),
change_log2 = as.vector(changes)
)
plot_data$cell_type <- factor(plot_data$cell_type, levels = targets)
results$cell_type <- factor(results$cell_type, levels = targets)
difference_plot <- ggplot(plot_data, aes(cell_type, change_log2)) +
geom_hline(yintercept = 0, linetype = "dashed", color = "grey50") +
geom_point(position = position_jitter(width = 0.12, height = 0, seed = 18),
color = "#28536b", alpha = 0.8, size = 2) +
labs(x = NULL, y = "Treated minus control log2 ratio",
title = "Each point represents one donor") +
theme_bw(base_size = 12)
effect_plot <- ggplot(results, aes(cell_type, ratio_fold)) +
geom_hline(yintercept = 1, linetype = "dashed", color = "grey50") +
geom_errorbar(aes(ymin = fold_low, ymax = fold_high), width = 0.1,
color = "#28536b") +
geom_point(color = "#c36b38", size = 3) +
scale_y_log10(breaks = c(1, 1.2, 1.4, 1.6)) +
labs(x = NULL, y = "Fold change in target / T-cell ratio",
title = "Geometric mean and pointwise 95% interval") +
theme_bw(base_size = 12)
ggsave("outputs/cell_abundance_differences_r.png", difference_plot,
width = 7, height = 4.5, dpi = 150)
ggsave("outputs/cell_abundance_effects_r.png", effect_plot,
width = 7, height = 4.5, dpi = 150)

Each point shows one donor’s treated-minus-control change in a log2 target-to-T-cell ratio.

Three estimates show geometric mean fold changes in the target-to-T-cell ratio with pointwise 95% confidence intervals.

This example estimates a paired relative change among captured and annotated cells. The following changes require a different analysis decision.

Your experiment Required decision
Different donors supply the two conditions. Use an independent-sample model; do not pair donors by row order.
A donor supplies several technical libraries for one biological sample. Combine the technical counts after checking compatible protocols, or model their shared donor explicitly.
Age, batch, or another covariate differs between groups. Use a design matrix that estimates the condition effect with the required covariates. A paired subtraction cannot remove a condition-confounded batch.
A target or reference has zero captured cells. Retain the zero in the count table. Choose a count model that represents the sampling process, or keep that comparison descriptive.
A rare population is the primary endpoint. Plan the required donors and capture depth for that population. Do not discard it because this example excludes sparse pDCs.
No reference population has a defensible interpretation. Consider a joint compositional model and state its identifying assumptions. A data-selected reference does not become biologically stable because the model selected it.
The question concerns absolute tissue abundance. Add a compatible absolute measurement, such as counts per measured tissue volume. Captured proportions alone cannot answer that question.

For many populations, propeller models transformed sample proportions and shares information about their variances. scCODA models the count composition jointly with an explicit reference. Their models answer different questions from this three-ratio example, and their design requirements need to match the experiment. Neither method makes cells from one donor independent biological replicates.

Holm, 1979 describes the sequential multiple-test procedure used to control family-wise error across the three planned comparisons.

Phipson and colleagues, 2022 describe propeller, which tests differences in cell type proportions with biological replication and variance moderation.

Büttner and colleagues, 2021 describe scCODA and the reference assumptions needed for a joint analysis of cell composition.

The R t-test documentation and SciPy one-sample t-test documentation define the test and confidence interval applied to the donor differences. Read the paired-test lesson before changing the experimental unit or subtraction direction.

The R p.adjust documentation explains Holm correction and its control of family-wise error. It also distinguishes that goal from false discovery rate control.

The speckle documentation provides propeller methods for sample-level proportions. Its design matrices are useful when a comparison needs more than a paired subtraction.

The scCODA introduction explains joint composition analysis and reference selection. Compare its model assumptions with the three prespecified ratios here before substituting one analysis for the other.