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.
Run this example
Section titled “Run this example”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.
Read the data and calculate the result
Section titled “Read the data and calculate the result”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) - 1p_value <- 2 * pt(-abs(estimate / standard_error), df = degrees)adjusted <- p.adjust(p_value, method = "BH")margin <- qt(0.975, degrees) * standard_errorresults <- 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: 194OTUs with BH adjusted p below 0.05: 70First OTU paired CLR effect: -0.141042
import jsonfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom scipy import statsfrom scipy.spatial.distance import pdist, squareform
counts = pd.read_csv( "/fixtures/cohort_counts.tsv", sep="\t", index_col=0).Tmetadata = pd.read_csv( "/fixtures/cohort_metadata.tsv", sep="\t", index_col=0).loc[counts.index]assert counts.index.equals(metadata.index)assert (counts.to_numpy() >= 0).all()assert (counts.to_numpy() == np.floor(counts.to_numpy())).all()output = Path("outputs")output.mkdir(exist_ok=True)
from statsmodels.stats.multitest import multipletests
filtered = counts.loc[:, (counts >= 5).mean(axis=0) >= 0.10]logged = np.log(filtered.to_numpy() + 1)clr_counts = logged - logged.mean(axis=1, keepdims=True)normal = metadata["tissue"].to_numpy() == "normal"tumor = metadata["tissue"].to_numpy() == "tumor"assert np.array_equal(metadata.loc[normal, "subject_id"], metadata.loc[tumor, "subject_id"])differences = clr_counts[tumor] - clr_counts[normal]estimate = differences.mean(axis=0)standard_error = stats.sem(differences, axis=0)degrees = len(differences) - 1p_value = stats.ttest_1samp(differences, 0, axis=0).pvalueadjusted = multipletests(p_value, method="fdr_bh")[1]margin = stats.t.ppf(0.975, degrees) * standard_errorresults = pd.DataFrame({"feature_id": filtered.columns, "estimate": estimate, "lower": estimate - margin, "upper": estimate + margin, "p_value": p_value, "adjusted": adjusted})results.to_csv(output / "paired_clr_python.tsv", sep="\t", index=False)print(f"Tested OTUs: {len(results)}")print(f"OTUs with BH adjusted p below 0.05: {(adjusted < 0.05).sum()}")print(f"First OTU paired CLR effect: {estimate[0]:.6f}")selected = np.argsort(-np.abs(estimate), kind="stable")[:12]figure, axis = plt.subplots(figsize=(7, 5))axis.axvline(0, color="gray")axis.errorbar(estimate[selected], np.arange(12), xerr=margin[selected], fmt="o", color="#286b8f")axis.set_yticks(np.arange(12), filtered.columns[selected].astype(str))axis.set(xlabel="Mean paired CLR difference with 95 percent interval", ylabel="Reference OTU")figure.tight_layout()figure.savefig(output / "differential_abundance_python.png", dpi=160)plt.close(figure)metrics = {"features": len(results), "discoveries": int((adjusted < 0.05).sum()), "first_estimate": float(estimate[0]), "first_adjusted": float(adjusted[0])}(output / "metrics_python.json").write_text(json.dumps(metrics))Tested OTUs: 194OTUs with BH adjusted p below 0.05: 70First OTU paired CLR effect: -0.141042
Interpret a relative change
Section titled “Interpret a relative change”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.
Select a method for the scientific target
Section titled “Select a method for the scientific target”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.
Fit ANCOM-BC2 in both languages
Section titled “Fit ANCOM-BC2 in both languages”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_idmodel_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: 194ANCOM-BC2 BH discoveries: 62First OTU ANCOM-BC2 effect: -0.176406from skbio.stats.composition import ancombc2
model_metadata = metadata.loc[:, ["subject_id", "tissue"]].copy()model_metadata["tissue"] = pd.Categorical( model_metadata["tissue"], categories=["normal", "tumor"])model_metadata["subject_id"] = pd.Categorical(model_metadata["subject_id"])ancom_fit = ancombc2( filtered, model_metadata, formula="subject_id + tissue", pseudocount=1, p_adjust="fdr_bh")ancom_results = ancom_fit.result.xs("tissue[T.tumor]", level="Covariate")ancom_results.to_csv(output / "ancombc_python.tsv", sep="\t")print("ANCOM-BC2 tested OTUs:", len(ancom_results))print("ANCOM-BC2 BH discoveries:", int((ancom_results["qvalue"] < 0.05).sum()))print(f"First OTU ANCOM-BC2 effect: {ancom_results['Log(FC)'].iloc[0]:.6f}")ANCOM-BC2 tested OTUs: 194ANCOM-BC2 BH discoveries: 62First OTU ANCOM-BC2 effect: -0.176406Compare 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-5assert same_discoveriesLargest absolute ANCOM-BC2 effect difference: 0.000000076Identical ANCOM-BC2 discovery sets: TrueAgreement 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.
Scientific references
Section titled “Scientific references”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.
Further reading
Section titled “Further reading”-
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.