13  Community similarity

Beta diversity quantifies the dissimilarity between communities (multiple samples), as opposed to alpha diversity, which focuses on variation within a community (one sample). In microbiome research, commonly used metrics of beta diversity include:

An ordination of the upland forest communities of southern wisconsin. Bray et al. (1957). Ecol Monogr 27:325–349. doi:10.2307/1942268.
The distribution of the flora in the alpine zone. Jaccard (1912). New Phytol 11:37–50. doi:10.1111/j.1469-8137.1912.tb05611.x.
The statistical analysis of compositional data. Aitchison (1986). Chapman & Hall.
UniFrac: A new phylogenetic method for comparing microbial communities. Lozupone et al. (2005). Appl Environ Microbiol 71:8228–8235. doi:10.1128/aem.71.12.8228-8235.2005.

Notably, only some of these measures are actual distances, as this is a mathematical concept whose definition is not satisfied by certain ecological measures, such as the Bray-Curtis index. Therefore, the terms dissimilarity and beta diversity are preferred.

The table below lists commonly used combinations of assay type and beta diversity metric.

Method description Assay type Beta diversity metric
Quantitative profiling Absolute counts Bray-Curtis
Relative profiling Relative abundances Bray-Curtis
Aitchison distance Absolute counts Aitchison
Aitchison distance clr Euclidean
Robust Aitchison distance rclr Euclidean
Presence/Absence similarity Relative abundances Jaccard
Presence/Absence similarity Absolute counts Jaccard
Phylogenetic distance Rarefied counts UniFrac
Dissimilarity or distance?

The terms dissimilarity and distance are often used interchangeably, but they have distinct meanings.

All distance metrics are also dissimilarity metrics, but not all dissimilarity metrics are distance metrics.

Dissimilarity is a broader concept that measures how different two samples are. Dissimilarity metrics do not necessarily fulfill the requirements of distances. For instance, Bray-Curtis is a dissimilarity metric: it is symmetric, but it does not satisfy the triangle inequality.

Distance metrics, for example Euclidean distance, measure how far apart two samples are. A distance is always symmetric, meaning that the distance from A to B equals the distance from B to A. Moreover, it satisfies the triangle inequality: the direct distance between two points is never longer than a detour through a third point.

In practice, beta diversity is usually represented as a dist object. Such an object is a triangular matrix where the distance between each pair of samples is encoded by a specific cell (Figure 13.1). This distance matrix can then undergo ordination, which is an important ecological tool to reduce the dimensionality of data for a more efficient analysis and visualization. Ordination techniques aim to capture as much essential information from the data as possible and turn it into a lower dimensional representation. While dimension reduction inevitably results in some information loss, commonly utilized ordination techniques aim to optimally preserve meaningful patterns of sample similarity, with the definition of “optimal” varying by method.

Three panels from left to right. Panel 1 is a tile grid of six samples by five taxa shaded by abundance; panel 2 is a triangular matrix of pairwise dissimilarities with values printed in the cells; panel 3 is a scatter plot of the six samples on PCoA 1 and PCoA 2, colored by Group 1 and Group 2.
Figure 13.1: From abundances to an ordination. Beta diversity compares the abundance profiles of each pair of samples (1) and stores the dissimilarities, here Bray-Curtis, in a triangular matrix (2). Ordination, here PCoA, places the samples in a low-dimensional space so that similar samples lie close to each other (3). Toy data.

Based on the type of algorithm, ordination methods in microbiome research can be generally divided into two categories:

The former includes Principal Coordinate Analysis (PCoA) (GOWER 1966) and Principal Component Analysis (PCA) (Pearson 1901; Hotelling 1933), whereas the latter is mainly represented by distance-based redundancy analysis (dbRDA) (Legendre and Anderson 1999). First, we will discuss unsupervised ordination methods and then proceed to supervised ones.

Some distance properties of latent root and vector methods used in multivariate analysis. GOWER (1966). Biometrika 53:325–338. doi:10.1093/biomet/53.3-4.325.
Distance-based redundancy analysis: Testing multispecies responses in multifactorial ecological experiments. Legendre et al. (1999). Ecol Monogr 69:1–24. doi:10.1890/0012-9615(1999)069[0001:dbratm]2.0.co;2.

Let us now prepare some demonstration data for the practical examples.

# Load mia and import sample dataset
library(mia)
data("GlobalPatterns", package = "mia")
tse <- GlobalPatterns

# Beta diversity metrics like Bray-Curtis are often
# applied to relabundances
tse <- transformAssay(
    tse,
    assay.type = "counts", method = "relabundance"
)

# Other metrics like Aitchison to clr-transformed data
tse <- transformAssay(
    tse,
    assay.type = "counts", method = "clr", pseudocount = 0.5
)

# Add group information Feces yes/no
tse$Group <- ifelse(tse$SampleType == "Feces", "Fecal", "Non-fecal")
Common mistake in Jaccard index

The standard Jaccard index is calculated based on a presence/absence table. However, a common mistake is using the quantitative version instead. By default, the function vegdist() from the vegan package (Oksanen et al. 2020) computes the abundance-weighted Jaccard dissimilarity, which is similar to Bray-Curtis. This can be controlled using the binary parameter.

When calculating the Jaccard index with mia’s functions (including getPERMANOVA() and addRDA()), it defaults to standard presence/absence version:

tse <- addDissimilarity(tse, assay.type = "counts", method = "jaccard")

… or if you want to be more explicit, you can transform the data to presence/absence scale and then calculate the Jaccard index:

tse <- transformAssay(tse, method = "pa")
tse <- addDissimilarity(tse, assay.type = "pa", method = "jaccard")
vegan: Community ecology package. Oksanen et al. (2020). R package version 2.5-7. https://CRAN.R-project.org/package=vegan.

13.1 Dissimilarity

Perhaps the simplest way to analyze dissimilarity is to calculate a dissimilarity matrix. In this matrix, each sample is compared with every other sample based on the specified dissimilarity method. The result includes a single number for each sample-pair. This number is an indication of how similar or dissimilar the microbial communities are.

One can calculate a dissimilarity matrix with *Dissimilarity() functions. Here we use addDissimilarity() that adds the matrix to the metadata slot. We calculate UniFrac dissimilarity that takes into account phylogenetic distances.

tse <- addDissimilarity(tse, assay.type = "counts", method = "unifrac")

The dissimilarities can then be visualized with a heatmap (Figure 13.2). Here we also add sample information to the plot.

library(miaViz)

# Wrap long sample type names
tse_plot <- tse
tse_plot[["SampleType"]] <- factor(
    tse_plot[["SampleType"]],
    labels = gsub(" \\(", "\n(", levels(tse_plot[["SampleType"]]))
)

plotDissimilarity(tse_plot, name = "unifrac", col.var = "SampleType")
Square heatmap with the samples on both axes, where cell color shows the UniFrac dissimilarity of each sample pair. Samples are split into blocks by sample type, and samples of the same type tend to be the most similar to each other.
Figure 13.2: Heatmap of pairwise UniFrac dissimilarities between the GlobalPatterns samples. Samples are ordered by seriation and split by sample type.

From the heatmap, we can observe that samples within the same sample type are the most similar to each other. plotDissimilarity() orders the samples by seriation of the dissimilarities (by default, their angular order in a multidimensional scaling; see the sort.method argument) and splits them by sample type.

13.2 Divergence

The divergence measure refers to a difference in community composition between the given sample(s) and a reference sample. This can be evaluated with addDivergence(). The reference and the dissimilarity measure can be specified with the reference and method arguments, respectively. The result is stored in the divergence column of colData.

tse <- addDivergence(
    tse,
    assay.type = "counts",
    reference = "median"
)
tse$divergence |> head()
##  [1] 0.9891 0.9912 0.9870 0.9954 0.9964 0.9901

13.3 Group comparison (PERMANOVA)

PERMANOVA (Permutational Multivariate Analysis of Variance) (Anderson 2001) can be seen as a non-parametric, multivariate extension of ANOVA (Analysis of Variance). It is used to compare groups in multivariate data and to assess whether a variable explains differences in the data. PERMANOVA first calculates the dissimilarities between samples, then compares the centroids (multivariate means) of each group to determine if they differ significantly.

A new method for non-parametric multivariate analysis of variance. Anderson (2001). Austral Ecol 26:32–46. doi:10.1111/j.1442-9993.2001.01070.pp.x.

PERMANOVA determines statistical significance by permuting (randomly shuffling) group labels many times (Figure 13.3). By comparing the observed test statistic to those from the permutations, it assesses if the observed group differences are likely due to chance, without relying on parametric assumptions.

Two panels. Left: a scatter plot of two colored groups of toy samples on two PCoA axes, with a black cross at each group centroid and faint lines from every sample to its centroid. Right: a gray histogram of pseudo-F values from permutations, with a vertical line marking the observed pseudo-F and a label giving its value and the p-value.
Figure 13.3: The idea of PERMANOVA. The test statistic (pseudo-F) compares the distances between group centroids (crosses) to the spread of samples around their own centroid (left). Permuting the group labels gives the distribution of pseudo-F when groups do not differ; the p-value is the proportion of permutations with a pseudo-F at least as large as the observed one (right). Toy data.

Since PERMANOVA relies on comparing centroids, it assumes that the groups have similar within-group variation, i.e., homogeneous multivariate dispersions (Anderson 2006). If this assumption isn’t met, a significant result may reflect differences in dispersion rather than in centroids, so it’s important to check this assumption before drawing conclusions.

set.seed(123)
res <- getPERMANOVA(
    tse,
    assay.type = "relabundance",
    formula = x ~ SampleType
)
res
##  $permanova
##  Permutation test for adonis under reduced model
##  Marginal effects of terms
##  Permutation: free
##  Number of permutations: 999
##  
##  adonis2(formula = formula, data = data, by = by, na.action = na.action)
##             Df SumOfSqs    R2    F Pr(>F)    
##  SampleType  8     8.25 0.731 5.78  0.001 ***
##  Residual   17     3.03 0.269                
##  Total      25    11.28 1.000                
##  ---
##  Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##  
##  $homogeneity
##             Df Sum Sq Mean Sq     F N.Perm Pr(>F) Total variance
##  SampleType  8 0.4997 0.06246 5.807    999  0.002         0.6825
##             Explained variance
##  SampleType             0.7321

The output includes both PERMANOVA and homogeneity results. When PERMANOVA results are significant, we check the homogeneity results to ensure reliability. The homogeneity test measures group dispersions which are the average distances between samples and their group centroids. A non-significant homogeneity result indicates that groups have similar within-group variability, i.e., the group dispersions are homogeneous, which is desired in PERMANOVA.

In our case, PERMANOVA results are significant; however, the homogeneity test shows a significant difference in group dispersion. This suggests that the observed differences may be influenced by unequal variability among groups, and therefore, caution is needed when interpreting the PERMANOVA result. The effect of SampleType on microbial composition may be confounded by dispersion differences.

PERMANOVA and distance-based redundancy analysis (dbRDA) are closely related, and they often give similar results. However, their assumptions are different; while PERMANOVA is a non-parametric method, dbRDA assumes linear relationships in the dissimilarity matrix. In addition, dbRDA can be used more broadly as the ordination can also be visualized.

13.4 Unsupervised ordination

Unsupervised ordination methods analyze variation in the data without additional information on covariates or other supervision of the model. Among the different approaches, Multidimensional Scaling (MDS) and non-metric MDS (NMDS) (Kruskal 1964) can be regarded as the standard. Metric MDS is also known as Principal Coordinate Analysis (PCoA). For this demonstration, we will analyze beta diversity in GlobalPatterns (Caporaso et al. 2011) (Section D.1), and observe the variation between stool samples and samples of differing origin.

Multidimensional scaling by optimizing goodness of fit to a nonmetric hypothesis. Kruskal (1964). Psychometrika 29:1–27. doi:10.1007/bf02289565.
Global patterns of 16S rRNA diversity at a depth of millions of sequences per sample. Caporaso et al. (2011). Proc Natl Acad Sci USA 108:4516–4522. doi:10.1073/pnas.1000080107.

13.4.1 Comparing communities

A typical comparison of community compositions starts with calculating the dissimilarities between the samples, for example with the Bray-Curtis index on the relative abundances. The samples are then ordinated with MDS, and the groups are compared visually in a 2D ordination plot. The addMDS() and addNMDS() functions calculate the dissimilarities and the ordination in one step.

The choice of the dissimilarity metric is important. It is selected with the method argument of addMDS() and addNMDS(). All standard metrics are available; see ?getDissimilarity for the full list. The results are stored in the reducedDim slot of the TreeSE.

# Load package to plot ordinations
library(miaViz)

# Run PCoA on relabundance assay with Bray-Curtis distances
tse <- addMDS(
    tse,
    method = "bray",
    assay.type = "relabundance",
    name = "MDS_bray"
)

Sample dissimilarity can be visualized on a lower-dimensional display (typically 2D) using the plotOrdination() function from the miaViz package. This also provides tools to incorporate additional information encoded by color, shape, size and other aesthetics. Can you find any difference between the groups in Figure 13.4?

# Create ggplot object with explained variance in the axis labels
p <- plotOrdination(
    tse, "MDS_bray",
    colour.by = "Group",
    add.expl.var = TRUE
)

p
Scatter plot of the samples on the first two MDS axes, with the percentage of variance explained in the axis labels. Points are colored by whether the sample is fecal or not.
Figure 13.4: MDS (PCoA) plot based on the Bray-Curtis dissimilarities of relative abundances in the GlobalPatterns dataset. Points are colored by group (fecal or non-fecal sample), and axis labels show the proportion of variance explained.

To further visualize the differences between the groups, we can add boxplots that display the distribution of the scores with respect to each group (Figure 13.5).

library(ggExtra)

# Legend below, so that it is not between the plot and the boxplots
p <- p + theme(legend.position = "bottom")
p <- ggMarginal(p, type = "boxplot", groupFill = TRUE)
p
The same MDS scatter plot colored by fecal versus non-fecal samples, with boxplots along the top and right margins comparing the two groups' scores on the horizontal and vertical axes.
Figure 13.5: Bray-Curtis MDS plot of the GlobalPatterns dataset with marginal boxplots showing the distribution of the scores on each axis for fecal and non-fecal samples.

A few combinations of beta diversity metrics and assay types are typically used. For instance, Bray-Curtis dissimilarity and Euclidean distance are often applied to the relative abundance and the clr assays, respectively. Besides beta diversity metric and assay type, the PCoA algorithm is also a variable that should be considered. Below, we show how the choice of these three factors can affect the resulting lower-dimensional data.

# Run NMDS on relabundance assay with Bray-Curtis distances
tse <- addNMDS(
    tse,
    method = "bray",
    assay.type = "relabundance",
    name = "NMDS_bray"
)

# Run MDS on clr assay with Aitchison distances
tse <- addMDS(
    tse,
    method = "euclidean",
    assay.type = "clr",
    name = "MDS_aitchison"
)

# Run NMDS on clr assay with Euclidean distances
tse <- addNMDS(
    tse,
    method = "euclidean",
    assay.type = "clr",
    name = "NMDS_aitchison"
)

Multiple ordination plots are combined into a multi-panel plot (Figure 13.6) with the patchwork package, so that different methods can be compared to find similarities between them or select the most suitable one to visualize beta diversity in the light of the research question.

Show the plotting code
# Load package for multi-panel plotting
library(patchwork)

# Generate plots for all 4 reducedDims
p1 <- plotOrdination(
    tse, "MDS_bray",
    colour.by = "Group", add.expl.var = TRUE
) +
    labs(title = "MDS, Bray-Curtis")
p2 <- plotOrdination(
    tse, "MDS_aitchison",
    colour.by = "Group", add.expl.var = TRUE
) +
    labs(title = "MDS, Aitchison")
p3 <- plotOrdination(tse, "NMDS_bray", colour.by = "Group") +
    labs(title = "NMDS, Bray-Curtis")
p4 <- plotOrdination(tse, "NMDS_aitchison", colour.by = "Group") +
    labs(title = "NMDS, Aitchison")

# Generate multi-panel plot
wrap_plots(p1, p2, p3, p4) +
    plot_layout(guides = "collect") +
    plot_annotation(tag_levels = "A")
Grid of four scatter plots: MDS and NMDS ordinations with Bray-Curtis and with Aitchison distances. In every panel, points are colored by fecal or non-fecal sample, with a shared legend.
Figure 13.6: Comparison of MDS and NMDS plots based on the Bray-Curtis or Aitchison distances on the GlobalPatterns dataset: (A) MDS, Bray-Curtis; (B) MDS, Aitchison; (C) NMDS, Bray-Curtis; (D) NMDS, Aitchison. Points are colored by group (fecal or non-fecal sample).

The UniFrac method is a special case, as it requires the phylogenetic tree of the features. addMDS() uses the tree in rowTree(tse) by default (Figure 13.7).

tse <- addMDS(
    tse,
    method = "unifrac",
    name = "MDS_unifrac",
    assay.type = "counts"
)

plotOrdination(tse, "MDS_unifrac", colour.by = "Group", add.expl.var = TRUE)
Scatter plot of the samples on the first two MDS axes based on UniFrac distances, with points colored by fecal or non-fecal sample.
Figure 13.7: UniFrac distances scaled by MDS of the GlobalPatterns dataset. Points are colored by group (fecal or non-fecal sample).

13.4.2 Rarefaction

Background on rarefaction (Sanders 1968; Hurlbert 1971) is provided in Section 10.5. For rarefaction in beta diversity analysis, see Schloss (2024).

Marine benthic diversity: A comparative study. Sanders (1968). The American Naturalist 102:243–282. doi:10.1086/282541.
The nonconcept of species diversity: A critique and alternative parameters. Hurlbert (1971). Ecology 52:577–586. doi:10.2307/1934145.
Rarefaction is currently the best approach to control for uneven sequencing effort in amplicon sequence analyses. Schloss (2024). mSphere 9:e00354–23. doi:10.1128/msphere.00354-23.

Let us first convert the count assay to centered log ratio (clr) assay and calculate MDS with Aitchison distance without rarefaction:

# Centered log-ratio transformation to properly apply Aitchison distance
tse <- transformAssay(
    tse,
    assay.type = "counts",
    method = "clr",
    pseudocount = 1,
    name = "clr_pc1"
)

# Run MDS on clr assay with Aitchison distance
tse <- addMDS(
    tse,
    method = "euclidean",
    assay.type = "clr_pc1",
    name = "MDS_aitchison_pc1"
)

Then let’s do the same with rarefaction:

# Define custom transformation function
clr <- function(x) {
    vegan::decostand(x, method = "clr", pseudocount = 1)
}

# Run transformation after rarefactions before calculating the beta diversity
tse <- addMDS(
    tse,
    assay.type = "counts",
    method = "euclidean",
    niter = 10, # Number of iterations
    sample = min(colSums(assay(tse, "counts"))), # Rarefaction depth
    transf = clr, # Applied transformation
    name = "MDS_aitchison_rarefied"
)

Now we are ready to plot the non-rarefied and rarefied MDS plots side-by-side (Figure 13.8).

# Generate plots for non-rarefied and rarefied Aitchison distances scaled by MDS
p1 <- plotOrdination(tse, "MDS_aitchison_pc1", colour.by = "SampleType") +
    labs(title = "Without rarefaction", colour = "Sample type")
p2 <- plotOrdination(tse, "MDS_aitchison_rarefied", colour.by = "SampleType") +
    labs(title = "With rarefaction", colour = "Sample type")

# Generate multi-panel plot
wrap_plots(p1, p2) +
    plot_layout(guides = "collect")
Two scatter plots side by side, showing Aitchison MDS ordinations of the samples without rarefaction (left) and with rarefaction (right). Points are colored by sample type, with a shared legend.
Figure 13.8: MDS plots based on Aitchison distances of the GlobalPatterns dataset without rarefaction (left) and with rarefaction (right). Points are colored by sample type.

The same can be done more compactly with lapply(), which creates one plot for each ordination. This is convenient when comparing more than two ordinations, as only the vector of names needs to be extended:

# One plot for each ordination, combined into a multi-panel plot
plots <- lapply(
    c("MDS_aitchison_pc1", "MDS_aitchison_rarefied"),
    function(name) plotOrdination(tse, name, colour.by = "SampleType")
)
wrap_plots(plots) +
    plot_layout(guides = "collect")
Note

Sometimes features are filtered before ordination. Features that hardly vary carry little information and mainly add noise. With addMDS(), the ntop argument keeps only the given number of features with the highest variance. By default, all features are used.

When rarefaction is not done, the getDissimilarity() utilizes vegan::vegdist() function while in rarefaction vegan::avgdist() is applied. The argument sample is set to the smallest metagenomic reads count across all samples. This ensures that no sample will be removed during the rarefaction process.

The argument niter sets the number of rarefaction rounds. By default (niter = NULL), no rarefaction is applied; here 10 iterations is often sufficient for beta diversity calculations. To use transformations after the rarefaction of the samples and before the beta diversity calculation, we can use the argument transf.

The mia package’s addAlpha() and getDissimilarity() functions support rarefaction in alpha and beta diversity calculations. Additionally, the rarefyAssay() function allows random subsampling of a given assay within a TreeSummarizedExperiment dataset.

13.4.3 Other methods

Other dimension reduction methods, such as PCA (Pearson 1901; Hotelling 1933) and robust PCA, are also available. PCA is calculated with addPCA() from mia and shown in Figure 13.9.

On lines and planes of closest fit to systems of points in space. Pearson (1901). The London, Edinburgh, and Dublin Philosophical Magazine and Journal of Science 2:559–572. doi:10.1080/14786440109462720.
Analysis of a complex of statistical variables into principal components. Hotelling (1933). Journal of Educational Psychology 24:417–441. doi:10.1037/h0071325.
scater: Pre-processing, quality control, normalisation and visualisation of single-cell RNA-seq data in R. McCarthy et al. (2017). Bioinformatics 33:1179–1186. doi:10.1093/bioinformatics/btw777.

Nonlinear methods such as t-distributed stochastic neighbor embedding (t-SNE) (van der Maaten and Hinton 2008) and Uniform Manifold Approximation and Projection (UMAP) (McInnes et al. 2018) are available in the scater package (McCarthy et al. 2017) (see the list at the end of this chapter). They are rarely used for microbiome data, and we do not show examples here: the result depends strongly on the tuning parameters and the random seed, and the distances between groups of samples in the plot are not interpretable.

tse <- addPCA(
    tse,
    name = "PCA",
    assay.type = "clr",
    ncomponents = 10
)

# Visualize the result
plotOrdination(tse, "PCA", colour.by = "Group", add.expl.var = TRUE)
Scatter plot of the samples on the first two principal components, with the percentage of variance explained in the axis labels. Points are colored by fecal or non-fecal sample.
Figure 13.9: PCA plot of the clr-transformed abundances in the GlobalPatterns dataset containing samples from different sources. Points are colored by group (fecal or non-fecal sample), and axis labels show the proportion of variance explained.

A scree plot shows how much variance each component explains (Figure 13.10). It helps to decide how many components are worth interpreting: typically those before the curve levels off.

plotScree(tse, "PCA")
Line plot with the principal components 1 to 10 on the x-axis and their eigenvalues on the y-axis. The eigenvalues drop steeply over the first three components and then level off.
Figure 13.10: Scree plot of the PCA of the clr-transformed GlobalPatterns data. Each point is the eigenvalue (explained variance) of one principal component.

Robust Aitchison PCA (RPCA) (Martino et al. 2019) is a PCA for compositional data with many zeros. It uses the robust clr (rclr) transformation, which is calculated from the non-zero values only, and treats the zeros as missing values that are filled in by matrix completion. Unlike the clr transformation, it does not need a pseudocount. RPCA is calculated with addRPCA() (Figure 13.11). The same method is extended to multiple omics in Joint-RPCA (Chapter 21).

A novel sparse compositional technique reveals microbial perturbations. Martino et al. (2019). mSystems 4:e00016–19. doi:10.1128/mSystems.00016-19.
# rclr without imputation: RPCA itself handles the zeros
tse <- transformAssay(
    tse,
    assay.type = "counts",
    method = "rclr",
    impute = FALSE
)
tse <- addRPCA(tse, assay.type = "rclr", name = "RPCA")

plotOrdination(tse, "RPCA", colour.by = "Group", add.expl.var = TRUE)
Scatter plot of the samples on the first two RPCA components, with the percentage of variance explained in the axis labels. Points are colored by fecal or non-fecal sample.
Figure 13.11: Robust Aitchison PCA (RPCA) of the GlobalPatterns dataset. Points are colored by group (fecal or non-fecal sample), and axis labels show the proportion of variance explained.

13.4.4 Explained variance

The percentage of explained variance is typically shown in PCA ordination plots. This quantifies the proportion of overall variance in the data that is captured by the PCA axes, or how well the ordination axes reflect the original distances.

Sometimes a similar measure is shown for MDS/PCoA. However, the interpretation is generally different, hence we do not recommend using it. PCA is a special case of PCoA with Euclidean distances. With non-Euclidean dissimilarities PCoA uses a trick where the pointwise dissimilarities are first cast into similarities in a Euclidean space (with some information loss i.e., stress) and then projected to the maximal variance axes. In this case, the maximal variance axes do not directly reflect the correspondence of the projected distances and original distances, as they do for PCA.

In typical use cases, we would like to know how well the ordination reflects the original similarity structures; then the quantity of interest is the so-called “stress” function, which measures the difference in pairwise similarities between the data points in the original (high-dimensional) vs. projected (low-dimensional) space.

Hence, we propose that for PCoA and other ordination methods, users would report relative stress, which varies within the unit interval and is better if smaller. This can be calculated as shown below.

# Quantify dissimilarities in the original feature space
d0 <- as.matrix(getDissimilarity(t(assay(tse, "relabundance")), "bray"))

# PCoA Ordination
tse <- addMDS(
    tse,
    name = "PCoA",
    method = "bray",
    assay.type = "relabundance"
)

# Quantify dissimilarities in the ordination space
dp <- as.matrix(dist(reducedDim(tse, "PCoA")))

# Calculate stress i.e. relative difference
# in the original and projected dissimilarities
stress <- sum((dp - d0)^2) / sum(d0^2)

A Shepard plot visualizes the original versus the ordinated dissimilarity between the observations (Figure 13.12).

Show the plotting code
ord <- order(as.vector(d0))
df <- data.frame(
    d0 = as.vector(d0)[ord],
    dmds = as.vector(dp)[ord]
)

ggplot(df, aes(x = d0, y = dmds)) +
    geom_point(alpha = 0.3) +
    labs(
        x = "Original distance",
        y = "MDS distance",
        subtitle = paste("Stress:", round(stress, 2))
    )
Scatter plot with the original Bray-Curtis dissimilarity on the x-axis and the distance in the PCoA space on the y-axis, one point per sample pair. The subtitle gives the stress value.
Figure 13.12: Shepard plot comparing the original Bray-Curtis dissimilarities (x-axis) with the distances in the PCoA space (y-axis) for the GlobalPatterns samples. The relative stress is shown in the subtitle.

13.5 Constrained ordination

dbRDA is a supervised counterpart of PCoA. It maximizes the variance with respect to the covariates provided by the user. This can be used to quantify associations between each covariate and community composition (beta diversity). The table below summarizes the relations between the supervised and unsupervised ordination methods.

supervised ordination unsupervised ordination
Euclidean distance RDA PCA
non-Euclidean distance dbRDA PCoA/MDS, NMDS

In summary, the “dbRDA” is the more general method that allows a wider variety of dissimilarity, or beta diversity, indices. This method is available via mia::getRDA(), which calls vegan::dbrda(). By default, this uses Euclidean distances, which is equivalent to the ordinary RDA. However, the dbRDA method (mia::getRDA()) allows the use of other dissimilarity indices as well.

Let us next demonstrate dbRDA with the enterotype dataset (Arumugam et al. 2011) (Section D.2). Here samples correspond to patients. The colData lists the clinical status of each patient and a few covariates such as gender and age.

Enterotypes of the human gut microbiome. Arumugam et al. (2011). Nature 473:174–180. doi:10.1038/nature09944.
# Load data
data("enterotype", package = "mia")
tse2 <- enterotype
rownames(tse2)[rownames(tse2) == "-1"] <- "Unassigned"

# Apply relative transform
tse2 <- transformAssay(tse2, method = "relabundance")

13.5.1 Redundancy analysis

dbRDA can be performed with the addRDA() function. In addition to the arguments previously defined for unsupervised ordination, this function takes a formula to control for variables and an action to treat missing values. Along with clinical status, which is the main outcome, we control for gender and age, and exclude observations where one of these variables is missing.

# Perform RDA
set.seed(123)
tse2 <- addRDA(
    tse2,
    assay.type = "relabundance",
    formula = assay ~ ClinicalStatus + Gender + Age,
    distance = "bray",
    na.action = na.exclude
)

# Store results of PERMANOVA test
rda_info <- attr(reducedDim(tse2, "RDA"), "significance")

The importance of each variable on the similarity between samples (i.e., loadings) can be assessed from the results of PERMANOVA, automatically provided by the addRDA() function. It first performs dbRDA and then applies permutational tests to its results.

As previously described, PERMANOVA is a widely used non-parametric multivariate method that aims to estimate the actual statistical significance of differences in the observed community composition between groups of samples (here, the five clinical status groups). PERMANOVA tests the hypothesis that the centroids of the community are equivalent between the compared groups. A p-value smaller than the significance threshold indicates that the groups have a different community composition, provided that the group dispersions are homogeneous (see below).

This method is implemented with the adonis2 function from the vegan package.

From the results table below, we see that both clinical status and age explain more than 10% of the variance, however, only age has statistical significance.

rda_info$permanova |>
    knitr::kable()
Df SumOfSqs F Pr(>F) Total variance Explained variance
Model 6 1.1157 1.940 0.042 3.991 0.2795
ClinicalStatus 4 0.5837 1.522 0.126 3.991 0.1463
Gender 1 0.1679 1.751 0.122 3.991 0.0421
Age 1 0.5245 5.471 0.001 3.991 0.1314
Residual 30 2.8757 NA NA 3.991 0.7205

Next, we proceed to visualize the weight and significance of each variable on the similarity between samples with an RDA plot, which can be generated with the plotRDA() function from the miaViz package (Figure 13.13).

# Load packages for plotting function
library(miaViz)

# Generate RDA plot colored by clinical status
plotRDA(tse2, "RDA", colour.by = "ClinicalStatus") +
    labs(colour = "Clinical status")
Scatter plot of the samples on the first two dbRDA axes, with points colored by clinical status. Arrows from the origin show the directions of the covariates clinical status, gender and age.
Figure 13.13: dbRDA plot of the enterotype dataset with samples colored by clinical status. Arrows show the contributions of the covariates clinical status, gender and age.

From above, we can see that only age significantly describes differences between the microbial profiles of different samples. Such visual approach complements the previous results obtained with PERMANOVA.

Speed up calculations

Calculating dissimilarities between samples is a computationally demanding task, which can make methods like dbRDA or PCoA time-consuming with large datasets. To speed up calculations, consider using functions that support parallel processing instead of the default vegan package options. Packages like parallelDist can significantly improve performance on systems with multiple available cores.

In *Dissimilarity() functions, you can specify the utilized dissimilarity function with dis.fun argument.

tse <- addDissimilarity(
    tse,
    assay.type = "relabundance",
    method = "bray",
    dis.fun = parallelDist::parallelDist
)

This same approach can also be used in PCoA.

tse <- addMDS(
    tse,
    assay.type = "relabundance",
    method = "bray",
    dis.fun = parallelDist::parallelDist
)

With dbRDA, you can use precomputed dissimilarity matrices, allowing the method to bypass the dissimilarity estimation step. This enhances efficiency and speeds up the analysis.

tse <- addRDA(
    tse,
    dis.name = "bray",
    formula = assay ~ ClinicalStatus + Gender + Age,
    na.action = na.exclude
)

13.5.2 dbRDA loadings

Let us visualize the model coefficients or loadings for species that exhibit the largest differences between the groups. This gives some insights into how the groups tend to differ from each other in terms of community composition (Figure 13.14).

plotLoadings(tse2, "RDA", ncomponents = 2, n = 20)
Two panels of horizontal bar charts, one for each of the first two dbRDA components, with the 20 taxa on the y-axis and their loadings on the x-axis.
Figure 13.14: Loadings of the 20 taxa with the largest contributions to the first two dbRDA components in the enterotype dataset.

In the example above, the largest contributions to the first dbRDA component can be attributed to Bifidobacterium and Unassigned.

13.5.3 Homogeneity check

It is important to note that the application of PERMANOVA assumes homogeneous group dispersions (variances). This can be tested with the PERMDISP2 method (Anderson 2006) by using the same assay and distance method as in PERMANOVA.

Distance-based tests for homogeneity of multivariate dispersions. Anderson (2006). Biometrics 62:245–253. doi:10.1111/j.1541-0420.2005.00440.x.

To ensure that the homogeneity assumption holds, we retrieve the corresponding information from the results of RDA. Group dispersions are only defined for categorical variables, so we show the results for clinical status and gender. addRDA() also tests age, but because age is continuous, each distinct value is treated as its own group, and that result is not meaningful. None of the p-values of the categorical variables is lower than the significance threshold, and thus homogeneity is observed.

Note

PERMANOVA assumes that the group dispersions are homogeneous. This means that the variation within groups, i.e., the spread of samples around their group centroid, is similar in all groups. If this assumption is not met, the results can be misleading.

addRDA() performs homogeneity test automatically.

# Homogeneity of dispersion is defined only for categorical variables
rda_info$homogeneity[c("ClinicalStatus", "Gender"), ] |>
    knitr::kable()
Df Sum Sq Mean Sq F N.Perm Pr(>F) Total variance Explained variance
ClinicalStatus 4 0.2511 0.0628 2.7440 999 0.131 1.0288 0.2440
Gender 1 0.0103 0.0103 0.4158 999 0.546 0.9283 0.0111

As the group dispersions are homogeneous, PERMANOVA can be seen as an appropriate choice for comparing community compositions.

13.6 Case studies

13.6.1 Visualizing the most dominant genus on PCoA

In this section, we visualize the most dominant genus with PCoA. A similar visualization was proposed by Salosensaari et al. (2021). First, let us agglomerate the data at the Genus level and identify the dominant taxonomic features for each sample.

Taxonomic signatures of cause-specific mortality risk in human gut microbiome. Salosensaari et al. (2021). Nat Commun 12:2671. doi:10.1038/s41467-021-22962-y.
# Agglomerate to genus level
tse_genus <- agglomerateByRank(tse, rank = "Genus")

# Convert to relative abundances
tse_genus <- transformAssay(
    tse_genus,
    method = "relabundance", assay.type = "counts"
)

# Add info on dominant genus per sample
tse_genus <- addDominant(
    tse_genus,
    assay.type = "relabundance", name = "dominant_taxa"
)

# Overview
summarizeDominance(
    tse_genus,
    digits = 3, name = "dominant_taxa"
)
##  # A tibble: 17 × 3
##    dominant_taxa                n rel_freq
##    <chr>                    <int>    <dbl>
##  1 Bacteroides                  5    0.192
##  2 Crenothrix                   3    0.115
##  3 Faecalibacterium             2    0.077
##  4 Prochlorococcus              2    0.077
##  5 Streptococcus                2    0.077
##  6 CandidatusNitrososphaera     1    0.038
##  # ℹ 11 more rows

Next, we perform PCoA with Bray-Curtis dissimilarity.

tse_genus <- addMDS(
    tse_genus,
    name = "PCoA_BC",
    method = "bray",
    assay.type = "relabundance"
)

Finally, we visualize the dominant genera on the PCoA (Figure 13.15).

Show the plotting code
# Dominant genus of each sample. Genera other than the six most often
# dominant ones are named "Other".
tse_genus <- addDominant(
    tse_genus,
    assay.type = "relabundance", n = 6, name = "most_abundant"
)

# Visualization
plotOrdination(
    tse_genus, "PCoA_BC",
    colour.by = "most_abundant",
    add.expl.var = TRUE
) +
    labs(colour = "Most abundant genus")
Scatter plot of the samples on the first two PCoA axes, with the percentage of variance explained in the axis labels. Points are colored by dominant genus, with seven colors for the six most often dominant genera and Other.
Figure 13.15: Bray-Curtis PCoA of the GlobalPatterns samples colored by their dominant genus. The six genera that are most often dominant are shown separately and the remaining genera are grouped as Other.

Similarly, we visualize and compare the sub-population (Figure 13.16).

Show the plotting code
# Visualization split by group
plotOrdination(
    tse_genus, "PCoA_BC",
    colour.by = "most_abundant",
    facet.by = "Group",
    add.expl.var = TRUE
) +
    labs(colour = "Most abundant genus")
Two scatter plots side by side, one for fecal and one for non-fecal samples, showing the samples on the first two PCoA axes. Points are colored by dominant genus, using the six most often dominant genera and Other.
Figure 13.16: Bray-Curtis PCoA of the GlobalPatterns samples colored by their dominant genus, shown separately for fecal and non-fecal samples.
Functions for dissimilarity and ordination

As a final note, we provide a comprehensive list of functions for the evaluation of dissimilarity indices available in the mia and scater packages. The get (and calculate) methods return the result, such as a matrix of reduced dimensions, as an output, whereas the add (and run) methods store the result into the specified TreeSE.

For more information on sample clustering, you can refer to:

UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction. McInnes et al. (2018). arXiv. doi:10.48550/arXiv.1802.03426.
Visualizing data using t-SNE. van der Maaten et al. (2008). Journal of Machine Learning Research 9:2579–2605. http://jmlr.org/papers/v9/vandermaaten08a.html.
Divergence measures based on the Shannon entropy. Lin (1991). IEEE Trans Inf Theory 37:145–151. doi:10.1109/18.61115.
From dissimilarities among species to dissimilarities among communities: A double principal coordinate analysis. Pavoine et al. (2004). Journal of Theoretical Biology 228:523–537. doi:10.1016/j.jtbi.2004.02.014.
Canonical correspondence analysis: A new eigenvector technique for multivariate direct gradient analysis. ter Braak (1986). Ecology 67:1167–1179. doi:10.2307/1938672.

13.7 Exercises

We use the Tengeler2020 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: Dissimilarity metrics

Goal: Explain how the choice of dissimilarity metric affects what is compared between samples.

Imagine two samples that both contain the same three taxa and 100 reads in total:

Taxon Sample A Sample B
Taxon 1 50 5
Taxon 2 30 5
Taxon 3 20 90

Answer the following questions without writing any code. The beginning of this chapter and the callouts “Dissimilarity or distance?” and “Common mistake in Jaccard index” will help you.

  1. What is the (presence/absence) Jaccard dissimilarity between the samples?

  2. Would the Bray-Curtis dissimilarity between the samples be the same as the Jaccard dissimilarity? Why?

  3. Which metric would you choose if you wanted to take into account how closely related the taxa are in the phylogenetic tree?

  4. The Aitchison distance can be calculated as a Euclidean distance. Which transformation must be applied to the counts first?

  5. Is Bray-Curtis a distance or a dissimilarity?

  1. The Jaccard dissimilarity is 0. The presence/absence Jaccard index only compares which taxa are present, and both samples contain the same three taxa.

  2. No. Bray-Curtis takes the abundances of the taxa into account. The samples contain the same taxa, but in very different proportions, so the Bray-Curtis dissimilarity is larger than zero, whereas the Jaccard dissimilarity is zero.

  3. UniFrac, which uses the phylogenetic tree of the taxa.

  4. The centered log-ratio (clr) transformation. The Aitchison distance is the Euclidean distance between clr-transformed abundances.

  5. Bray-Curtis is a dissimilarity. It does not fulfill all the requirements of a distance metric.

Exercise 2: Dissimilarity and divergence

Goal: Calculate and visualize the dissimilarities between samples, and the divergence of each sample from a reference.

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

  2. Transform the counts assay to relative abundances. The new assay is called relabundance.

  3. Calculate the Bray-Curtis dissimilarities between the samples from the relabundance assay with addDissimilarity(). Check the names of metadata(tse). Where was the result stored?

  4. Visualize the dissimilarity matrix as a heatmap, and annotate the samples by patient_status.

  5. Calculate the divergence of each sample from the median sample with addDivergence(). Use the relabundance assay, reference = "median" and method = "bray". The result is stored in the divergence column of colData.

  6. Visualize the divergence as boxplots, with one box for each group in patient_status.

  7. What does a single value in the dissimilarity matrix tell? What does a high divergence tell about a sample?

Useful functions: data(), mia::transformAssay(), mia::addDissimilarity(), metadata(), miaViz::plotDissimilarity(), mia::addDivergence(), miaViz::plotBoxplot()

library(mia)
library(miaViz)

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

# 2. Relative abundances
tse <- transformAssay(tse, assay.type = "counts", method = "relabundance")

# 3. Bray-Curtis dissimilarities, stored in metadata
tse <- addDissimilarity(tse, assay.type = "relabundance", method = "bray")
names(metadata(tse))
##  [1] "bray"

# 4. Heatmap of the dissimilarities
plotDissimilarity(tse, name = "bray", col.var = "patient_status")


# 5. Divergence from the median sample
tse <- addDivergence(
    tse,
    assay.type = "relabundance",
    reference = "median",
    method = "bray"
)

# 6. Boxplot of divergence by group
plotBoxplot(tse, col.var = "divergence", x = "patient_status") +
    labs(x = "Patient status", y = "Divergence from the median")

  1. The dissimilarity matrix was stored in metadata(tse) under the name bray.
  1. Each value in the dissimilarity matrix compares one pair of samples. A value close to 0 means that the two communities are very similar, and a value close to 1 means that they share hardly any abundance. The divergence compares a sample to a reference, here the median sample. A high divergence means that the community of the sample differs much from the typical community in the data.
Exercise 3: Principal Coordinate Analysis (PCoA)

Goal: Run PCoA and compare how the choice of dissimilarity metric and assay affects the ordination.

  1. Run PCoA with addMDS() on the relabundance assay using Bray-Curtis dissimilarity. Store the result under the name "MDS_bray".

  2. List the names of the reduced dimensions stored in tse. Is "MDS_bray" among them?

  3. Plot the first two coordinates of "MDS_bray" and color the samples by patient_status.

  4. Apply the clr transformation to the counts assay with a pseudocount of 0.5. Then run PCoA on the clr assay with Euclidean distance, that is, with the Aitchison distance. Store the result under the name "MDS_aitchison".

  5. Plot the first two coordinates of "MDS_aitchison" and color the samples by patient_status. Compare the plot with the plot from step 3.

  6. How do you read a PCoA plot? Why can the two plots look different, even though they are based on the same samples?

Useful functions: mia::addMDS(), mia::getDissimilarity(), SingleCellExperiment::reducedDimNames(), miaViz::plotOrdination(), mia::transformAssay()

library(miaViz)

# 1. PCoA with Bray-Curtis dissimilarity
tse <- addMDS(
    tse,
    method = "bray",
    assay.type = "relabundance",
    name = "MDS_bray"
)

# 2. Names of the reduced dimensions
reducedDimNames(tse)
##  [1] "MDS_bray"

# 3. Plot the Bray-Curtis PCoA
plotOrdination(tse, "MDS_bray", colour.by = "patient_status") +
    labs(colour = "Patient status")


# 4. clr transformation and PCoA with Aitchison distance
tse <- transformAssay(
    tse,
    assay.type = "counts", method = "clr", pseudocount = 0.5
)
tse <- addMDS(
    tse,
    method = "euclidean",
    assay.type = "clr",
    name = "MDS_aitchison"
)

# 5. Plot the Aitchison PCoA
plotOrdination(tse, "MDS_aitchison", colour.by = "patient_status") +
    labs(colour = "Patient status")

  1. Each point is a sample. Samples that are close to each other have similar community compositions, and samples that are far apart have different compositions. If the samples of a group cluster together and apart from the other group, the groups differ in community composition. If the groups overlap, the ordination does not show a clear difference. The two plots are based on different metrics. Bray-Curtis on relative abundances is dominated by the most abundant taxa. The Aitchison distance compares log-ratios, so a relative (fold) change counts equally regardless of the abundance of the taxon, and rare taxa have more influence than in Bray-Curtis. Therefore, the metric and assay should be chosen to fit the research question.
Exercise 4: Rarefaction in PCoA

Goal: Account for uneven sequencing depth with rarefaction in ordination.

  1. Calculate the library size of each sample, that is, the total number of reads in each sample, and summarize the library sizes.

  2. Run PCoA with Bray-Curtis dissimilarity and rarefaction. Use the counts assay, set the rarefaction depth sample to the smallest library size, use niter = 10 iterations, and store the result under the name "MDS_bray_rarefied". Set a seed before running the PCoA, as rarefaction is random.

  3. Plot the first two coordinates of "MDS_bray_rarefied" and color the samples by patient_status. Compare the plot with the "MDS_bray" plot from Exercise 3.

  4. Why do we rarefy, and why do we use the smallest library size as the rarefaction depth?

Useful functions: assay(), colSums(), summary(), min(), set.seed(), mia::addMDS(), mia::getDissimilarity(), miaViz::plotOrdination()

# 1. Library sizes
lib_size <- colSums(assay(tse, "counts"))
summary(lib_size)
##     Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##     1772   11804   16745   17997   21502   40584

# 2. PCoA with rarefaction
set.seed(123)
tse <- addMDS(
    tse,
    method = "bray",
    assay.type = "counts",
    sample = min(lib_size),
    niter = 10,
    name = "MDS_bray_rarefied"
)

# 3. Plot the rarefied PCoA
plotOrdination(tse, "MDS_bray_rarefied", colour.by = "patient_status") +
    labs(colour = "Patient status")

  1. Samples with more reads tend to have more taxa detected, so part of the differences between samples can be due to sequencing depth. Rarefaction subsamples every sample to the same number of reads, and the dissimilarities are averaged over the iterations. A sample cannot be subsampled to more reads than it contains, so samples with fewer reads than the chosen depth would have to be removed. Using the smallest library size keeps all the samples. If the rarefied and non-rarefied plots look similar, the differences in sequencing depth have little effect on the ordination. If they look different, sequencing depth affects the result. Note that PCoA axes can be flipped between runs, so compare the relative positions of the samples rather than the signs of the coordinates.
Exercise 5: PERMANOVA

Goal: Test whether a variable explains differences in community composition, and check the homogeneity of group dispersions.

  1. Set a seed, as PERMANOVA is based on random permutations. Then run PERMANOVA with getPERMANOVA() on the relabundance assay with Bray-Curtis dissimilarity and the formula x ~ patient_status. Store the result in res.

  2. Look at the permanova table of the result. Find the proportion of variance explained (R2) by patient_status and the p-value (Pr(>F)).

  3. Look at the homogeneity table of the result. What does this test measure?

  4. Why should the homogeneity of group dispersions be checked when interpreting PERMANOVA?

Useful functions: set.seed(), mia::getPERMANOVA()

# 1. PERMANOVA
set.seed(123)
res <- getPERMANOVA(
    tse,
    assay.type = "relabundance",
    method = "bray",
    formula = x ~ patient_status
)

# 2. PERMANOVA results
res$permanova
##  Permutation test for adonis under reduced model
##  Marginal effects of terms
##  Permutation: free
##  Number of permutations: 999
##  
##  adonis2(formula = formula, data = data, by = by, na.action = na.action)
##                 Df SumOfSqs    R2  F Pr(>F)    
##  patient_status  1     1.70 0.306 11  0.001 ***
##  Residual       25     3.86 0.694              
##  Total          26     5.56 1.000              
##  ---
##  Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

# 3. Homogeneity of group dispersions
res$homogeneity
##                 Df  Sum Sq Mean Sq     F N.Perm Pr(>F) Total variance
##  patient_status  1 0.03382 0.03382 3.327    999  0.088          0.288
##                 Explained variance
##  patient_status             0.1174
  1. R2 tells the proportion of the variation in community composition that patient_status explains, and Pr(>F) is the permutation p-value. A p-value below the significance threshold (e.g. 0.05) means that the group centroids differ more than would be expected by chance.

  2. The homogeneity test compares the group dispersions, that is, the average distances between the samples and their group centroid.

  3. PERMANOVA compares the group centroids and assumes that the dispersions of the groups are similar. A significant PERMANOVA result together with a non-significant homogeneity test supports a difference in composition between the groups. If the homogeneity test is also significant, the PERMANOVA result may be caused by differences in the within-group variability instead, and it should be interpreted with caution.

Exercise 6: Distance-based redundancy analysis (dbRDA)

Goal: Run dbRDA with several covariates and visualize the result.

  1. Set a seed. Then run dbRDA with addRDA() on the relabundance assay with Bray-Curtis dissimilarity (distance = "bray") and the formula assay ~ patient_status + cohort.

  2. Retrieve the "significance" attribute of the "RDA" reduced dimension and store it in rda_info. Look at its permanova and homogeneity tables.

  3. Visualize the dbRDA result and color the samples by patient_status.

  4. Visualize the loadings of the 10 taxa with the largest contributions to the first two dbRDA components.

  5. Why do we include cohort in the formula? How do you read the arrows in the dbRDA plot?

Useful functions: set.seed(), mia::addRDA(), attr(), SingleCellExperiment::reducedDim(), miaViz::plotRDA(), miaViz::plotLoadings()

# 1. dbRDA with two covariates
set.seed(123)
tse <- addRDA(
    tse,
    assay.type = "relabundance",
    formula = assay ~ patient_status + cohort,
    distance = "bray"
)

# 2. PERMANOVA and homogeneity results
rda_info <- attr(reducedDim(tse, "RDA"), "significance")
rda_info$permanova
##                 Df SumOfSqs      F Pr(>F) Total variance Explained variance
##  Model           3   2.6540  7.009  0.001          5.557             0.4776
##  patient_status  1   1.7663 13.993  0.001          5.557             0.3178
##  cohort          2   0.9519  3.770  0.002          5.557             0.1713
##  Residual       23   2.9032     NA     NA          5.557             0.5224
rda_info$homogeneity
##                 Df  Sum Sq  Mean Sq       F N.Perm Pr(>F) Total variance
##  patient_status  1 0.03382 0.033822 3.32695    999  0.090         0.2880
##  cohort          2 0.00261 0.001305 0.05596    999  0.966         0.5623
##                 Explained variance
##  patient_status           0.117448
##  cohort                   0.004641

# 3. dbRDA plot
plotRDA(tse, "RDA", colour.by = "patient_status") +
    labs(colour = "Patient status")


# 4. Loadings of the top 10 taxa
plotLoadings(tse, "RDA", ncomponents = 2, n = 10)

  1. The mice come from different cohorts, and the cohort may also affect community composition. When cohort is included in the formula, the effect of patient_status is estimated while controlling for cohort, and the permanova table shows the variance explained by each variable separately. In the dbRDA plot, each arrow shows a covariate. For a categorical variable, there is one arrow for each level, compared to the reference level. The direction of an arrow shows in which direction the samples differ along that covariate, and a longer arrow means a stronger association with community composition. The labels show the explained variance and the p-value of each variable.
Back to top