15  Differential abundance

An important component of many microbiome studies is differential abundance analysis (DAA). It is mainly used to identify differences in the abundances of individual taxa (at any taxonomic level) between two or more groups, such as treatment versus control groups.

The goal of DAA is thus to identify biomarkers of a certain phenotype or condition, and gain understanding of a complex system by looking at its isolated components. For example, the identification of a bacterial taxon that is more abundant in healthy versus diseased individuals can lead to important insights into the underlying mechanisms of the disease. In other words, differentially abundant taxa can be involved in the dynamics of the disease, which in turn helps to understand the system as a whole.

15.1 Challenges

As discussed in Section 10.1, microbiome data display unique properties, such as compositionality and skewed/zero-inflated distributions. Evidently, these properties need to be addressed properly also in DAA. Unfortunately, there is currently no consensus on how that should be done. Instead, there exist dozens of methods employing varying techniques and, consequently, providing highly discordant results.

The discordancy of results provided by different DAA methods was recently well illustrated by Nearing et al. (2022). In this study, multiple DAA methods were applied to 38 different datasets and their results were compared to one another. Similar findings were also made by Yang and Chen (2022) who evaluated DAA methods on 106 real datasets (along with simulated data). They found especially that on many datasets almost any taxon was detected by at least one DAA method (see Figure 7 in their article). They thus raised concerns of potential cherry-picking, that is, a researcher would be likely to find the taxa in favor of their hypothesis by just trying out several different DAA methods.

15.2 Recommendations

Usually, when a new DAA method is introduced, the authors demonstrate it to perform better compared to some of the existing alternatives. That is often achieved by employing simulated data and possibly one or more real datasets. The authors may have, however, selected their simulation models, example datasets, evaluation metrics, compared methods, etc. specifically to show the introduced method in a favorable light. Assessing the performance of different methods based solely on the studies where they were originally introduced may therefore not be advisable.

A more neutral evaluation of the performance of different DAA methods can be found from several independent benchmarking studies (e.g. Weiss et al. (2017), Hawinkel et al. (2019), Calgaro et al. (2020), Wallen (2021), Nearing et al. (2022), Yang and Chen (2022), Cappellato et al. (2022), Roche and Mukherjee (2022), Swift et al. (2023), Wirbel et al. (2024), Pelto et al. (2025), Gamboa-Tuz et al. (2025)). Unfortunately, these studies have ended up with very discordant conclusions on the methods. However, if we look specifically at some benchmarking studies that have used only real datasets (instead of simulated data), we can see that analysis of relative abundances (TSS normalized counts) with a simple non-parametric method or linear regression has performed well.

A broken promise: Microbiome differential abundance methods do not control the false discovery rate. Hawinkel et al. (2019). Brief Bioinform 20:210–221. doi:10.1093/BIB/BBX104.
Comparison study of differential abundance testing methods using two large Parkinson disease gut microbiome datasets derived from 16S amplicon sequencing. Wallen (2021). BMC Bioinformatics 22:1–29. doi:10.1186/s12859-021-04193-6.
Investigating differential abundance methods in microbiome data: A benchmark study. Cappellato et al. (2022). PLoS Comput Biol 18:e1010467. doi:10.1371/JOURNAL.PCBI.1010467.
A review of normalization and differential abundance methods for microbiome counts data. Swift et al. (2023). WIREs Comput Stat 15:e1586. doi:10.1002/WICS.1586.
A realistic benchmark for differential abundance testing and confounder adjustment in human microbiome studies. Wirbel et al. (2024). Genome Biol 25:247. doi:10.1186/S13059-024-03390-9.
  • Nearing et al. (2022) studied the performance of DAA methods using 38 datasets. They evaluated the number of detected taxa (ASVs), consistency of the detected taxa between methods, replication of results between studies and error rate on datasets with randomly assigned groups. They emphasized conservatism (low error rate) in their recommendations and ended up recommending ALDEx2 (Fernandes et al. 2014) and ANCOM (Mandal et al. 2015). In this book, we use the newer ANCOM-BC method (Lin and Peddada 2020) from the ANCOMBC package instead of the original ANCOM. Nearing et al. (2022) also recommended Maaslin2 (Mallick et al. 2021) (i.e. analyzing arcsine square root transformed relative abundances with linear regression) as a more powerful option.

  • In addition to simulations, Yang and Chen (2022) estimated the FDR of different DAA methods on 106 real datasets with randomly created groups. They found that the observed FDR was at the nominal level when, for instance, analyzing relative abundances either with the Wilcoxon test (Wilcoxon 1945) or with linear regression (Maaslin2).

  • Pelto et al. (2025) studied how the results from different DAA methods replicate between random partitions of datasets and between datasets from independent studies. They found that when considering consistency along with sensitivity, the best performance was obtained by analyzing relative abundances with a non-parametric method or (after log transformation) with linear regression/t-test (Maaslin2) or analyzing presence/absence of taxa with logistic regression. Their approach is illustrated in Figure 15.1.

  • Gamboa-Tuz et al. (2025) employed three real datasets to benchmark different DAA methods against biological ground truth. They found that methods employing the TSS normalization (with e.g. the Wilcoxon test) and RNA-seq-derived methods performed best.

Microbiome differential abundance methods produce different results across 38 datasets. Nearing et al. (2022). Nat Commun 13:342. doi:10.1038/s41467-022-28034-z.
Unifying the analysis of high-throughput sequencing datasets: Characterizing RNA-seq, 16S rRNA gene sequencing and selective growth experiments by compositional data analysis. Fernandes et al. (2014). Microbiome 2:15. doi:10.1186/2049-2618-2-15.
Analysis of composition of microbiomes: A novel method for studying microbial composition. Mandal et al. (2015). Microb Ecol Health Dis 26. doi:10.3402/mehd.v26.27663.
Individual comparisons by ranking methods. Wilcoxon (1945). Biometrics Bull 1:80. doi:10.2307/3001968.
Schematic in three panels. Panel a: an exploratory and a validation dataset, each with a control and a case group, are analyzed separately; the forest plots of five taxa are then overlaid, showing taxon 1 with conflicting estimates and taxon 4 with replicated estimates. Panel b: one original dataset is randomly split into exploratory and validation sets. Panel c: two separate studies serve as the exploratory and validation sets.
Figure 15.1: Assessing the replicability of differential abundance analysis. (a) DAA is performed separately on an exploratory and a validation dataset, and the estimates for each taxon are compared. A taxon whose estimates point in opposite directions is a conflicting finding, and a taxon whose estimates agree is a replicated finding. The exploratory and validation datasets are obtained (b) by randomly splitting one dataset or (c) from two independent studies. Reproduced from Pelto et al. (2025) under CC BY 4.0.

We therefore recommend performing DAA by analyzing relative (TSS normalized) abundances by a non-parametric method (e.g., the Wilcoxon test or ordinal regression model) or, after a log transformation, with t-test/linear regression. In addition to their good performance on real data they have the benefit of being intuitive and easy to understand. Linear regression of log-transformed relative abundances is implemented, for instance, in LimROTS (Anwar et al. 2025) and Maaslin2 (Mallick et al. 2021), which we demonstrate below (Section 15.3).

Normalization and microbial differential abundance strategies depend upon data characteristics. Weiss et al. (2017). Microbiome 5:1–18. doi:10.1186/s40168-017-0237-y.
Assessment of statistical methods from single cell, bulk RNA-seq, and metagenomics applied to microbiome data. Calgaro et al. (2020). Genome Biol 21:191. doi:10.1186/s13059-020-02104-1.
benchdamic: Benchmarking of differential abundance methods for microbiome data. Calgaro et al. (2023). Bioinformatics 39:btac778. doi:10.1093/bioinformatics/btac778.

We note, however, that the performance of DAA methods likely depends on the characteristics of the analyzed data (Weiss et al. 2017; Calgaro et al. 2020). Consequently, while the methods recommended above seem to be good general default methods, they may not necessarily be the optimal methods in many cases. If one wants to evaluate which method may perform best specifically on their data, one option is to use the benchdamic package by Calgaro et al. (2023) (see vignette here).

Lastly, based on recent studies on classification accuracy of healthy vs. non-healthy patients, it seems that a high proportion of information in microbiome data is included in the mere presence/absence of taxa (Giliberti et al. 2022; Karwowska et al. 2025). A viable, and even simpler, alternative to DAA is thus differential prevalence analysis (see also Pelto et al. (2025)), which is covered in Chapter 16.

Host phenotype classification from human microbiome data is mainly driven by the presence of microbial taxa. Giliberti et al. (2022). PLoS Comput Biol 18:e1010066. doi:10.1371/journal.pcbi.1010066.
Effects of data transformation and model selection on feature importance in microbiome classification data. Karwowska et al. (2025). Microbiome 13. doi:10.1186/s40168-024-01996-6.

15.3 In practice

Following the recommendations above, we show in this section how to perform DAA by analyzing (log transformed) relative abundances with linear regression models, using LimROTS and Maaslin2. We first compare two groups with LimROTS while controlling for a covariate (Section 15.3.2). We then show with MaAsLin2 the simplest case where two groups are compared without other covariates, followed by more complex analyses, namely, the analysis with additional covariate(s) included and the analysis with interaction of two variables. Furthermore, we illustrate the differential analysis of positive (non-zero) abundances. Differential prevalence analysis is shown in Chapter 16.

15.3.1 Preparing the data

We use the Tengeler2020 dataset (C Tengeler et al. 2020) (Section D.4), in which mice were humanized with the gut microbiota of either individuals with ADHD (N = 13) or healthy controls (N = 14). The samples belong to three different cohorts.

Gut microbiota from persons with attention-deficit/hyperactivity disorder affects the brain in mice. C Tengeler et al. (2020). Microbiome 8:1–14. doi:10.1186/s40168-020-00816-x.
# Load the needed packages
library(mia)
library(knitr)
library(dplyr)
library(tinytable)

# Import dataset
data("Tengeler2020", package = "mia")
tse <- Tengeler2020

# Show patient status by cohort
table(tse$patient_status, tse$cohort) |>
    kable()
Cohort_1 Cohort_2 Cohort_3
ADHD 4 5 4
Control 6 5 3

Before starting the analysis, we agglomerate the features by genus and filter them by a prevalence threshold of 10%. Furthermore, we create assays for relative abundances and presence/absence of taxa. Lastly, we transform variable patient_status to a factor with Control as the reference level. (It is a standard practice to use the control group as the reference group in many statistical analyses.)

# Agglomerate by genus and subset by prevalence
tse <- agglomerateByRank(tse, rank = "Genus")
tse <- addPrevalence(tse)
tse <- subsetBy(tse, rows = prevalence > 0.1)

# Transform count data and create assay of relative abundances
tse <- transformAssay(tse, assay.type = "counts", method = "relabundance")

# Transform count data and create assay of presence/absence of taxa
tse <- transformAssay(tse, assay.type = "counts", method = "pa")

# Transform patient_status to a factor and set "Control" as the reference level
tse$patient_status <- factor(tse$patient_status, levels = c("Control", "ADHD"))

# We also transform cohort as a factor
tse$cohort <- factor(tse$cohort, levels = c("Cohort_1", "Cohort_2", "Cohort_3"))

15.3.2 LimROTS

We first perform DAA with LimROTS (Anwar et al. 2025), which fits a linear model for each taxon. It combines the linear model and the empirical Bayes variance moderation of limma (Ritchie et al. 2015) with a reproducibility-optimized test statistic. LimROTS extends the ROTS method (Elo et al. 2008) with support for covariates. The statistic is tuned with bootstrap resampling so that the ranking of the taxa is as reproducible as possible, and the p-values are obtained by permutation. LimROTS works directly with SummarizedExperiment objects, including TreeSE, and it adds the results to the rowData of the data.

LimROTS: A hybrid method integrating empirical Bayes and reproducibility-optimized statistics for robust differential expression analysis. Anwar et al. (2025). Bioinformatics 41:btaf570. doi:10.1093/bioinformatics/btaf570.
limma powers differential expression analyses for RNA-sequencing and microarray studies. Ritchie et al. (2015). Nucleic Acids Res 43:e47. doi:10.1093/nar/gkv007.
Reproducibility-optimized test statistic for ranking genes in microarray studies. Elo et al. (2008). IEEE/ACM Trans Comput Biol Bioinform 5:423–431. doi:10.1109/tcbb.2007.1078.

Compared with standard linear models, such as those fitted by MaAsLin2 (Section 15.3.3.1), LimROTS has some potential advantages. The empirical Bayes moderation borrows information across taxa to stabilize the variance estimates, which helps when there are few samples. The reproducibility optimization adapts the test statistic to the data at hand, and the permutation-based p-values do not rely on the distributional assumptions of the linear model, which log-transformed abundances with many zeros often violate (Anwar et al. 2025).

LimROTS expects log-transformed data. We analyze log2 transformed relative abundances, and the zeros are replaced by half of the smallest non-zero relative abundance in the data before the transformation. We compare the ADHD and control groups while controlling for cohort as a covariate (the role of covariates is discussed in Section 15.3.3.3). The group variable must be a factor, and LimROTS reports the difference between its first and second level. To obtain the log2-fold change of ADHD versus Control, we therefore put ADHD first. The number of bootstrap and permutation iterations is set with niter, and the runs can be parallelized with the BPPARAM argument.

library(LimROTS)
library(BiocParallel)

# Log2-transform relative abundances, adding half of the smallest positive
# relative abundance as a pseudocount
relab <- assay(tse, "relabundance")
tse <- transformAssay(
    tse,
    assay.type = "relabundance",
    method = "log2",
    pseudocount = min(relab[relab > 0]) / 2,
    name = "log2_relabundance"
)

# LimROTS reports the first level minus the second level of the group
tse_limrots <- tse
tse_limrots$patient_status <- factor(
    tse_limrots$patient_status,
    levels = c("ADHD", "Control")
)

set.seed(123)
tse_limrots <- LimROTS(
    tse_limrots,
    assay.type = "log2_relabundance",
    meta.info = c("patient_status", "cohort"), # Variables used in the model
    group = "patient_status", # The variable of interest
    formula.str = "~ 0 + patient_status + cohort",
    niter = 1000, # Bootstrap and permutation iterations
    BPPARAM = SerialParam(), # For example, MulticoreParam(4) to parallelize
    verbose = FALSE
)

The results are stored in the rowData. We extract the log2-fold change estimates (corrected.logfc), the permutation-based p-values (pvalue) and the Benjamini-Hochberg adjusted p-values (BH.pvalue), that is, the q-values (Benjamini and Hochberg 1995). Positive log2-fold changes (coef) indicate a higher abundance in the ADHD group.

res_limrots <- data.frame(
    feature = rownames(tse_limrots),
    coef = rowData(tse_limrots)$corrected.logfc,
    pval = rowData(tse_limrots)$pvalue,
    qval = rowData(tse_limrots)$BH.pvalue
)

# Print the results for taxa with the smallest p-values
res_limrots |>
    arrange(pval) |>
    head() |>
    tt() |>
    format_tt(digits = 3, num_fmt = "significant_cell")
feature coef pval qval
Anaerostipes 4.34 0.0000102 0.0000455
Anaerotruncus -3.39 0.0000102 0.0000455
Dielma -4.63 0.0000102 0.0000455
Eisenbergiella -4.34 0.0000102 0.0000455
Eubacterium -8.35 0.0000102 0.0000455
Holdemania -3.62 0.0000102 0.0000455

Using the standard criterion for statistical significance, q-value < 0.05, the abundances of 29 out of 49 genera differ between the groups. Several genera share the smallest p-value that is possible with the number of permutations used. For instance, [Eubacterium] fissicatena group has a positive log2-fold change, so it is more abundant in the ADHD group, while [Eubacterium] rectale group is less abundant. We repeat the analysis with MaAsLin2 in the following sections and compare the results in Section 15.3.3.3.

15.3.3 MaAsLin2

We then perform DAA with the Maaslin2() function from the Maaslin2 package (Mallick et al. 2021). We show the simplest case where two groups are compared, the analysis with a covariate, and the analysis with an interaction of two variables.

Multivariable association discovery in population-scale meta-omics studies. Mallick et al. (2021). PLoS Comput Biol 17:e1009442. doi:10.1371/journal.pcbi.1009442.

15.3.3.1 Two groups

Here, we perform the simplest version of DAA, namely, the comparison of two groups without any other covariates included in the analysis. In our case, this means comparing the relative abundances of genera between the microbiome of ADHD individuals versus control.

The Maaslin2() function

  • transforms counts to relative abundances,
  • replaces zeros by half of the smallest non-zero relative abundance (separately for each taxon),
  • applies log2 transformation to the relative abundances, and
  • runs a linear regression model for each taxon using the transformed relative abundances as the response variable.

To run the function we need to provide it with the count matrix and metadata as inputs. We also need to provide it with the variable indicating the compared groups, i.e. patient_status in our case. Furthermore, we need to specify the folder for some output files. Lastly, we prevent Maaslin2() from creating certain plots. (Note that Maaslin2() prints a lot of output, which is suppressed here for convenience.)

library(Maaslin2)

obj_daa_basic <- Maaslin2(
    input_data = assay(tse), # The count matrix
    input_metadata = colData(tse) |> as.data.frame(), # The metadata
    fixed_effects = "patient_status", # The predictor variable

    output = "output", # The name of the folder for output files.
    plot_heatmap = FALSE,
    plot_scatter = FALSE
)

Next, we extract the data.frame of results from the list object returned by Maaslin2() and keep the most relevant columns.

# Extract the results from the list object
res_daa_basic <- obj_daa_basic$results |>
    select(feature, name, coef, stderr, pval, qval) |>
    mutate(feature = rownames(tse)[match(feature, make.names(rownames(tse)))])

# Print the results for taxa with the smallest p-values
res_daa_basic |>
    arrange(pval) |>
    head() |>
    tt() |>
    format_tt(digits = 3, num_fmt = "significant_cell")
feature name coef stderr pval qval
Eubacterium patient_statusADHD -1.54 0.131 0.0000000000101 0.000000000495
Dielma patient_statusADHD -2.35 0.37 0.00000116 0.0000198
Ruminococcaceae_UCG-004 patient_statusADHD 2.96 0.467 0.00000121 0.0000198
[Eubacterium]_rectale_group patient_statusADHD -2.91 0.47 0.00000177 0.0000217
[Eubacterium]_fissicatena_group patient_statusADHD 3.96 0.698 0.00000662 0.0000649
Parabacteroides patient_statusADHD -3.32 0.602 0.00000989 0.0000808

The columns of res_daa_basic are as follows:

  • feature indicates the name of a taxon (here genus).
  • name indicates the predictor variable. As patient_status is a categorical variable, it also tells the group used as the non-reference level (here ADHD as Control was set as the reference level).
  • coef is the log2-fold change estimate, a standard way to express effect size in DAA. Most importantly, positive values indicate abundance being higher in the non-reference group (here ADHD). More precisely, 2 ^ coef would be interpreted as the ratio of geometric means of the relative abundances between the ADHD and Control groups.
  • stderr is the standard error of the log2-fold change estimate. It is used below to calculate the confidence intervals.
  • pval is the unadjusted p-value.
  • qval (q-value) is the FDR adjusted p-value (Benjamini and Hochberg 1995). This is generally used to define statistical significance. Typically, q-values < .05 are considered (statistically) significant.
Controlling the false discovery rate: A practical and powerful approach to multiple testing. Benjamini et al. (1995). J R Stat Soc Series B 57:289–300. doi:10.1111/J.2517-6161.1995.TB02031.X.

Now, if we use the standard criterion for statistical significance, namely, q-value < 0.05, we can see that the DAA result is statistically significant for 24 out of 49 genera. The smallest p-values are observed for the genera named as Eubacterium, Dielma, Ruminococcaceae UCG-004, [Eubacterium] rectale group and [Eubacterium] fissicatena group. (Maaslin2 has some problems with special characters such as [ or ], so we mapped the names back to the original ones above.) Moreover, for instance, the negative log2-fold change estimate of Eubacterium tells that the average relative abundance of Eubacterium is lower in the ADHD group, whereas the positive estimate of Ruminococcaceae UCG-004 tells that its average relative abundance is higher in the ADHD group.

15.3.3.2 Visualizing the results

While the numbers above provide summarized information about the group differences for each taxon, it is often useful to further examine these associations in more detail. That can be done, for instance, using strip plots with boxplots. We show here how such plots can be created for the five significant genera with the smallest p-values by using the plotBoxplot() function from the miaViz package (Figure 15.2).

library(miaViz)

# Create strip plots with boxplots (and prevalence bars)
plotBoxplot(
    tse,
    features = c(
        "Eubacterium",
        "Dielma",
        "Ruminococcaceae_UCG-004",
        "[Eubacterium]_rectale_group",
        "[Eubacterium]_fissicatena_group"
    ),
    assay.type = "relabundance", # To plot relative abundances
    x = "patient_status", # The variable on the x (horizontal) axis
    facet.by = "rownames", # To create a separate facet for each feature
    scales = "free_y", # To allow different y-axis scales
    add.proportion = TRUE # Add bars indicating prevalence
) +
    labs(x = "Patient status", y = "Relative abundance")
Five facets, one per genus, each with free y-axis scales and showing relative abundance in the ADHD and Control groups as boxplots overlaid with points for individual samples, plus horizontal prevalence bars below the boxes. Eubacterium, Dielma and [Eubacterium] rectale group are higher in the Control group, whereas Ruminococcaceae UCG-004 and [Eubacterium] fissicatena group are higher in the ADHD group.
Figure 15.2: Relative abundances of the five significant genera with the smallest p-values in the ADHD and Control groups of the Tengeler2020 data, shown as strip plots with boxplots in a separate facet for each genus. The bars at the bottom show the prevalence of each genus in each group.

In each facet,

  • the thicker horizontal line in each boxplot indicates the median,
  • each box indicates the interquartile range (IQR), namely, the range between the 25th (Q1) and 75th percentile (Q3),
  • the lower whisker indicates the smallest value above \(Q1 - 1.5 \times IQR\),
  • the upper whisker indicates the largest value below \(Q3 + 1.5 \times IQR\), and
  • the horizontal bars at the bottom indicate the prevalence of each genus in each group.

The strip plots and boxplots clearly show, for instance, how the relative abundance of Eubacterium is lower in the ADHD group, as was indicated by the negative log2-fold change estimate (coef) in the results table above. Moreover, the prevalence bars show that these genera differ also in their presence. For instance, Eubacterium is present in all samples of the control group but in none of the ADHD group, whereas Ruminococcaceae UCG-004 is present only in the ADHD group.

Lastly, we show how the results for all genera can be summarized visually by plotting the log2-fold change estimates and their 95% confidence intervals (Figure 15.3). plotForest() calculates the confidence intervals from the standard errors (err.var), using the t distribution with the residual degrees of freedom (df) of the model. Here, the degrees of freedom are the number of samples minus the number of estimated coefficients, that is, the intercept and patient_status.

# Plot the log2-fold changes and the 95% confidence intervals
plotForest(
    res_daa_basic,
    effect.var = "coef",
    err.var = "stderr",
    df = ncol(tse) - 2,
    id.var = "feature",
    order.by = "coef"
) +
    labs(x = "Log2 fold change (ADHD vs. Control)")
Forest plot with one row per genus, sorted by estimate, showing the log2-fold change as a point with a horizontal 95% confidence interval. Many genera have confidence intervals that do not contain zero, some with negative and some with positive estimates.
Figure 15.3: Forest plot of the log2-fold change estimates (ADHD vs. Control) and their 95% confidence intervals for all genera in the Tengeler2020 data, ordered by the estimate.

15.3.3.3 With covariates

Here we show how to perform DAA with an additional covariate included in the analysis. One usually wants to include a variable as a covariate if they suspect that it may act as a confounding variable, namely, a variable that causes a spurious association between the variable of main interest and the abundances.

We use here cohort as a covariate. We proceed as above except that we now set fixed_effects = c("patient_status", "cohort"). Furthermore, we now calculate the q-values manually so that they are calculated separately for each variable in the model (indicated by the variable metadata in obj_daa_cov$results). This is because Maaslin2() calculates the q-values over all variables in the model, which is not what we want here, as we are only interested in the variable patient_status.

# Run Maaslin2 with patient_status and cohort as predictor variables
obj_daa_cov <- Maaslin2(
    input_data = assay(tse),
    input_metadata = colData(tse) |> as.data.frame(),
    fixed_effects = c("patient_status", "cohort"),
    output = "output",
    plot_heatmap = FALSE,
    plot_scatter = FALSE
)

# Extract the results and calculate the q-values for each variable
res_daa_cov <- obj_daa_cov$results |>
    group_by(metadata) |>
    mutate(qval = p.adjust(pval, method = "fdr")) |>
    ungroup() |>
    select(feature, name, coef, stderr, pval, qval) |>
    mutate(feature = rownames(tse)[match(feature, make.names(rownames(tse)))])
# Print a sample of the results
res_daa_cov |>
    arrange(feature, name) |>
    head() |>
    tt() |>
    format_tt(digits = 3, num_fmt = "significant_cell")
feature name coef stderr pval qval
Akkermansia cohortCohort_2 0.557 0.46 0.238 0.357
Akkermansia cohortCohort_3 0.561 0.509 0.282 0.4
Akkermansia patient_statusADHD 0.243 0.398 0.548 0.671
Alistipes cohortCohort_2 0.0469 0.416 0.911 0.95
Alistipes cohortCohort_3 0.252 0.461 0.59 0.688
Alistipes patient_statusADHD 0.557 0.361 0.136 0.197

Note that there now appear results also for the variable cohort. As cohort consists of three groups, namely, Cohort_1 (the reference group), Cohort_2 and Cohort_3, there are results separately for the comparison between Cohort_2 vs. Cohort_1 (cohortCohort_2) and for the comparison between Cohort_3 vs. Cohort_1 (cohortCohort_3).

We can now examine how the inclusion of cohort as a covariate affects the results for patient_status.

# Print the results for taxa with the smallest p-values for patient_status
res_daa_cov |>
    filter(name == "patient_statusADHD") |>
    arrange(pval) |>
    head() |>
    tt() |>
    format_tt(digits = 3, num_fmt = "significant_cell")
feature name coef stderr pval qval
Eubacterium patient_statusADHD -1.54 0.137 0.000000000086 0.00000000421
Dielma patient_statusADHD -2.46 0.338 0.000000203 0.00000494
[Eubacterium]_rectale_group patient_statusADHD -3.07 0.431 0.000000303 0.00000494
Ruminococcaceae_UCG-004 patient_statusADHD 2.93 0.448 0.00000111 0.0000114
Parabacteroides patient_statusADHD -3.52 0.54 0.00000117 0.0000114
Eisenbergiella patient_statusADHD -3.06 0.482 0.00000178 0.0000145

When comparing these results to the results in Section 15.3.3.1, we can see that, for instance, the q-values of Dielma and Parabacteroides are now somewhat smaller, and a few more genera have q-values below 0.05. Nevertheless, the results look overall rather similar to the results without the covariate included: the same genera have the smallest p-values, and the genera that were significant without the covariate remain significant. Therefore, cohort does not seem to be a confounder causing spurious associations between patient status and the abundances of any taxa.

These results also agree well with those of LimROTS with the same model (Section 15.3.2). Largely the same genera have the smallest p-values, and the log2-fold changes of the significant genera have the same signs. The estimates are not identical, as the zeros are replaced differently (MaAsLin2 uses the smallest non-zero value of each taxon, whereas we used the smallest value in the whole data with LimROTS) and the p-values are computed differently. In this example, a few more genera passed the q < 0.05 threshold with LimROTS (29 genera) than with MaAsLin2 (27 genera).

15.3.3.4 With an interaction

Here we show a more complex version of DAA, namely, a case where the interaction effect of two variables is analyzed. We give this example here for illustration purposes but note that such complex analysis may not be advisable in a small dataset such as our example dataset.

We analyze the interaction between patient_status and cohort. We proceed as in Section 15.3.3.3 above except that we now also add the interaction term into the formula. As Maaslin2() does not directly support the analysis with interactions, we must first create the interaction dummy variables into the tse object. The main effects patient_status and cohort as well as the interaction dummy variables are then included in the Maaslin2() function.

# Create dummy variables for the interaction term
tse$patient_statusADHD_cohortCohort_2 <-
    ifelse(tse$patient_status == "ADHD" & tse$cohort == "Cohort_2", 1, 0)
tse$patient_statusADHD_cohortCohort_3 <-
    ifelse(tse$patient_status == "ADHD" & tse$cohort == "Cohort_3", 1, 0)

# Run Maaslin2 with patient_status, cohort and their interaction terms
obj_daa_ia <- Maaslin2(
    input_data = assay(tse),
    input_metadata = colData(tse) |> as.data.frame(),
    fixed_effects = c(
        "patient_status",
        "cohort",
        "patient_statusADHD_cohortCohort_2",
        "patient_statusADHD_cohortCohort_3"
    ),
    output = "output",
    plot_heatmap = FALSE,
    plot_scatter = FALSE
)

# Extract the results and calculate the q-values for each variable
res_daa_ia <- obj_daa_ia$results |>
    mutate(
        metadata = ifelse(
            metadata %in% c(
                "patient_statusADHD_cohortCohort_2",
                "patient_statusADHD_cohortCohort_3"
            ),
            "patient_status:cohort",
            metadata
        )
    ) |>
    group_by(metadata) |>
    mutate(qval = p.adjust(pval, method = "fdr")) |>
    ungroup() |>
    select(feature, name, coef, stderr, pval, qval) |>
    mutate(feature = rownames(tse)[match(feature, make.names(rownames(tse)))])
# Print a sample of the results
res_daa_ia |>
    arrange(feature, name) |>
    head() |>
    tt() |>
    format_tt(digits = 3, num_fmt = "significant_cell")
feature name coef stderr pval qval
Akkermansia cohortCohort_2 1.31 0.555 0.0276 0.06
Akkermansia cohortCohort_3 1.68 0.648 0.0168 0.0404
Akkermansia patient_statusADHD 1.52 0.592 0.0178 0.0364
Akkermansia patient_statusADHD_cohortCohort_2 -0.701 0.328 0.0445 0.101
Akkermansia patient_statusADHD_cohortCohort_3 -0.85 0.332 0.0182 0.0545
Alistipes cohortCohort_2 0.571 0.517 0.282 0.485

The results object res_daa_ia now also includes the interaction terms patient_statusADHD_cohortCohort_2 and patient_statusADHD_cohortCohort_3.

We examine the term patient_statusADHD_cohortCohort_3. It indicates how the differences between the ADHD and Control groups vary between cohorts 1 and 3.

# Print the results for the interaction term patient_statusADHD_cohortCohort_3
res_daa_ia |>
    filter(name == "patient_statusADHD_cohortCohort_3") |>
    arrange(pval) |>
    head() |>
    tt() |>
    format_tt(digits = 3, num_fmt = "significant_cell")
feature name coef stderr pval qval
Paraprevotella patient_statusADHD_cohortCohort_3 1.11 0.0749 0.00000000000127 0.000000000125
Catabacter patient_statusADHD_cohortCohort_3 1.53 0.219 0.000000674 0.0000103
Coprobacter patient_statusADHD_cohortCohort_3 1.46 0.231 0.0000027 0.0000328
uncultured_2 patient_statusADHD_cohortCohort_3 0.638 0.101 0.00000301 0.0000328
Anaerotruncus patient_statusADHD_cohortCohort_3 -0.978 0.21 0.000134 0.0011
[Eubacterium]_fissicatena_group patient_statusADHD_cohortCohort_3 -1.88 0.439 0.000335 0.00252

The smallest p-value is observed for Paraprevotella. As the corresponding log2-fold change estimate is positive it means that the difference in the relative abundance of Paraprevotella between the ADHD and Control groups is higher in Cohort 3 than in Cohort 1.

This interaction can be better illustrated by plotting the relative abundances of Paraprevotella by patient_status and cohort (Figure 15.4).

# Plot the abundances of Paraprevotella by patient_status and cohort
plotBoxplot(
    tse,
    features = "Paraprevotella",
    assay.type = "relabundance", # To plot relative abundances
    x = "patient_status", # The variable on the x (horizontal) axis
    facet.by = "cohort", # To create a separate plot for each cohort
    add.proportion = TRUE # Add bars indicating prevalence
) +
    labs(x = "Patient status", y = "Relative abundance")
Facets for each cohort with the same y-axis scale, each showing Paraprevotella relative abundance in the ADHD and Control groups as boxplots with points for individual samples and prevalence bars below. Paraprevotella is present only in the Control group in Cohort 1, absent in Cohort 2, and present only in the ADHD group in Cohort 3.
Figure 15.4: Relative abundances of Paraprevotella in the ADHD and Control groups of the Tengeler2020 data, shown separately for each cohort. The bars at the bottom show the prevalence of Paraprevotella in each group.

Here we can clearly see how the relative abundances of Paraprevotella are higher in the Control group in Cohort 1 but they are higher in the ADHD group in Cohort 3. As the association is negative in Cohort 1 (the baseline cohort) and positive in Cohort 3, the sign of the interaction estimate is positive (the association becomes more positive when we move from the baseline cohort to a non-baseline cohort). Note also that within each cohort, Paraprevotella is present in only one of the groups, if at all. With such sparse data, the estimates of complex models should be interpreted with caution.

Note that a similar plot could also be used to illustrate a possible confounding effect.

15.3.4 Positive abundances

It may sometimes be biologically relevant to analyze only the positive (non-zero) relative abundances of taxa. We thus briefly show here how to perform such analysis using the maaslin3() function from the maaslin3 package (Nickols et al. 2026). Purely for illustration purposes, we show here the analysis with an interaction term.

MaAsLin 3: Refining and extending generalized multivariable linear models for meta-omic association discovery. Nickols et al. (2026). Nat Methods 23:554–564. doi:10.1038/s41592-025-02923-9.

We proceed as in the previous sections. maaslin3() fits both a model for the positive abundances and a logistic regression model for the presence/absence of the taxa (the latter is used in Section 16.2). Here we extract the results of the former, fit_data_abundance, from the list object returned by maaslin3(). We also need to set median_comparison_abundance = FALSE in the function call as we want to estimate the differences of (positive) relative abundances and not make any compositional adjustments.

library(maaslin3)

# Run maaslin3 function.
obj_daa_pos_ia <- maaslin3(
    tse,
    output = "output",
    formula = ~ patient_status * cohort,
    median_comparison_abundance = FALSE,
    verbosity = "ERROR",
    plot_associations = FALSE,
    plot_summary_plot = FALSE
)

# Extract the results and calculate the q-values for each variable
res_daa_pos_ia <- obj_daa_pos_ia$fit_data_abundance$results |>
    filter(!is.na(pval_individual) & N_not_zero > 6) |>
    group_by(metadata) |>
    mutate(qval = p.adjust(pval_individual, method = "fdr")) |>
    ungroup() |>
    select(feature, name, coef, stderr,
        pval = pval_individual, qval, N_not_zero
    )

# The results for the interaction between patient_status and cohort (when
# comparing Cohort_3 to Cohort_1) for the taxa with the smallest p-values
res_daa_pos_ia |>
    filter(name == "patient_statusADHD:cohortCohort_3") |>
    arrange(pval) |>
    head() |>
    tt() |>
    format_tt(digits = 3, num_fmt = "significant_cell")
feature name coef stderr pval qval N_not_zero
Parabacteroides patient_statusADHD:cohortCohort_3 -3.44 0.766 0.00032 0.00683 23
Bacteroides patient_statusADHD:cohortCohort_3 2.46 0.771 0.00454 0.0485 26
[Clostridium]_innocuum_group patient_statusADHD:cohortCohort_3 -3.54 1.28 0.012 0.0768 25
Akkermansia patient_statusADHD:cohortCohort_3 -2.35 0.917 0.0182 0.0943 27
Alistipes patient_statusADHD:cohortCohort_3 -2.06 0.854 0.0253 0.108 27
uncultured_bacterium patient_statusADHD:cohortCohort_3 3.76 1.55 0.0593 0.173 10

The output is similar to the outputs in the previous sections. It, however, now includes also N_not_zero indicating the number of samples with positive (non-zero) relative abundances, that is, the sample size used in the analysis for each taxon.

The results are interpreted in a similar manner as in normal DAA (Section 15.3.3.4). For instance, the estimates (coef) indicate the log2-fold changes of positive relative abundances (as maaslin3() performs log2 transformation to the positive relative abundances).

15.3.5 Alternative options

15.3.5.1 Advanced compositionality adjustments

We have shown above (sections 15.3.3.1, 15.3.3.3, 15.3.3.4 and 15.3.4) how to perform DAA by analyzing relative abundances (TSS normalized counts) without any advanced adjustments for compositionality. As explained in Section 15.2, this choice was motivated by some recent benchmark studies that have employed only real data, especially the study by Gamboa-Tuz et al. (2025).

Commonly used compositional data analysis implementations are not advantageous in microbial differential abundance analyses benchmarked against biological ground truth. Gamboa-Tuz et al. (2025). bioRxiv 2025.02.13.638109. doi:10.1101/2025.02.13.638109.
The accuracy of absolute differential abundance analysis from relative count data. Roche et al. (2022). PLoS Comput Biol 18:e1010284. doi:10.1371/journal.pcbi.1010284.
A comprehensive evaluation of microbial differential abundance analysis methods: Current status and potential solutions. Yang et al. (2022). Microbiome 10:130. doi:10.1186/s40168-022-01320-0.

We note, however, that in some benchmark studies such simple versions of DAA have performed worse than some more advanced methods when compared on simulated data with strong compositional effects (e.g. Roche and Mukherjee (2022), Yang and Chen (2022)). We therefore give below some options for incorporating more advanced compositionality adjustments in DAA.

  • In Maaslin2, the default normalization method (TSS) can be replaced by TMM normalization (Robinson and Oshlack 2010) by including normalization = "TMM" in the Maaslin2() function.
  • In the analysis of positive abundances with maaslin3, the adjustment for compositional bias can be enabled by setting median_comparison_abundance = TRUE in maaslin3() function.
  • One can use DAA methods that are specifically designed to account for the compositionality of microbiome data. Such methods include, for instance,
A scaling normalization method for differential expression analysis of RNA-seq data. Robinson et al. (2010). Genome Biol 11:R25. doi:10.1186/gb-2010-11-3-r25.
Analysis of compositions of microbiomes with bias correction. Lin et al. (2020). Nat Commun 11:3514. doi:10.1038/s41467-020-17041-7.
Multigroup analysis of compositions of microbiomes with covariate adjustments and repeated measures. Lin et al. (2024). Nat Methods 21:83–91. doi:10.1038/s41592-023-02092-7.
LinDA: Linear models for differential abundance analysis of microbiome compositional data. Zhou et al. (2022). Genome Biol 23:95. doi:10.1186/s13059-022-02655-5.

15.3.5.2 A non-parametric alternative to MaAsLin2

As MaAsLin2 analyzes log transformed relative abundances, it needs to replace the zeros by some positive numbers before the transformation. If one wants to avoid this somewhat arbitrary imputation, we suggest performing DAA by using non/semi-parametric ordinal regression models (ORM). ORM can be seen as an extension of the familiar Wilcoxon test in the sense that it provides p-values similar to those of the Wilcoxon test in the simple two group comparison, but it can also incorporate covariates (and interaction terms) (Harrell 2001; Liu et al. 2017). ORM has also performed well in one benchmark study (Pelto et al. 2025).

Regression modeling strategies. Harrell (2001). Springer New York. doi:10.1007/978-1-4757-3462-1.
Modeling continuous response variables using ordinal regression. Liu et al. (2017). Stat Med 36:4316. doi:10.1002/SIM.7433.
Elementary methods provide more replicable results in microbial differential abundance analysis. Pelto et al. (2025). Brief Bioinform 26:bbaf130. doi:10.1093/BIB/BBAF130.

As there does not currently exist a good implementation of ORM for DAA one must use a custom function. Such a custom function with application examples is given in extra materials. We also note that, in contrast to the Maaslin2() function, the custom function provides confidence intervals and q-values (calculated for the variable of interest) automatically in its output.

15.3.5.3 Taxon set enrichment

DAA results can be interpreted further with taxon set enrichment analysis, which is similar to gene set enrichment analysis in transcriptomics. The TaxSEA package (Pham et al. 2025) tests whether the taxa in predefined sets, such as producers of specific metabolites or taxa linked to a disease in earlier studies, tend to have larger or smaller fold changes than other taxa. As input, it takes the fold changes from DAA. See the TaxSEA documentation for examples.

TaxSEA: Rapid interpretation of microbiome alterations using taxon set enrichment analysis and public databases. Pham et al. (2025). Brief Bioinform 26. doi:10.1093/bib/bbaf173.

15.4 Exercises

We use the peerj13075 dataset.

Solve the exercises in order, as each exercise continues from the previous one. Try to solve each exercise yourself before opening the solution.

Exercise 1: Reading DAA results

Goal: Interpret the results of DAA.

Imagine that you have compared the relative abundances of three taxa between a Treatment group and a Control group. Control was set as the reference level. The results are the following:

feature coef pval qval
Taxon A 1.0 0.001 0.01
Taxon B -2.0 0.004 0.03
Taxon C 1.5 0.020 0.12

Answer the following questions without writing any code. Section 15.3.3.1 will help you.

  1. Which taxa are statistically significant when the standard criterion q-value < 0.05 is used?

  2. For which taxa is the estimated abundance higher in the Treatment group?

  3. The log2-fold change (coef) of Taxon A is 1. What is the ratio of the geometric means of the relative abundances between the Treatment and Control groups? What is the ratio for Taxon B?

  4. The p-value of Taxon C is smaller than 0.05. Why do we use the q-value instead of the p-value to define statistical significance?

  5. Why is it not a good idea to run several DAA methods and report the one that gives the most significant taxa?

  1. Taxon A and Taxon B, because their q-values are smaller than 0.05.

  2. Taxon A and Taxon C, because their log2-fold changes are positive. The abundance is higher in the non-reference group (Treatment) when coef is positive. Note that the difference is not statistically significant for Taxon C.

  3. The ratio is 2 ^ coef. For Taxon A, it is \(2^{1} = 2\), that is, the geometric mean is two times higher in the Treatment group. For Taxon B, it is \(2^{-2} = 0.25\), that is, the geometric mean in the Treatment group is a quarter of that in the Control group.

  4. In DAA, one test is performed for each taxon. The more tests we perform, the more likely it is that some of them give small p-values just by chance. The q-value is a p-value adjusted for multiple testing, and it controls the false discovery rate (FDR).

  5. Different DAA methods often give very different results. If we try many methods, we are likely to find a method that supports our hypothesis just by chance (cherry-picking). The method should therefore be chosen before the analysis, for example, based on the recommendations in Section 15.2.

Exercise 2: Prepare the data

Goal: Prepare the data for DAA.

  1. Load the peerj13075 dataset from the mia package and store it in a variable called tse.

  2. Check how many samples there are in each group of the Diet column.

  3. Agglomerate the data to genus level with rank = "genus". (Note that the rank names of this dataset are written in lowercase.) Then add the prevalence and keep only the genera that are present in more than 50% of the samples. How many genera remain?

  4. Add an assay of relative abundances called "relabundance".

  5. Convert the Diet column to a factor and set Mixed as the reference level.

  6. Why is it important to know which group is the reference level?

Useful functions: data(), table(), mia::agglomerateByRank(), mia::addPrevalence(), mia::subsetBy(), mia::transformAssay(), factor()

library(mia)

# 1. Load the data
data("peerj13075", package = "mia")
tse <- peerj13075

# 2. Number of samples in each diet group
table(tse$Diet)
##  
##  Mixed   Veg 
##     28    30

# 3. Agglomerate to genus level and keep prevalent genera
tse <- agglomerateByRank(tse, rank = "genus")
tse <- addPrevalence(tse)
tse <- subsetBy(tse, rows = prevalence > 0.5)
nrow(tse)
##  [1] 37

# 4. Add relative abundances
tse <- transformAssay(tse, assay.type = "counts", method = "relabundance")

# 5. Set Mixed as the reference level
tse$Diet <- factor(tse$Diet, levels = c("Mixed", "Veg"))
  1. The log2-fold changes compare the non-reference group to the reference group. Here, a positive coef will mean that the abundance is higher in the Veg group than in the Mixed group, and a negative coef the opposite. If the reference level was Veg, the signs would be reversed.
Exercise 3: Compare two groups

Goal: Perform a simple two-group DAA with Maaslin2() and interpret its results.

  1. Run Maaslin2() to compare the genera between the diet groups. Give it the counts assay as input_data, colData(tse) converted to a data.frame as input_metadata, and fixed_effects = "Diet". Set output = "output", plot_heatmap = FALSE and plot_scatter = FALSE. Store the result in a variable called obj_daa.

  2. Extract the results table from obj_daa. Keep the columns feature, name, coef, stderr, pval and qval, as shown in Section 15.3.3.1, and store the table in a variable called res_daa.

  3. Show the six genera with the smallest p-values.

  4. How many genera have a q-value smaller than 0.05?

  5. What does the value DietVeg in the name column tell? How would you read a negative value in the coef column?

Useful functions: Maaslin2::Maaslin2(), colData(), as.data.frame(), dplyr::select(), dplyr::arrange(), head(), sum()

library(Maaslin2)
library(dplyr)

# 1. Run Maaslin2 with diet as the predictor variable
obj_daa <- Maaslin2(
    input_data = assay(tse, "counts"),
    input_metadata = colData(tse) |> as.data.frame(),
    fixed_effects = "Diet",
    output = "output",
    plot_heatmap = FALSE,
    plot_scatter = FALSE
)
# 2. Extract the results
res_daa <- obj_daa$results |>
    select(feature, name, coef, stderr, pval, qval)

# 3. Genera with the smallest p-values
res_daa |>
    arrange(pval) |>
    head()
##             feature    name   coef stderr      pval    qval
##  1    Vulgatibacter DietVeg -2.751 0.7572 0.0006089 0.01364
##  2 Desulfotomaculum DietVeg -2.133 0.6041 0.0008350 0.01364
##  3   Oceanobacillus DietVeg -3.592 1.0442 0.0011056 0.01364
##  4 Anaeromyxobacter DietVeg -2.395 0.7887 0.0036350 0.02713
##  5      Geobacillus DietVeg -3.095 1.0204 0.0036662 0.02713
##  6   Brevibacterium DietVeg  2.287 0.8588 0.0100783 0.06215

# 4. Number of genera with q-value < 0.05
sum(res_daa$qval < 0.05)
##  [1] 5
  1. DietVeg tells that the predictor variable is Diet and that the results compare the Veg group to the reference group Mixed. A negative log2-fold change means that the estimated relative abundance of the genus is lower in the Veg group than in the Mixed group. Whether the difference is statistically significant is seen from the q-value.
Exercise 4: Visualize the results

Goal: Visualize DAA results with strip plots, boxplots and a forest plot.

  1. Take the names of the three genera with the smallest p-values from res_daa. Plot their relative abundances in the diet groups with plotBoxplot(). Use assay.type = "relabundance", x = "Diet", facet.by = "rownames", scales = "free_y" and add.proportion = TRUE.

  2. Plot the log2-fold changes and their 95% confidence intervals for all genera with plotForest(). Calculate the intervals from the standard errors with the degrees of freedom of the model, as shown in Section 15.3.3.2. Order the genera by their log2-fold change.

  3. How can you see from the forest plot whether the abundance of a genus is higher or lower in the Veg group? How can you see whether the 95% confidence interval contains zero?

Useful functions: dplyr::arrange(), head(), dplyr::pull(), miaViz::plotBoxplot(), miaViz::plotForest()

library(miaViz)

# 1. Strip plots with boxplots for the three genera with the smallest p-values
top_genera <- res_daa |>
    arrange(pval) |>
    head(3) |>
    pull(feature)

plotBoxplot(
    tse,
    features = top_genera,
    assay.type = "relabundance",
    x = "Diet",
    facet.by = "rownames",
    scales = "free_y",
    add.proportion = TRUE
) +
    labs(y = "Relative abundance")


# 2. Forest plot of the log2-fold changes and their 95% CIs
# The model has two coefficients: the intercept and Diet
plotForest(
    res_daa,
    effect.var = "coef",
    err.var = "stderr",
    df = ncol(tse) - 2,
    id.var = "feature",
    order.by = "coef"
) +
    labs(x = "Coefficient")

  1. Each point shows the log2-fold change of one genus, and the line shows its 95% confidence interval. Points to the right of zero mean that the abundance is estimated to be higher in the Veg group, and points to the left of zero that it is lower. If the line crosses zero, the confidence interval contains zero, and the difference is not statistically significant at the 5% level before adjusting for multiple testing.
Exercise 5: Add a covariate

Goal: Include a covariate in DAA.

  1. Make a cross-table of the Diet and Geographical_location columns. Are the diet groups evenly distributed across the cities?

  2. Convert the Geographical_location column to a factor with the levels Pune, Ahmednagar and Nashik, in this order. Pune is then the reference level.

  3. Run Maaslin2() again, now with fixed_effects = c("Diet", "Geographical_location"). Store the result in a variable called obj_daa_cov.

  4. Extract the results and calculate the q-values separately for each variable, as shown in Section 15.3.3.3. Store the table in a variable called res_daa_cov.

  5. Show the six genera with the smallest p-values for DietVeg.

  6. Why can it be important to include the city as a covariate? Why are the q-values calculated separately for each variable?

Useful functions: table(), factor(), Maaslin2::Maaslin2(), dplyr::group_by(), dplyr::mutate(), stats::p.adjust(), dplyr::ungroup(), dplyr::select(), dplyr::filter(), dplyr::arrange(), head()

# 1. Cross-table of diet and city
table(tse$Diet, tse$Geographical_location)
##         
##          Ahmednagar Nashik Pune
##    Mixed          4     10   14
##    Veg            7      1   22

# 2. Set Pune as the reference level
tse$Geographical_location <- factor(
    tse$Geographical_location,
    levels = c("Pune", "Ahmednagar", "Nashik")
)
  1. In the cross-table, the rows are the diet groups and the columns are the cities, and each cell is the number of samples with that diet from that city. The groups are evenly distributed if the proportions of Mixed and Veg samples are similar in each city (column).
# 3. Run Maaslin2 with diet and city as the predictor variables
obj_daa_cov <- Maaslin2(
    input_data = assay(tse, "counts"),
    input_metadata = colData(tse) |> as.data.frame(),
    fixed_effects = c("Diet", "Geographical_location"),
    output = "output",
    plot_heatmap = FALSE,
    plot_scatter = FALSE
)
# 4. Extract the results and calculate the q-values for each variable
res_daa_cov <- obj_daa_cov$results |>
    group_by(metadata) |>
    mutate(qval = p.adjust(pval, method = "fdr")) |>
    ungroup() |>
    select(feature, name, coef, pval, qval)

# 5. Genera with the smallest p-values for diet
res_daa_cov |>
    filter(name == "DietVeg") |>
    arrange(pval) |>
    head()
##  # A tibble: 6 × 5
##    feature          name     coef     pval   qval
##    <chr>            <chr>   <dbl>    <dbl>  <dbl>
##  1 Vulgatibacter    DietVeg -3.04 0.000588 0.0218
##  2 Anaeromyxobacter DietVeg -2.53 0.00520  0.0682
##  3 Oceanobacillus   DietVeg -3.26 0.00644  0.0682
##  4 Desulfotomaculum DietVeg -1.84 0.00737  0.0682
##  5 Brevibacterium   DietVeg  1.64 0.0851   0.527 
##  6 Geobacillus      DietVeg -1.59 0.0979   0.527
  1. If the diet groups are not evenly distributed across the cities, and the city itself is associated with the skin microbiome, the city can act as a confounder. Differences that we see between the diet groups could then be partly due to differences between the cities. With the city as a covariate, the diet effect is estimated while the city is held constant. You can compare the results to those of Exercise 3: if the estimates and q-values for diet change a lot, the covariate affects the diet results.

Maaslin2() adjusts the p-values over all variables in the model. We are mainly interested in diet, so we adjust the p-values only over the tests for diet. This way, the tests for the city do not affect the q-values of diet.

Back to top