14  Community typing

Community typing in microbial ecology involves identifying distinct microbial communities by recognizing patterns in the data. The community types are described based on taxonomic feature characteristics, representing each community. The samples are described by community type assignments, which are defined by the ecosystem features in the sample. Community typing techniques can typically be divided into unsupervised clustering and dimensionality reduction techniques, where clustering is more commonly used.

In this chapter, we first walk you through some common clustering schemes in use for microbial community ecology, then focus on more detailed community typing techniques based on data dimensionality reduction.

14.1 Clustering methods

Clustering techniques aim to find groups, called clusters, that share a pattern in the data. In the microbiome context, clustering techniques are included in microbiome community typing methods. For example, clustering allows samples to be distinguished from each other based on their microbiome community composition. A clustering scheme consists of two steps: the first is to compute the sample dissimilarities with a given distance metric, and the second is to form the clusters based on the dissimilarity matrix. The data can be clustered either based on features or on samples. The examples below are focused on sample clustering.

There are multiple clustering algorithms available. bluster is a Bioconductor package providing tools for clustering data in the SummarizedExperiment container. It offers multiple algorithms such as hierarchical clustering, DBSCAN, and K-means.

# Load dependencies
library(bluster)

In the examples of this chapter we use the peerj13075 data (Potbhare et al. 2022) (Section D.3) for microbiota community typing. This chapter illustrates how different results can be obtained depending on the choice of the algorithm. To reduce calculation time we decided to agglomerate taxonomic features onto ‘Class’ level and filter out the least prevalent taxonomic features as well as less commonly detected within a sample resulting in 26 features in the data (25 classes and an “Other” group that combines the remaining features).

Skin microbiota diversity among genetically unrelated individuals of Indian origin. Potbhare et al. (2022). PeerJ 10:e13075. doi:10.7717/peerj.13075.
library(mia)
data("peerj13075", package = "mia")
tse <- peerj13075

# Filter out most taxa to ease the calculation
tse_prev <- agglomerateByRank(tse, rank = "class")
tse_prev <- addPrevalence(tse_prev, detection = 0.01)
altExp(tse, "prevalent") <- subsetBy(
    tse_prev,
    rows = prevalence > 0.2, collapse = TRUE
)

14.1.1 Hierarchical clustering

Hierarchical clustering aims to find hierarchy between samples or features. There are two approaches: agglomerative (“bottom-up”) and divisive (“top-down”). In the agglomerative approach, each observation is first in a unique cluster, after which the algorithm continues to agglomerate similar data points into clusters. The divisive approach, instead, starts with one cluster that contains all observations. Clusters are split recursively into clusters that differ the most. The clustering can be continued until each cluster contains only one observation.

In this example we use the addCluster() function from mia to cluster the data. The addCluster() function allows you to choose a clustering algorithm and offers multiple parameters to shape the result. The HclustParam() parameter is used for hierarchical clustering, and it accepts several sub-parameters, as further detailed in the HclustParam documentation of bluster (see ?bluster::HclustParam). Notably, the by argument specifies whether clustering is performed based on features or samples. Here, we cluster counts data, for which we compute the dissimilarities with the Bray-Curtis distance (Bray and Curtis 1957) using the ward.D2 method (Ward 1963; Murtagh and Legendre 2014). Statistical information can be optionally returned with the full parameter. Finally, the clust.col parameter allows us to choose the name of the column in the colData (default name is cluster).

An ordination of the upland forest communities of southern wisconsin. Bray et al. (1957). Ecol Monogr 27:325–349. doi:10.2307/1942268.
Hierarchical grouping to optimize an objective function. Ward (1963). J Am Stat Assoc 58:236–244. doi:10.1080/01621459.1963.10500845.
Ward’s hierarchical agglomerative clustering method: Which algorithms implement Ward’s criterion? Murtagh et al. (2014). J Classif 31:274–295. doi:10.1007/s00357-014-9161-z.
library(vegan)

# Set seed for reproducibility
set.seed(174923)

# Add cluster
altExp(tse, "prevalent") <- addCluster(
    altExp(tse, "prevalent"),
    assay.type = "counts",
    by = "cols",
    HclustParam(method = "ward.D2", dist.fun = getDissimilarity, metric = "bray"),
    full = TRUE,
    clust.col = "hclust"
)

# Print the result table
table(altExp(tse, "prevalent")$hclust)
##  
##   1  2  3  4  5  6 
##  13  5  8 16 11  5

From the table we can see that the hierarchical clustering suggests six clusters to describe the data. Unless the number of clusters (k) or the cutting height (h) is given in the cut.params argument of HclustParam(), the tree is cut at half of its total height; the number of branches crossing this height determines the number of clusters.

Now, we visualize the hierarchical structure of the clusters with a dendrogram tree using dendextend (Galili 2015). In each splitting point, the tree is divided into two clusters leading to the hierarchy. In this example, each sample is labeled by its dominant taxon to visualize ecological differences between the clusters (Figure 14.1).

dendextend: An R package for visualizing, adjusting and comparing trees of hierarchical clustering. Galili (2015). Bioinformatics 31:3718–3720. doi:10.1093/bioinformatics/btv428.
library(dendextend)

# Get hclust data from metadata
hclust_data <- metadata(altExp(tse, "prevalent"))$clustering$hclust

# Get the dendrogram object
dendro <- as.dendrogram(hclust_data)
k <- length(unique(altExp(tse, "prevalent")$hclust))

# Color the branches by clusters, with the same Okabe-Ito colors as in the
# miaViz plots (black, the first color, is skipped)
cols <- palette.colors(k + 1, "Okabe-Ito")[-1]

# Order the colors to be equivalent to the factor levels; color_branches()
# colors the clusters from left to right in the order of the leaves
leaf_order <- order.dendrogram(dendro)
leaf_clusters <- altExp(tse, "prevalent")$hclust[leaf_order]
cols <- cols[unique(as.integer(leaf_clusters))]
dend <- color_branches(dendro, k = k, col = unlist(cols))

# Label the samples by their dominant taxon, in the order of the leaves
altExp(tse, "prevalent") <- addDominant(altExp(tse, "prevalent"))
labels(dend) <- altExp(tse, "prevalent")$dominant_taxa[leaf_order]
dend <- color_labels(dend, k = k, col = unlist(cols))

# Adjust frame for the figure
par(mar = c(9, 3, 0.5, 0.5))

# Plot dendrogram
dend |>
    set("labels_cex", 0.8) |>
    plot()
Dendrogram with the samples as leaves along the bottom and merge height on the vertical axis. Branches and leaf labels are drawn in six colors, one per cluster, and each leaf is labeled with the sample's dominant taxon.
Figure 14.1: Dendrogram of the hierarchical clustering (Ward’s method on Bray-Curtis dissimilarities) of samples in the prevalent class-level peerj13075 data. Branches and labels are colored by cluster, and samples are labeled by their dominant taxon.

We can also visualize the clusters by projecting the data onto a two-dimensional surface that captures the most variability in the data. In this example, we use multidimensional scaling (MDS) (see Section 13.4). The resulting ordination is shown in Figure 14.2.

library(miaViz)

# Add the MDS dimensions for plotting
altExp(tse, "prevalent") <- addMDS(
    altExp(tse, "prevalent"),
    assay.type = "counts",
    FUN = vegan::vegdist,
    method = "bray"
)
plotOrdination(
    altExp(tse, "prevalent"), "MDS",
    colour.by = "hclust", add.expl.var = TRUE
) +
    labs(colour = "Cluster")
Scatter plot of the samples on the first two MDS axes, with points colored by their hierarchical clustering assignment.
Figure 14.2: MDS ordination based on Bray-Curtis dissimilarities of the prevalent class-level peerj13075 data, with samples colored by hierarchical clustering assignment.

14.1.2 Agglomerate by cluster

Another way to agglomerate the data is to perform it based on clusters of the taxonomic features. To do so, we usually start by doing a compositionality-aware transformation such as CLR (Fernandes et al. 2014), followed by the application of a standard clustering method.

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.
A new measure of rank correlation. Kendall (1938). Biometrika 30:81–93. doi:10.1093/biomet/30.1-2.81.

Below is an example of a CLR transformation followed by the hierarchical clustering algorithm. We will use the Kendall dissimilarity, that is, one minus Kendall’s rank correlation (Kendall 1938).

# The result of the CLR transform is stored in the assay clr
tse <- transformAssay(tse, method = "clr", pseudocount = 1)

tse <- transformAssay(
    tse,
    assay.type = "clr", method = "standardize", MARGIN = "rows"
)

# Declare the Kendall dissimilarity computation function
kendall_dissimilarity <- function(x) {
    as.dist(1 - cor(t(x), method = "kendall"))
}

# Cluster (with Kendall dissimilarity) on the features of the `standardize` assay
tse <- addCluster(
    tse,
    assay.type = "standardize",
    clust.col = "hclustKendall",
    by = "rows",
    HclustParam(dist.fun = kendall_dissimilarity, method = "ward.D2")
)

The results are stored in the rowData column specified with the clust.col parameter. To better visualize the results and the distribution of the clusters, we can plot the number of features in each cluster (Figure 14.3).

library(miaViz)

plotBarplot(tse, row.var = "hclustKendall") +
    labs(x = "Feature cluster", y = "Number of features")
Bar plot with one bar per cluster on the x-axis and the number of taxonomic features in that cluster on the y-axis.
Figure 14.3: Number of taxonomic features in each cluster obtained by hierarchical clustering of standardized CLR-transformed abundances with Kendall dissimilarity.

Then we can merge data to clusters.

# Aggregate clusters as a sum of each cluster values
tse_merged <- agglomerateByVariable(tse, by = "rows", group = "hclustKendall")
tse_merged
##  class: TreeSummarizedExperiment 
##  dim: 4 58 
##  metadata(0):
##  assays(3): counts clr standardize
##  rownames(4): 1 2 3 4
##  rowData names(7): kingdom phylum ... genus hclustKendall
##  colnames(58): ID1 ID2 ... ID57 ID58
##  colData names(5): Sample Geographical_location Gender Age Diet
##  reducedDimNames(0):
##  mainExpName: NULL
##  altExpNames(1): prevalent
##  rowLinks: NULL
##  rowTree: NULL
##  colLinks: NULL
##  colTree: NULL

This confirms that the operation succeeded, as the number of rows now matches the number of clusters. You can find more information on agglomeration from Chapter 9.

14.1.3 DMM

This section focuses on Dirichlet Multinomial Mixture Model (DMM) analysis (Holmes et al. 2012). It is a Bayesian clustering technique that allows searching for sample patterns that reflect sample similarity in the data using both prior information and the data.

Dirichlet multinomial mixtures: Generative models for microbial metagenomics. Holmes et al. (2012). PLoS One 7:e30126. doi:10.1371/journal.pone.0030126.

In this example, we cluster the data with DMM clustering. In the example below, we calculate model fit using Laplace approximation to reduce the calculation time. The cluster information is added to the metadata with an optional name. In this example, we use a prior assumption that the optimal number of clusters to describe the data would be in the range from 1 to 6.

# Runs the model and calculates the most likely number of clusters from 1 to 6
set.seed(1495723)

altExp(tse, "prevalent") <- addCluster(
    altExp(tse, "prevalent"),
    assay.type = "counts",
    name = "DMM",
    DmmParam(k = 1:6, type = "laplace"),
    by = "cols",
    full = TRUE,
    clust.col = "dmmclust"
)

Figure 14.4 represents the Laplace approximation to the model evidence for each of the six models. We can see that the best number of clusters is two, as the minimum value of Laplace approximation determines the optimal k.

library(miaViz)

plotDMNFit(altExp(tse, "prevalent"), type = "laplace", name = "DMM") +
    scale_x_continuous(breaks = 1:6)
Line plot with the number of DMM components (1 to 6) on the x-axis and the Laplace approximation on the y-axis. The line reaches its lowest value at two components.
Figure 14.4: Laplace approximation of model evidence for DMM models with one to six components fitted to the prevalent class-level peerj13075 data. Lower values indicate a better fit.

Two clusters describe the data best. Now we can plot which taxonomic features define the key cluster features (Figure 14.5).

library(DirichletMultinomial)

# Get the estimates of how much each class contributes to each cluster
models <- metadata(altExp(tse, "prevalent"))$DMM
n_clusters <- models[["best"]]
best_model <- models[["dmm"]][[n_clusters]]
drivers <- fitted(best_model, scale = TRUE)

# Plot by utilizing miaViz's function plotLoadings
plotLoadings(drivers, ncomponents = n_clusters)
Two panels of horizontal bar charts, one per DMM component, with taxonomic features on the y-axis and the size of their contribution to that component on the x-axis.
Figure 14.5: Contributions of taxonomic features to each of the two components of the best-fitting DMM model.

As well as in hierarchical clustering, we can also visualize the clusters by projecting the data onto a two-dimensional surface calculated using MDS (Figure 14.6). The plot rather clearly demonstrates the cluster division.

# DMM clusters
plotOrdination(
    altExp(tse, "prevalent"), "MDS",
    colour.by = "dmmclust", add.expl.var = TRUE
) +
    labs(colour = "DMM cluster")
Scatter plot of the samples on the first two MDS axes, with points colored by the two DMM clusters, which occupy separate areas of the plot.
Figure 14.6: MDS ordination based on Bray-Curtis dissimilarities of the prevalent class-level peerj13075 data, with samples colored by DMM cluster assignment.

14.2 Dimensionality reduction

Dimensionality reduction can be considered a part of community typing, where the aim is to find underlying structure in the data. Dimensionality reduction relies on the idea that the data can be described as a lower rank representation, where latent features with different loads of the observed ones describe the sample set. This representation stores the information about sample dissimilarity with significantly reduced amount of data dimensions. Unlike clustering, where each sample is assigned into one cluster, dimensionality reduction allows continuous memberships of all samples across all community types. Dimensionality reduction techniques are explained in more detail in Chapter 13.

14.2.1 NMF

In this section, we will particularly focus on Non-negative Matrix Factorization (NMF) (Lee and Seung 1999). NMF decomposes the original data X into two lower rank matrices: H representing key taxonomic feature characteristics of each community type and W representing continuous sample memberships across all community types. The NMF algorithm calculates the minimum distance between the original data and its approximation using Kullback-Leibler divergence.

Learning the parts of objects by non-negative matrix factorization. Lee et al. (1999). Nature 401:788–791. doi:10.1038/44565.
A flexible R package for nonnegative matrix factorization. Gaujoux et al. (2010). BMC Bioinformatics 11:367. doi:10.1186/1471-2105-11-367.

Here, we use the mia wrapper getNMF for the NMF package (Gaujoux and Seoighe 2010). To reduce calculation time, we set the number of components k to four instead of optimizing the number of components that describe the original data the best. The matrix returned by getNMF contains the sample scores, while the NMF output and NMF feature loadings are stored in the attributes NMF_output and loadings, respectively.

library(NMF)

# Calculate NMF
set.seed(3221)
res <- getNMF(altExp(tse, "prevalent"), k = 4)

# Obtain the relative membership of each component in each sample
wrel <- t(apply(res, 1, function(x) {
    x / sum(x)
}))

# Define the community type of a sample with the highest relative abundance
altExp(tse, "prevalent")$NMFcomponent <- as.factor(apply(wrel, 1, which.max))
table(altExp(tse, "prevalent")$NMFcomponent)
##  
##   1  2  3  4 
##  11 14 28  5

Now, we can plot the NMF community types calculated based on maximum membership for each sample onto a two-dimensional surface (Figure 14.7).

# NMF community types
plotOrdination(
    altExp(tse, "prevalent"), "MDS",
    colour.by = "NMFcomponent", add.expl.var = TRUE
) +
    labs(colour = "NMF component")
Scatter plot of the samples on the first two MDS axes, with points colored by NMF community type, one of four components.
Figure 14.7: MDS ordination based on Bray-Curtis dissimilarities of the prevalent class-level peerj13075 data, with samples colored by NMF community type, defined as the component with the highest relative membership.

Latent Dirichlet Allocation (LDA) (Blei et al. 2003) is an alternative to NMF. It is a probabilistic topic model for count data: each sample is a mixture of “topics”, i.e., community types, and each topic is a distribution over the features. In mia, LDA is calculated with addLDA() (or getLDA()), and its results are used in the same way as those of NMF.

Latent dirichlet allocation. Blei et al. (2003). Journal of Machine Learning Research 3:993–1022. https://www.jmlr.org/papers/v3/blei03a.html.

14.3 Heatmaps with clusters

In Section 11.2, we visualized community composition with heatmaps. We can visualize the data similarly but add additional information on clusters.

# Keep only counts; transformed assays cannot be meaningfully agglomerated
assays(tse) <- assays(tse)["counts"]

# Agglomerate to Genus level
tse <- agglomerateByRank(tse, rank = "genus")
tse <- addPrevalence(tse)
tse <- subsetBy(tse, rows = prevalence > 0.5, collapse = TRUE)

# Apply clr and scale data
tse <- transformAssay(tse, method = "clr", pseudocount = 0.5)
tse <- transformAssay(
    tse,
    assay.type = "clr", method = "standardize", MARGIN = "rows"
)

Now we can cluster rows. The resulting tree of taxa, plotted with ggtree (Yu et al. 2017), is shown in Figure 14.8.

ggtree: An R package for visualization and annotation of phylogenetic trees with their covariates and other associated data. Yu et al. (2017). Methods Ecol Evol 8:28–36. doi:10.1111/2041-210x.12628.
library(ape)
library(ggtree)

# Hierarchical clustering
tse <- addCluster(
    tse,
    assay.type = "standardize", HclustParam(method = "complete"),
    full = TRUE
)
taxa_hclust <- metadata(tse)[["clustering"]][["hclust"]]

# Creates a tree
taxa_tree <- as.phylo(taxa_hclust)
ggtree(taxa_tree) + geom_tiplab(size = 3) + hexpand(0.3)
Tree drawn with straight right-angled branches, splitting from a single root on the left into the genera as tips on the right, showing how the genera group by similar abundance profiles.
Figure 14.8: Tree from complete-linkage hierarchical clustering of genera based on standardized CLR-transformed abundances in the peerj13075 data.

Based on the phylo tree, we decide to create eight clusters.

# Hierarchical clustering with k = 8
tse <- addCluster(
    tse,
    assay.type = "standardize",
    HclustParam(method = "complete", cut.params = list(k = 8)),
    clust.col = "taxa_cluster"
)

For the columns, we can utilize k-means clustering (Hartigan and Wong 1979). First we have to specify the number of clusters. Figure 14.9 shows the elbow and silhouette (Rousseeuw 1987) methods for this purpose.

Algorithm AS 136: A K-means clustering algorithm. Hartigan et al. (1979). Appl Stat 28:100–108. doi:10.2307/2346830.
Silhouettes: A graphical aid to the interpretation and validation of cluster analysis. Rousseeuw (1987). J Comput Appl Math 20:53–65. doi:10.1016/0377-0427(87)90125-7.
library(factoextra)
library(patchwork)

# Samples must be in rows, so we transpose the assay
mat <- t(assay(tse, "standardize"))
# Elbow method
p1 <- fviz_nbclust(mat, kmeans, method = "wss") +
    labs(y = "Total within-cluster sum of squares")
# Silhouette method
p2 <- fviz_nbclust(mat, kmeans, method = "silhouette")

p1 + p2 & labs(title = NULL)
Two line plots with the number of clusters on the x-axis. Left: total within-cluster sum of squares, which levels off after about three clusters. Right: average silhouette width, which is highest at two clusters, followed by three.
Figure 14.9: Selection of the number of k-means clusters. Left: total within-cluster sum of squares (elbow method). Right: average silhouette width, both as a function of the number of clusters.

The decrease in the within-cluster sum of squares levels off after about three clusters, and the average silhouette width is highest for two clusters and second highest for three. Based on the results, we split the columns into three clusters.

# K-means clustering with 3 clusters
tse <- addCluster(
    tse,
    assay.type = "standardize", by = "cols",
    KmeansParam(centers = 3),
    clust.col = "sample_cluster"
)

# Number of samples in each cluster
table(colData(tse)[["sample_cluster"]])
##  
##   1  2  3 
##  15 13 30

Now we can create a heatmap where the taxa are grouped by their clusters, and the samples by their clusters and gender (Figure 14.10).

plotHeatmap(
    tse,
    assay.type = "standardize",
    row.var = "taxa_cluster",
    col.var = c("sample_cluster", "Gender")
)
Large heatmap with genera as rows and samples as columns, colored by standardized CLR abundance. Rows are split into eight blocks by taxa cluster, and columns into blocks by k-means sample cluster and gender, with annotation bars marking the groups.
Figure 14.10: Heatmap of standardized CLR-transformed genus abundances in the peerj13075 data. Rows are grouped by hierarchical clusters of taxa, and columns by k-means clusters of samples and by gender.
TipOther methods

For more community typing techniques applied to the SprockettTHData dataset, see the attached .Rmd file.

14.4 Exercises

We use the GlobalPatterns dataset.

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

TipExercise 1: Clustering and dimensionality reduction

Goal: Explain the main ideas of community typing.

Answer the following questions without writing any code. The beginning of this chapter and the sections “Clustering methods” and “Dimensionality reduction” will help you.

  1. Clustering of samples consists of two steps. What are they?

  2. In clustering, how many clusters does each sample belong to? How does this differ in dimensionality reduction methods such as NMF?

  3. Can the data be clustered only based on samples?

  1. First, the dissimilarities between the samples are calculated with a chosen dissimilarity metric, such as Bray-Curtis. Second, the clusters are formed from the dissimilarity matrix with a clustering algorithm, such as hierarchical clustering.

  2. In clustering, each sample is assigned to exactly one cluster. In dimensionality reduction, each sample has a continuous membership across all community types. For instance, in NMF a sample can belong partly to several community types.

  3. No. The data can be clustered either based on samples or based on features. For example, taxonomic features with similar abundance patterns can be clustered together.

TipExercise 2: Hierarchical clustering

Goal: Cluster samples with hierarchical clustering and visualize the clusters.

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

  2. Agglomerate the data to the Class rank, and transform the counts assay into relative abundances. Then add the prevalence using the relabundance assay and a detection threshold of 0.01, and combine the classes with a prevalence of 0.2 or less into “Other”. How many features are left?

  3. Cluster the samples with hierarchical clustering with addCluster(). Use the counts assay, Bray-Curtis dissimilarity and the ward.D2 method. Return the full results with full = TRUE and store the clusters in the colData column "hclust".

  4. Show the number of samples in each cluster. Then cross-tabulate the clusters with SampleType.

  5. Plot the dendrogram of the hierarchical clustering, which is stored in metadata(tse)$clustering$hclust. Label the samples by their SampleType.

  6. Run PCoA with Bray-Curtis dissimilarity on the counts assay with addMDS(). Plot the first two coordinates and color the samples by the "hclust" clusters. Then make the same plot again, but color the samples by SampleType.

  7. How can you tell from the cross-tabulation and the plots whether the clusters correspond to the sample types?

Useful functions: data(), mia::agglomerateByRank(), mia::transformAssay(), mia::addPrevalence(), mia::subsetBy(), mia::addCluster(), bluster::HclustParam(), mia::getDissimilarity(), table(), metadata(), plot(), mia::addMDS(), miaViz::plotOrdination()

library(mia)
library(bluster)
library(miaViz)

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

# 2. Agglomerate to prevalent classes
tse <- agglomerateByRank(tse, rank = "Class")
tse <- transformAssay(tse, assay.type = "counts", method = "relabundance")
tse <- addPrevalence(tse, assay.type = "relabundance", detection = 0.01)
tse <- subsetBy(tse, rows = prevalence > 0.2, collapse = TRUE)
nrow(tse)
##  [1] 15

# 3. Hierarchical clustering of samples
tse <- addCluster(
    tse,
    assay.type = "counts",
    by = "cols",
    HclustParam(
        method = "ward.D2", dist.fun = getDissimilarity, metric = "bray"
    ),
    full = TRUE,
    clust.col = "hclust"
)

# 4. Cluster sizes, and clusters compared to sample types
table(tse$hclust)
##  
##  1 2 3 4 5 
##  8 7 5 3 3
table(tse$hclust, tse$SampleType)
##     
##      Feces Freshwater Freshwater (creek) Mock Ocean Sediment (estuary) Skin
##    1     0          2                  0    0     3                  0    0
##    2     4          0                  0    3     0                  0    0
##    3     0          0                  0    0     0                  2    2
##    4     0          0                  0    0     0                  1    1
##    5     0          0                  3    0     0                  0    0
##     
##      Soil Tongue
##    1    3      0
##    2    0      0
##    3    0      1
##    4    0      1
##    5    0      0

# 5. Dendrogram labeled by sample type
hclust_res <- metadata(tse)$clustering$hclust
plot(hclust_res, labels = tse$SampleType, main = "", sub = "", xlab = "")


# 6. PCoA colored by clusters and by sample type
tse <- addMDS(
    tse,
    method = "bray",
    assay.type = "counts"
)
plotOrdination(tse, "MDS", colour.by = "hclust", add.expl.var = TRUE) +
    labs(colour = "Cluster")

plotOrdination(tse, "MDS", colour.by = "SampleType", add.expl.var = TRUE) +
    labs(colour = "Sample type")

  1. In the cross-tabulation, each row is a cluster and each column a sample type. If the clusters correspond to the sample types, the samples of each sample type fall into a single cluster. If the samples of a sample type are spread across several clusters, or a cluster contains many sample types, the clusters and the sample types do not match well. In the plots, the clusters correspond to the sample types if the two colorings group the same samples together.
TipExercise 3: Dirichlet Multinomial Mixtures (DMM)

Goal: Cluster samples with DMM and choose the number of clusters.

  1. Set a seed, as DMM is random. Then cluster the samples with DMM with addCluster(). Use the counts assay and test from 1 to 5 clusters with Laplace approximation (k = 1:5, type = "laplace"). Store the models in metadata under the name "DMM" with full = TRUE, and the clusters in the colData column "dmmclust".

  2. Plot the model fit for each number of clusters. Which number of clusters fits the data best?

  3. Show the number of samples in each DMM cluster. Then cross-tabulate the DMM clusters with the hierarchical clusters from Exercise 2.

  4. Plot the PCoA from Exercise 2 and color the samples by the DMM clusters.

  5. Get the best model from metadata(tse)$DMM, calculate how much each taxonomic feature contributes to each cluster with fitted(), and visualize the contributions.

Useful functions: set.seed(), mia::addCluster(), bluster::DmmParam(), miaViz::plotDMNFit(), table(), miaViz::plotOrdination(), metadata(), DirichletMultinomial::fitted(), miaViz::plotLoadings()

library(miaViz)
library(DirichletMultinomial)

# 1. DMM clustering with 1 to 5 clusters
set.seed(123)
tse <- addCluster(
    tse,
    assay.type = "counts",
    name = "DMM",
    DmmParam(k = 1:5, type = "laplace"),
    by = "cols",
    full = TRUE,
    clust.col = "dmmclust"
)

# 2. Model fit
plotDMNFit(tse, type = "laplace", name = "DMM")


# 3. Cluster sizes, and DMM clusters compared to hierarchical clusters
table(tse$dmmclust)
##  
##   1  2 
##  19  7
table(tse$hclust, tse$dmmclust)
##     
##      1 2
##    1 8 0
##    2 0 7
##    3 5 0
##    4 3 0
##    5 3 0

# 4. PCoA colored by DMM clusters
plotOrdination(tse, "MDS", colour.by = "dmmclust", add.expl.var = TRUE) +
    labs(colour = "DMM cluster")


# 5. Contributions of the features to each cluster in the best model
models <- metadata(tse)$DMM
n_clusters <- models[["best"]]
best_model <- models[["dmm"]][[n_clusters]]
drivers <- fitted(best_model, scale = TRUE)
plotLoadings(drivers, ncomponents = n_clusters)

  1. The best number of clusters is the one with the lowest value of the Laplace approximation. It is also stored in metadata(tse)$DMM$best.

  2. Different algorithms can give different clusters for the same data. If each hierarchical cluster falls into a single DMM cluster, the methods agree. DMM may also merge several hierarchical clusters into one.

TipExercise 4: K-means clustering

Goal: Cluster samples with k-means and choose the number of clusters with the silhouette method.

  1. Apply the clr transformation to the counts assay. After the filtering there are no zeros, so no pseudocount is needed.

  2. Set a seed, as k-means is random. Then plot the average silhouette width for different numbers of clusters with fviz_nbclust(). K-means clusters the rows of the data, so give the function the transposed clr assay, where the samples are in rows. Use nstart = 25, so that k-means is run from 25 random starting points and the result is stable.

  3. Set a seed again, and cluster the samples with k-means with addCluster(). Use the clr assay, 5 clusters (centers = 5) and nstart = 25. Store the clusters in the colData column "kmeans". Check the plot from step 2: how does the average silhouette width of 5 clusters compare to the other numbers of clusters?

  4. Cross-tabulate the k-means clusters with SampleType.

Useful functions: mia::transformAssay(), set.seed(), factoextra::fviz_nbclust(), t(), assay(), mia::addCluster(), bluster::KmeansParam(), table()

library(factoextra)

# 1. clr transformation
tse <- transformAssay(tse, assay.type = "counts", method = "clr")

# 2. Silhouette method
set.seed(123)
fviz_nbclust(
    t(assay(tse, "clr")), kmeans,
    method = "silhouette", nstart = 25
) +
    labs(title = NULL)


# 3. k-means clustering with 5 clusters
set.seed(123)
tse <- addCluster(
    tse,
    assay.type = "clr",
    by = "cols",
    KmeansParam(centers = 5, nstart = 25),
    clust.col = "kmeans"
)

# 4. k-means clusters compared to sample types
table(tse$kmeans, tse$SampleType)
##     
##      Feces Freshwater Freshwater (creek) Mock Ocean Sediment (estuary) Skin
##    1     0          2                  0    0     3                  0    0
##    2     0          0                  0    3     0                  0    3
##    3     0          0                  0    0     0                  0    0
##    4     4          0                  0    0     0                  0    0
##    5     0          0                  3    0     0                  3    0
##     
##      Soil Tongue
##    1    0      0
##    2    0      2
##    3    3      0
##    4    0      0
##    5    0      0
  1. The silhouette width measures how well each sample fits its own cluster compared to the other clusters. The number of clusters with the highest average silhouette width (marked with a dashed line) gives the most clearly separated clusters.
TipExercise 5: Clustering taxonomic features

Goal: Cluster taxonomic features and agglomerate the data based on the clusters.

  1. Standardize the clr assay by features (method = "standardize", MARGIN = "rows"). The new assay is called standardize.

  2. Cluster the features with hierarchical clustering with addCluster(). Use the standardize assay, cluster by rows, use the complete method, and cut the tree into 4 clusters (cut.params = list(k = 4)). Store the clusters in the rowData column "taxa_clusters".

  3. Visualize the number of features in each cluster with a bar plot.

  4. Agglomerate the data based on the feature clusters. How many rows does the agglomerated data have?

  5. Why are the abundances transformed with clr before clustering the features? Why does the agglomeration give a warning about the clr and standardize assays?

Useful functions: mia::transformAssay(), mia::addCluster(), bluster::HclustParam(), miaViz::plotBarplot(), mia::agglomerateByVariable(), nrow()

# 1. Standardize the clr assay by features
tse <- transformAssay(
    tse,
    assay.type = "clr", method = "standardize", MARGIN = "rows"
)

# 2. Hierarchical clustering of features into 4 clusters
tse <- addCluster(
    tse,
    assay.type = "standardize",
    by = "rows",
    HclustParam(method = "complete", cut.params = list(k = 4)),
    clust.col = "taxa_clusters"
)

# 3. Number of features in each cluster
plotBarplot(tse, row.var = "taxa_clusters") +
    labs(x = "Feature cluster", y = "Number of features")


# 4. Agglomerate the data based on the clusters
tse_merged <- agglomerateByVariable(
    tse,
    by = "rows", group = "taxa_clusters"
)
nrow(tse_merged)
##  [1] 4
  1. The agglomerated data has one row for each cluster, that is, 4 rows.

  2. Microbiome data is compositional, so the clr transformation is applied to make the abundances comparable before the dissimilarities are calculated. In agglomeration, the values of the features in the same cluster are summed. This is meaningful for counts, but not for transformed values that include negative values, such as clr and standardized values. Therefore, the transformations should be calculated again from the agglomerated counts.

TipExercise 6: Heatmap with clusters

Goal: Visualize the clusters of samples and features together with the abundances on a heatmap.

  1. Visualize the standardize assay as a heatmap with plotHeatmap(). Group the rows by the feature clusters in the rowData column "taxa_clusters" from Exercise 5, and the columns by the k-means clusters in the colData column "kmeans" from Exercise 4 and by SampleType.

  2. Look at the rows of the heatmap. How can you see from the heatmap that the features in the same cluster have similar abundance profiles across the samples?

  3. Look at the columns of the heatmap. How can you see whether the k-means clusters match the sample types?

  4. Why is the standardized clr assay used for the heatmap instead of the counts?

Useful functions: miaViz::plotHeatmap()

# 1. Heatmap grouped by feature and sample clusters
plotHeatmap(
    tse,
    assay.type = "standardize",
    row.var = "taxa_clusters",
    col.var = c("kmeans", "SampleType")
)

  1. Each row group contains the features of one cluster. If the features in a cluster have similar abundance profiles, the colors within the group change in a similar way across the samples, which forms horizontal patterns of similar color.

  2. The columns are first grouped by the k-means clusters and then by SampleType. If a sample type appears in only one k-means cluster, the clustering separates that sample type from the others. If the same sample type appears in several k-means clusters, the clusters do not match the sample types.

  3. The counts of different features vary greatly in scale, so a few abundant features would dominate the colors. The clr transformation accounts for the compositionality of the data, and the standardization puts all features on the same scale, so that the patterns across the samples can be compared between the features. This is the same data that was used to cluster the features.

Back to top