Skip to content

Differential abundance

Differential abundance starts with a comparison and a measurement scale. In this cohort the comparison is tumor tissue minus matched normal tissue from the same patient. The outcome below is a centered log ratio, so its effect is a change relative to the geometric mean of the retained OTUs.

The example uses paired t tests on CLR differences to make the estimand visible. It is not an absolute abundance estimator. The prevalence filter, pseudocount, normality approximation for the mean differences, and multiplicity procedure all belong in the interpretation.

The example uses the prepared Kostic colorectal cohort. The workflow and dataset page explains its source, paired design, and selection rule. Counts, taxonomy, and metadata come from the same public archive. The original features are reference OTUs, not ASVs from the separate ampliseq demonstration.

The companion repository is private and requires access. Its microbiome:0.1.0 container provides the packages, and the runner mounts the prepared tables at /fixtures. Run each language’s blocks in order. The container runs without network access.

The same patient order is checked before subtraction. The code estimates the mean paired difference and its 95 percent interval for each retained OTU. Benjamini-Hochberg adjusts the full family of tested OTUs, before any results are selected for display. The intervals are marginal intervals, not simultaneous intervals across the feature family.

The paired counts and metadata come from Kostic and colleagues, distributed in the pinned phyloseq example archive. McMurdie and Holmes distribute that package under AGPL-3. The source notice records the exact archive, the 76-subject selection, and the applicable package terms.

library(ggplot2)
library(jsonlite)
counts <- read.delim(
"/fixtures/cohort_counts.tsv", row.names = 1, check.names = FALSE
)
counts <- t(as.matrix(counts))
metadata <- read.delim("/fixtures/cohort_metadata.tsv")
metadata <- metadata[match(rownames(counts), metadata$sample_id), ]
stopifnot(identical(rownames(counts), metadata$sample_id))
stopifnot(all(counts >= 0), all(counts == floor(counts)))
dir.create("outputs", showWarnings = FALSE)
filtered <- counts[, colMeans(counts >= 5) >= 0.10, drop = FALSE]
logged <- log(filtered + 1)
clr_counts <- logged - rowMeans(logged)
normal <- which(metadata$tissue == "normal")
tumor <- which(metadata$tissue == "tumor")
stopifnot(identical(metadata$subject_id[normal], metadata$subject_id[tumor]))
differences <- clr_counts[tumor, ] - clr_counts[normal, ]
estimate <- colMeans(differences)
standard_error <- apply(differences, 2, sd) / sqrt(nrow(differences))
degrees <- nrow(differences) - 1
p_value <- 2 * pt(-abs(estimate / standard_error), df = degrees)
adjusted <- p.adjust(p_value, method = "BH")
margin <- qt(0.975, degrees) * standard_error
results <- data.frame(feature_id = colnames(filtered), estimate = estimate,
lower = estimate - margin, upper = estimate + margin,
p_value = p_value, adjusted = adjusted)
write.table(results, "outputs/paired_clr_r.tsv", sep = "\t",
row.names = FALSE, quote = FALSE)
cat("Tested OTUs:", nrow(results), "\n")
cat("OTUs with BH adjusted p below 0.05:", sum(adjusted < 0.05), "\n")
cat(sprintf("First OTU paired CLR effect: %.6f\n", estimate[1]))
plot_data <- results[order(abs(results$estimate), decreasing = TRUE)[1:12], ]
plot_data$feature_id <- factor(
plot_data$feature_id, levels = plot_data$feature_id
)
figure <- ggplot(plot_data, aes(estimate, feature_id)) +
geom_vline(xintercept = 0, color = "gray65") +
geom_errorbar(aes(xmin = lower, xmax = upper),
orientation = "y", width = 0.2) +
geom_point(color = "#286b8f") + theme_minimal(base_size = 12) +
labs(x = "Mean paired CLR difference with 95 percent interval",
y = "Reference OTU")
ggsave("outputs/differential_abundance_r.png", figure,
width = 7, height = 5, dpi = 160)
write_json(list(features = nrow(results), discoveries = sum(adjusted < 0.05),
first_estimate = estimate[1], first_adjusted = adjusted[1]),
"outputs/metrics_r.json", auto_unbox = TRUE, digits = 16)
Tested OTUs: 194
OTUs with BH adjusted p below 0.05: 70
First OTU paired CLR effect: -0.141042

Differential abundance from the R example.

A positive effect means that the OTU increased relative to the geometric mean of this filtered feature set. It does not establish that the number of its cells increased. A change in the reference components can change the ratio even when the absolute amount of the OTU stays constant.

The plot selects features by absolute effect size. That choice makes the displayed effects subject to selection, and the nominal intervals do not correct for it. The complete exported table preserves every tested OTU. Repeat the analysis with the alternate zero rule from the compositional data lesson before interpreting a result that depends on low counts.

ANCOM-BC2 models sampling bias and supports covariate adjustment and repeated measurements. Its assumptions and target differ from the direct CLR comparison above. A paired study still needs a supported patient adjustment, and estimated corrections do not replace an external microbial load measurement.

ALDEx2 propagates uncertainty through compositional transformations. A package name does not settle the design, reference denominator, or sensitivity analysis. Report the complete model and the meaning of its effect rather than selecting a method because it returns the largest list of taxa.

The following fits use the same retained OTUs and a fixed effect for each patient. The tissue coefficient compares tumor with normal after that adjustment. R uses ANCOMBC, and Python uses the implementation in scikit-bio. The fitted coefficient and its adjusted p-value are distinct from the direct CLR estimates above, even when their directions agree.

The one-count pseudocount is explicit in both fits. The R pseudocount sensitivity procedure is disabled for this implementation comparison. That check remains necessary before a biological interpretation.

library(ANCOMBC)
library(phyloseq)
model_metadata <- metadata[, c("sample_id", "subject_id", "tissue")]
rownames(model_metadata) <- model_metadata$sample_id
model_metadata$tissue <- factor(
model_metadata$tissue, levels = c("normal", "tumor")
)
model_metadata$subject_id <- factor(model_metadata$subject_id)
microbiome_data <- phyloseq(
otu_table(filtered, taxa_are_rows = FALSE), sample_data(model_metadata)
)
ancom_fit <- ancombc2(
data = microbiome_data, fix_formula = "subject_id + tissue",
pseudo = 1, pseudo_sens = FALSE, prv_cut = 0, lib_cut = 0,
p_adj_method = "BH", group = "tissue", struc_zero = FALSE,
global = FALSE, pairwise = FALSE, n_cl = 1, verbose = FALSE
)
ancom_results <- ancom_fit$res[, c(
"taxon", "lfc_tissuetumor", "se_tissuetumor", "q_tissuetumor"
)]
write.table(ancom_results, "outputs/ancombc_r.tsv", sep = "\t",
row.names = FALSE, quote = FALSE)
cat("ANCOM-BC2 tested OTUs:", nrow(ancom_results), "\n")
cat("ANCOM-BC2 BH discoveries:",
sum(ancom_results$q_tissuetumor < 0.05, na.rm = TRUE), "\n")
cat(sprintf("First OTU ANCOM-BC2 effect: %.6f\n",
ancom_results$lfc_tissuetumor[1]))
ANCOM-BC2 tested OTUs: 194
ANCOM-BC2 BH discoveries: 62
First OTU ANCOM-BC2 effect: -0.176406

Compare implementations on aligned features

Section titled “Compare implementations on aligned features”

The comparison below reads the R table written earlier in the same runner. It aligns OTU identifiers before comparing coefficients and discovery sets. Small numerical differences can arise from convergence and numerical routines; the code reports their size instead of assuming exact equality.

r_ancom = pd.read_csv(output / "ancombc_r.tsv", sep="\t", index_col=0)
r_ancom.index = r_ancom.index.astype(str)
ancom_results.index = ancom_results.index.astype(str)
r_ancom = r_ancom.loc[ancom_results.index]
effect_difference = np.abs(
r_ancom["lfc_tissuetumor"] - ancom_results["Log(FC)"]
)
same_discoveries = np.array_equal(
r_ancom["q_tissuetumor"] < 0.05, ancom_results["qvalue"] < 0.05
)
print("Largest absolute ANCOM-BC2 effect difference:",
f"{effect_difference.max():.9f}")
print("Identical ANCOM-BC2 discovery sets:", same_discoveries)
assert effect_difference.max() < 1e-5
assert same_discoveries
Largest absolute ANCOM-BC2 effect difference: 0.000000076
Identical ANCOM-BC2 discovery sets: True

Agreement checks the two implementations on this input and design. It does not validate their shared assumptions or turn a tissue association into a causal effect. Preserve the full results and examine zero sensitivity, covariates, and the interpretation of the sampling bias adjustment before reporting taxa.

Lin and Peddada, 2020 describe ANCOM-BC, the analysis of microbiome compositions with bias correction.

McMurdie and Holmes, 2013 describe phyloseq for reproducible analysis and graphics of microbiome census data.

Aton and colleagues, 2025 describe scikit-bio, the Python library for biological omic data analysis.

  • ANCOMBC ancombc2 reference

    The manual defines fixed effects, random effects, and pseudocount sensitivity. Read those arguments alongside the patient adjustment and disabled sensitivity procedure in this comparison.

  • scikit-bio ANCOM-BC2 reference

    The reference separates the core model from preprocessing and pseudocount sensitivity. It also describes the result table and covariate formula used to align the Python and R fits.

  • Gloor and colleagues, Microbiome Datasets Are Compositional

    The paper explains the relative reference of CLR effects. A direct CLR contrast and a sampling bias model require separate interpretations.