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:
- Bray-Curtis index (for compositional data) (Bray and Curtis 1957)
- Jaccard index (for presence/absence data, ignoring abundance information) (Jaccard 1912)
- Aitchison distance (Euclidean distance for clr-transformed abundances, aiming to avoid the compositionality bias) (Aitchison 1986)
- UniFrac distance (takes into account the phylogenetic tree information) (Lozupone and Knight 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.
| 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 |
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.
Based on the type of algorithm, ordination methods in microbiome research can be generally divided into two categories:
- unsupervised ordination
- supervised ordination
The former includes Principal Coordinate Analysis (PCoA) (GOWER 1966), Principal Component Analysis (PCA), and Uniform Manifold Approximation and Projection for Dimension Reduction (UMAP) (McInnes et al. 2018), 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.
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 = TRUE
)
# Add group information Feces yes/no
tse$Group <- tse$SampleType == "Feces"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 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")
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")
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.
tse <- addDivergence(
tse,
assay.type = "counts",
reference = "median"
)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.
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.
Since PERMANOVA relies on comparing centroids, it assumes that the groups have similar within-group variation, i.e., homogeneous multivariate dispersions. 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.
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.003 0.6825
## Explained variance
## SampleType 0.7321The 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. However, 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.
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.
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
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)
p <- ggMarginal(p, type = "boxplot", groupFill = TRUE)
p
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")
p2 <- plotOrdination(tse, "MDS_aitchison", colour.by = "Group")
p3 <- plotOrdination(tse, "NMDS_bray", colour.by = "Group")
p4 <- plotOrdination(tse, "NMDS_aitchison", colour.by = "Group")
# Generate multi-panel plot
wrap_plots(p1, p2, p3, p4) +
plot_layout(guides = "collect")
The Unifrac method is a special case, as it requires data on the relationship of features in the form of a phylo tree. getDissimilarity() performs the calculation to return a dist object, which can again be used within addMDS() (Figure 13.7).
tse <- addMDS(
tse,
method = "unifrac",
name = "unifrac",
tree = rowTree(tse),
ntop = nrow(tse),
assay.type = "counts"
)
plotOrdination(tse, "unifrac", colour.by = "Group")
13.4.2 Rarefaction
Background on rarefaction is provided in Section 10.5.
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")
p2 <- plotOrdination(tse, "MDS_aitchison_rarefied", colour.by = "SampleType")
# Generate multi-panel plot
wrap_plots(p1, p2) +
plot_layout(guides = "collect")
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")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 and UMAP, are also available. PCA is calculated with addPCA() from mia, and UMAP with runUMAP() from the scater package (McCarthy et al. 2017). PCA is shown in Figure 13.9 and UMAP in Figure 13.10.
tse <- addPCA(
tse,
name = "PCA",
assay.type = "counts",
ncomponents = 10
)
# Visualize the result
plotOrdination(tse, "PCA", colour.by = "Group", add.expl.var = TRUE)
As mentioned before, applicability of the different methods depends on your sample set and research question.
library(scater)
tse <- runUMAP(
tse,
name = "UMAP",
assay.type = "counts",
ncomponents = 3
)
# Visualize the result
plotOrdination(tse, "UMAP", colour.by = "Group")
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.11).
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_smooth() +
geom_point() +
labs(
x = "Original distance",
y = "MDS distance",
subtitle = paste("Stress:", round(stress, 2))
)
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, UMAP |
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.
# Load data
data("enterotype", package = "mia")
tse2 <- enterotype
# 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
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.041 | 3.991 | 0.2795 |
| ClinicalStatus | 4 | 0.5837 | 1.522 | 0.129 | 3.991 | 0.1463 |
| Gender | 1 | 0.1679 | 1.751 | 0.115 | 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.12).
# Load packages for plotting function
library(miaViz)
# Generate RDA plot colored by clinical status
plotRDA(tse2, "RDA", colour.by = "ClinicalStatus")
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.
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.13).
plotLoadings(tse2, "RDA", ncomponents = 2, n = 20)
In the example above, the largest contributions to the first dbRDA component can be attributed to Bifidobacterium and -1.
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.
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.
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.117 | 1.0288 | 0.2440 |
| Gender | 1 | 0.0103 | 0.0103 | 0.4158 | 999 | 0.574 | 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.0.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.
# 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 rowsNext, we perform PCoA with Bray-Curtis dissimilarity.
tse_genus <- addMDS(
tse_genus,
name = "PCoA_BC",
method = "bray",
assay.type = "relabundance"
)Finally, we get the top taxonomic features and visualize their abundances on PCoA (Figure 13.14).
Show the plotting code
# Getting the top taxa
top_taxa <- getTop(tse_genus, top = 6, assay.type = "relabundance")
# Naming all the rest of non top-taxa "Other"
dominant <- tse_genus$dominant_taxa
most_abundant <- ifelse(dominant %in% top_taxa, dominant, "Other")
# Calculating percentage of the most abundant
most_abundant_percent <- round(prop.table(table(most_abundant)) * 100, 1)
# Storing the genera with their percentages as a new column within colData
colData(tse_genus)$most_abundant <- paste0(
most_abundant, " (", most_abundant_percent[most_abundant], "%)"
)
# Visualization
plotOrdination(
tse_genus, "PCoA_BC",
colour.by = "most_abundant",
add.expl.var = TRUE
)
Similarly, we visualize and compare the sub-population (Figure 13.15).
Show the plotting code
# Visualization split by group
plotOrdination(
tse_genus, "PCoA_BC",
colour.by = "most_abundant",
facet.by = "Group",
add.expl.var = TRUE
)
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.
- Canonical Correspondence Analysis (CCA):
getCCA()andaddCCA() - dbRDA:
getRDA()andaddRDA(); our recommended default method to assess differences in community composition (beta diversity) - Double Principal Coordinate Analysis (DPCoA):
getDPCoA()andaddDPCoA() - Jensen-Shannon Divergence (JSD):
getDissimilarity()andaddDissimilarity()withmethod = "jsd" - MDS:
getMDS()andaddMDS() - NMDS:
getNMDS()andaddNMDS() - Overlap:
getDissimilarity()andaddDissimilarity()withmethod = "overlap" - PERMANOVA:
getPERMANOVA()andaddPERMANOVA()(based onvegan::adonis2()) can be used to assess significance when comparing community composition between groups. However, retrieving the loadings and components is more tricky. - t-distributed Stochastic Neighbor Embedding (t-SNE):
calculateTSNE()andrunTSNE() - UMAP:
calculateUMAP()andrunUMAP()
For more information on sample clustering, you can refer to:
- How to extract information from clusters
- Chapter 14 on community typing
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.






