10  Transformation

Data transformations are common in (microbial) ecology (Legendre and Gallagher 2001). They are used to mitigate technical biases in the data, to obtain more interpretable values, to enhance the comparability of samples/features or to make data compatible with the assumptions of certain statistical methods.

Examples include transforming feature counts into relative abundances (i.e., “normalizing as proportions”), or with compositionality-aware transformations such as the centered log-ratio transformation (clr).

10.1 Why transform the data

Transformations are important in working with microbiome data due to various unique characteristics of sequencing data. For example, the above mentioned examples of feature transformations are commonly used with microbiome data following the inherently proportional nature of sequencing reads: due to the nature of sequencing technology, read counts of taxa do not represent real counts of microbes in the original sample, and raw counts of taxa per sample are thus not comparable between samples.

This compositionality means that a change in the absolute abundance of one taxon will lead to apparent variations in the relative abundances of other taxa in the same sample (Figure 10.1). If neglected, such properties may cause significant bias in the results of statistical tests. The above-mentioned transformation processes are one method developed to overcome these issues by making taxon abundances comparable across samples.

Two panels of stacked bars for a before and an after sample made of taxa A, B and C. In the absolute panel, A grows from 40 to 80 while B and C stay at 30; in the relative panel, A grows from 40% to 57% and B and C shrink from 30% to 21%.
Figure 10.1: Compositionality. The absolute abundance of taxon A doubles while taxa B and C do not change (left). In relative abundances, B and C appear to decrease (right), because the proportions in each sample must sum to one.

In addition to this compositionality, other special characteristics of microbiome sequencing data are high variability and zero-inflation. High variability means that abundance of taxa often varies by several orders of magnitude from sample to sample. Zero-inflation means that typically more than 70% of the taxa-per-sample values are zeros, which could be due to either physical absence (structural zeros) or insufficient sequencing coverage (sampling zeros).

10.2 Common methods

Let us now summarize some commonly used transformations in microbiome data science; further details and benchmarks are available in the references.

  • alr: The additive log ratio transformation (Aitchison 1986) is part of a broader Aitchison family of transformations with ‘clr’ and ‘rclr’. Compared to them the biggest difference is that it selects a single feature or component as a reference and expresses all other features as log-ratios relative to it. Greenacre et al. (2021) provides guidance on choosing an appropriate reference feature.

  • binning: Zero-aware quantile binning (Medearis et al. 2026). A useful transformation for discretizing raw abundance data to control noise, while still retaining some information. Selection of proper nbins should be tuned as a hyperparameter, when modeling.

  • clr: Centered log ratio transformation (Aitchison 1986) is used to reduce data skewness and compositionality bias in relative abundances, while bringing the data onto a logarithmic scale. This transformation is frequently applied in microbial ecology as it enhances comparability of relative differences between samples (Gloor et al. 2017). However, the resulting transformed values are difficult to interpret directly, and it can only be applied to positive values, not zeros. A usual solution for making values non-zero is to add a pseudocount, which adds another type of bias in the data as true taxon absences are not taken into account. This is mitigated by the method of robust clr transformation (see rclr below).

  • hellinger: Hellinger transformation (Legendre and Gallagher 2001) is equal to the square root of relative abundances. This ecological transformation can be useful when the focus is on how species proportions vary across samples, rather than on absolute counts.

  • log, log2, log10: Logarithmic transformations, used e.g. to reduce data skewness. With compositional data, the clr (or rclr) transformation is often preferred.

  • pa: Presence/Absence transformation ignores abundances and only indicates whether the given feature is detected above the given threshold (default: 0). This simple transformation is relatively widely used in ecological research, whenever we have reasons to be interested in which taxa are present in which samples more so than their abundances. An example of such case is the process of inferring microbial ecological association networks from covariation of taxa across samples. Here, microbes that are rarely seen in the same samples are expected to have a negative ecological association (either competitive exclusion with each other or different ecological niche preferences). Conversely, looking for negative correlations in their relative abundances would not be a meaningful measure of ecological associations. Moreover, it has been used in machine learning classification models with a good performance (Giliberti et al. 2022; Karwowska et al. 2025).

  • rank: Rank transformation replaces each feature abundance value by its rank. It is similar to relative rank transformation (rrank) which uses relative ranks. This has use, for instance, in non-parametric statistics.

  • rclr: The robust clr (rclr) is similar to regular clr (see above) but allows data with zeros and avoids the need to add pseudocount (Keshavan et al. 2010; Martino et al. 2019).

  • relabundance: Relative transformation, also known as normalizing as proportions, total sum scaling (TSS) and compositional transformation. This converts counts into proportions (on the scale [0, 1]) that sum up to 1. Much of the currently available taxonomic abundance data from high-throughput assays (16S, metagenomic sequencing) is compositional by nature, even if the data is provided as “counts” (Gloor et al. 2017).

  • standardize: Standardize (or z-score) transformation scales data to zero mean and unit variance. This is used to bring features (or samples) to more comparable levels in terms of mean and scale of the values. This can enhance visualization and interpretation of the data.

  • Other available transformations include chi-square (chi.square) (Legendre and Gallagher 2001), frequency transformation (frequency), and make margin sum of squares equal to one (normalize).

The statistical analysis of compositional data. Aitchison (1986). Chapman & Hall.
Compositional data analysis of microbiome and any-omics datasets: A validation of the additive logratio transformation. Greenacre et al. (2021). Front Microbiol 12. doi:10.3389/fmicb.2021.727398.
BiomeGPT: A foundation model for the human gut microbiome. Medearis et al. (2026). bioRxiv. doi:10.64898/2026.01.05.697599.
Ecologically meaningful transformations for ordination of species data. Legendre et al. (2001). Oecologia 129:271–280. doi:10.1007/s004420100716.
Matrix completion from a few entries. Keshavan et al. (2010). IEEE Trans Inf Theory 56:2980–2998. doi:10.1109/TIT.2010.2046205.
A novel sparse compositional technique reveals microbial perturbations. Martino et al. (2019). mSystems 4:e00016–19. doi:10.1128/mSystems.00016-19.

Transformations on abundance assays can be performed with the transformAssay() function from the mia package, keeping both the original and the transformed assay(s) in the data object. The function applies sample-wise or column-wise transformation when MARGIN = 'cols', feature-wise or row-wise transformation when MARGIN = 'rows'. A complete list of available transformations and parameters is available in the function help.

Important: Choosing a pseudocount

A pseudocount is a small non-negative value (e.g., 1) added to the normalized data to avoid taking the logarithm of zero. Its value can have a significant impact on the results when applying a logarithm transformation to normalized data, as the logarithm transformation is a nonlinear operation that can fundamentally change the data distribution (Costea et al. 2014).

The pseudocount should be chosen consistently across all normalization methods being compared, for example, by setting it to a value smaller than the minimum abundance value before transformation. Some tools, like ANCOMBC (Lin and Peddada 2020), take into account the effect of the pseudocount by performing sensitivity tests using multiple pseudocount values. See Chapter 15.

Analysis of compositions of microbiomes with bias correction. Lin et al. (2020). Nat Commun 11:3514. doi:10.1038/s41467-020-17041-7.
A fair comparison. Costea et al. (2014). Nat Methods 11:359. doi:10.1038/nmeth.2897.

10.3 In practice

Below, we apply relative transformation to the counts table.

# Load example data
library(mia)
data("Tengeler2020", package = "mia")
tse <- Tengeler2020

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

Get the values in the resulting assay, and view the first five rows and columns of it.

assay(tse, "relabundance")[1:5, 1:5]
##                     A110    A111     A12     A13     A14
##  Bacteroides     0.47393 0.28657 0.00000 0.22459 0.27397
##  Bacteroides_1   0.32230 0.00000 0.16664 0.07080 0.08503
##  Parabacteroides 0.00000 0.02390 0.00000 0.01400 0.02283
##  Bacteroides_2   0.00000 0.04709 0.00000 0.14019 0.10376
##  Akkermansia     0.03057 0.04659 0.07539 0.01489 0.01323

In the ‘pa’ transformation, the abundance table is converted to a presence/absence table that ignores abundances and only indicates whether the given feature is detected in the sample.

tse <- transformAssay(tse, method = "pa")
assay(tse, "pa")[1:5, 1:5]
##                  A110 A111 A12 A13 A14
##  Bacteroides        1    1   0   1   1
##  Bacteroides_1      1    0   1   1   1
##  Parabacteroides    0    1   0   1   1
##  Bacteroides_2      0    1   0   1   1
##  Akkermansia        1    1   1   1   1

You can now view the names of all assays in your data object with:

assayNames(tse)
##  [1] "counts"       "relabundance" "pa"

A common question is whether the centered log-ratio (clr) transformation should be applied directly to raw counts or if a prior transformation, such as conversion to relative abundances, is necessary.

In theory, the clr transformation is scale-invariant, meaning it does not matter whether it is applied to raw or relative abundances, as long as the relative scale of abundances remains the same. However, in practice, there are some differences due to the introduction of a pseudocount, which can introduce bias.

There is no single correct answer, but the following considerations may help:

  • Data imputation should typically be applied to raw abundances, regardless of the microbial profiling pipeline used or whether the obtained abundances are counts or relative abundances.

  • Once a pseudocount has been added, it makes no difference whether one first converts to relative abundances before applying clr or applies clr directly to the adjusted counts.

  • Since applying clr directly to raw counts is the simpler approach, it is generally recommended.

  • One might also consider using robust clr instead.

tse <- transformAssay(
    x = tse,
    assay.type = "counts",
    method = "clr",
    pseudocount = 0.5,
    name = "clr"
)

To incorporate phylogenetic information, one can apply the phylogenetic isometric log-ratio (philr) transformation (Egozcue et al. 2003; Silverman et al. 2017). Unlike standard transformations, philr accounts for the genetic relationships between taxonomic features. This is important because closely related species often share similar properties, which traditional transformations fail to capture.

Isometric logratio transformations for compositional data analysis. Egozcue et al. (2003). Mathematical Geology 35:279–300. doi:10.1023/a:1023818214614.
A phylogenetic transform enhances analysis of compositional microbiota data. Silverman et al. (2017). eLife 6:e21887. doi:10.7554/eLife.21887.
tse <- transformAssay(
    tse,
    method = "philr", MARGIN = "rows", pseudocount = 0.5
)

Unlike other transformations, philr outputs a table where rows represent nodes of phylogeny. These new features do not match the features of TreeSummarizedExperiment which is why this new dataset is stored into altExp.

altExp(tse, "philr")
##  class: TreeSummarizedExperiment 
##  dim: 149 27 
##  metadata(0):
##  assays(1): philr
##  rownames(149): node_1 node_2 ... node_148 node_149
##  rowData names(0):
##  colnames(27): A110 A111 ... A38 A39
##  colData names(4): patient_status cohort patient_status_vs_cohort
##    sample_name
##  reducedDimNames(0):
##  mainExpName: NULL
##  altExpNames(0):
##  rowLinks: NULL
##  rowTree: NULL
##  colLinks: NULL
##  colTree: NULL

10.4 Choosing a transformation

The most suitable transformation depends on the research question and the analysis method, and there is no single best choice. The table below lists common choices that are supported by benchmarking studies or widely used in the field, with links to the chapters where they are applied. They are reasonable starting points rather than strict rules.

Analysis Common choice Rationale
Alpha diversity Counts, rarefied if sequencing depths differ (Section 12.2.3); relative abundances when counts are not available Richness depends on sequencing depth (Schloss 2024a), and richness estimators such as Chao1 need counts. Shannon and Simpson indices depend only on the proportions, so they give the same result with relative abundances, such as the profiles from MetaPhlAn (Beghini et al. 2021), which are commonly used and do not include counts.
Beta diversity and ordination Relative abundances with Bray-Curtis; clr or rclr with Euclidean distance (Aitchison distance); presence/absence with Jaccard Each dissimilarity assumes a specific transformation; see the table in Chapter 13.
Differential abundance Relative abundances, analyzed with a non-parametric test or, after log transformation, with linear regression This has performed well in benchmarks on real data (Nearing et al. 2022; Yang and Chen 2022; Gamboa-Tuz et al. 2025; Pelto et al. 2025); see Section 15.2.
Correlation and cross-association, e.g. taxa vs. metabolites clr, or rclr when there are many zeros Log-ratios reduce the spurious correlations caused by compositionality (Gloor et al. 2017); see Chapter 17.
Heatmaps clr, then standardization of each feature (Z-transformation) Puts features with very different abundances on a comparable scale; see Section 11.2.
Supervised machine learning Relative abundances or presence/absence Simple transformations often perform as well as or better than compositional ones (Giliberti et al. 2022; Yerke et al. 2024; Karwowska et al. 2025); see the machine learning chapter in OMA extras.
Integrating taxonomic, functional, and strain-level profiling of diverse microbial communities with bioBakery 3. Beghini et al. (2021). eLife 10. doi:10.7554/elife.65088.
Microbiome differential abundance methods produce different results across 38 datasets. Nearing et al. (2022). Nat Commun 13:342. doi:10.1038/s41467-022-28034-z.
A comprehensive evaluation of microbial differential abundance analysis methods: Current status and potential solutions. Yang et al. (2022). Microbiome 10:130. doi:10.1186/s40168-022-01320-0.
Commonly used compositional data analysis implementations are not advantageous in microbial differential abundance analyses benchmarked against biological ground truth. Gamboa-Tuz et al. (2025). bioRxiv 2025.02.13.638109. doi:10.1101/2025.02.13.638109.
Elementary methods provide more replicable results in microbial differential abundance analysis. Pelto et al. (2025). Brief Bioinform 26:bbaf130. doi:10.1093/BIB/BBAF130.
Host phenotype classification from human microbiome data is mainly driven by the presence of microbial taxa. Giliberti et al. (2022). PLoS Comput Biol 18:e1010066. doi:10.1371/journal.pcbi.1010066.
Proportion-based normalizations outperform compositional data transformations in machine learning applications. Yerke et al. (2024). Microbiome 12:45. doi:10.1186/s40168-023-01747-z.
Effects of data transformation and model selection on feature importance in microbiome classification data. Karwowska et al. (2025). Microbiome 13. doi:10.1186/s40168-024-01996-6.

The transformation also determines how the values are interpreted:

  • Relative abundance is the proportion of a feature in a sample, which is easy to interpret but depends on the other features in the sample.
  • clr is the logarithm of a feature’s abundance relative to the geometric mean of all features in the sample. A positive value means that the feature is more abundant than an average feature in that sample. Because the reference is sample-specific, differences between samples are relative rather than absolute (Gloor et al. 2017).
  • rclr is interpreted like clr, but it is computed from the non-zero values only, and zeros are kept as missing values.
  • Presence/absence only tells whether a feature was detected, which makes it robust to differences in sequencing depth and to noise in the abundances.
Microbiome datasets are compositional: And this is not optional. Gloor et al. (2017). Front Microbiol 8:2224. doi:10.3389/fmicb.2017.02224.

For choosing the taxonomic level of the analysis, see Section 9.3.

10.5 Rarefaction

The number of taxa we observe in a sample depends strongly on how deeply the sample was sequenced. Sequencing depth (or library size, see Section 7.2.1) refers to the number of reads obtained for a sample. In practice, sequencing depth often varies substantially between samples, even within the same study.

A common way to visualize this relationship is with a rarefaction curve (Sanders 1968; Hurlbert 1971), which shows how the number of observed features increases as a function of the number of reads sampled (Figure 10.2).

library(mia)
library(vegan)

data("GlobalPatterns", package = "mia")
tse <- GlobalPatterns

mat <- tse |>
    assay("counts") |>
    t()
rarecurve(
    mat,
    step = 1000, label = FALSE,
    xlab = "Number of reads", ylab = "Number of observed taxa"
)
Line plot with sample size in reads on the x-axis and number of observed taxa on the y-axis, with one rising curve per sample that levels off at a different height and reaches a different maximum depth.
Figure 10.2: Rarefaction curves for the GlobalPatterns samples, showing the number of observed taxa as a function of the number of sampled reads. Each line represents one sample.

If a sample has not been sequenced deeply enough for its curve to approach saturation, its observed richness will be artificially low. This is not a biological signal: it is a measurement artifact caused by limited sampling.

This becomes problematic when samples are sequenced at different depths. Samples with larger library sizes tend to show more observed taxa simply because more reads were collected, not because their microbial communities are truly more diverse. Consequently, variation in sequencing depth can bias commonly used alpha and beta diversity metrics (Schloss 2024a).

To inspect the depth variation in the data, we can compute and visualize total counts per sample (Figure 10.3).

library(miaViz)

tse <- addQC(tse, assay.type = "counts")

plotBoxplot(tse, col.var = "total", x = "SampleType") +
    scale_y_continuous(labels = scales::comma) +
    labs(x = "Sample type", y = "Library size")
Boxplots of total counts per sample (y-axis) for each sample type (x-axis), with the individual samples drawn as points.
Figure 10.3: Library sizes (total counts per sample) in the GlobalPatterns dataset, grouped by sample type.

We can also quantify the spread in sequencing depth:

# Calculate variation between highest and lowest sequencing depth
depth_variation <- max(tse[["total"]]) / min(tse[["total"]])
depth_variation
##  [1] 40.16

This dataset shows up to a 40-fold difference in sequencing depth across samples.

To mitigate bias from uneven sequencing depths, rarefaction has been proposed (Sanders 1968; Hurlbert 1971) and recently re-evaluated (Schloss 2024a, 2024b). Rarefaction standardizes sequencing depth by randomly subsampling reads so that all retained samples have the same total number of reads.

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.

Conceptually, the workflow is:

  1. Choose a rarefaction depth (often the minimum library size across samples, here 58,688).
  2. Discard samples with fewer reads than this depth.
  3. For each remaining sample, randomly subsample exactly that many reads.

In mia, rarefaction can be applied directly to an assay:

tse_rarefy <- rarefyAssay(
    tse,
    assay.type = "counts"
)
tse_rarefy
##  class: TreeSummarizedExperiment 
##  dim: 12807 26 
##  metadata(0):
##  assays(2): counts subsampled
##  rownames(12807): 549322 951 ... 200359 271582
##  rowData names(7): Kingdom Phylum ... Genus Species
##  colnames(26): CL3 CC1 ... Even2 Even3
##  colData names(17): X.SampleID Primer ... q75 q100
##  reducedDimNames(0):
##  mainExpName: NULL
##  altExpNames(0):
##  rowLinks: a LinkDataFrame (12807 rows)
##  rowTree: 1 phylo tree(s) (19216 leaves)
##  colLinks: NULL
##  colTree: NULL

There has been a long-lasting controversy surrounding the use of rarefaction in microbial ecology. The main concern is that subsampling would omit data (McMurdie and Holmes 2014; Schloss 2024b), which is why rarefaction is generally discouraged for differential abundance testing performed on a single rarefied table (McMurdie and Holmes 2014).

Waste not, want not: Why rarefying microbiome data is inadmissible. McMurdie et al. (2014). PLoS Comput Biol 10:e1003531. doi:10.1371/journal.pcbi.1003531.
Waste not, want not: Revisiting the analysis that called into question the practice of rarefaction. Schloss (2024b). mSphere 9:e00355–23. doi:10.1128/msphere.00355-23.
Rarefaction is currently the best approach to control for uneven sequencing effort in amplicon sequence analyses. Schloss (2024a). mSphere 9:e00354–23. doi:10.1128/msphere.00354-23.
Rarefaction is better than robust Aitchison PCA and other compositional data analysis methods at controlling for uneven sequencing effort. Schloss (2026). mSystems 11:e00930–26. doi:10.1128/msystems.00930-26.

However, this concern is reduced when rarefaction is treated as a repeated resampling step rather than a one-off subsample. By rarefying to the minimum library size and repeating the procedure many times, we compute the diversity metric (e.g., alpha or beta diversity) for each iteration and average across iterations, yielding a stable estimate at a common sequencing effort (Schloss 2024a, 2024b). Patrick Schloss has demonstrated that this repeated rarefaction procedure is “the only method that could control for variation in uneven sequencing effort when measuring commonly used alpha and beta diversity metrics” (Schloss 2024a). The relative benefits of rarefaction and of robust Aitchison PCA and other compositional data analysis methods in controlling for uneven sequencing effort are currently being debated (Schloss 2026).

Section 12.2.3 demonstrates rarefaction for calculating alpha diversity, and Section 13.4.2 extends the approach to beta diversity.

Summary

Microbiome data is characterized by the following features:

  • Compositionality
  • High variability
  • Zero-inflation

OSCA book provides additional information on normalization from the perspective of single-cell analysis.

10.6 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: Compositionality and zeros

Goal: Explain why microbiome data needs to be transformed.

Imagine the true number of cells of three taxa in two samples. Between the samples, only Taxon 1 has changed:

Taxon Sample A Sample B
Taxon 1 100 300
Taxon 2 100 100
Taxon 3 200 200

Answer the following questions without writing any code. The sections “Why transform the data” and “Common methods” will help you.

  1. Calculate the relative abundances of the taxa in both samples.

  2. Which taxa have changed in their absolute abundance? Which taxa seem to change when you look at the relative abundances? What is this property of the data called?

  3. Sequencing gives a number of reads that does not depend on the number of cells in the original sample. Why can the raw counts of a taxon not be compared directly between samples?

  4. The clr transformation takes the logarithm of the abundances. Why is this a problem with microbiome data, and how can the problem be avoided?

  1. The relative abundance is the count of a taxon divided by the total count of the sample. In Sample A, the relative abundances are 100 / 400 = 0.25, 0.25 and 0.5. In Sample B, they are 300 / 600 = 0.5, 100 / 600 = 0.17 and 200 / 600 = 0.33.

  2. Only Taxon 1 has changed in absolute abundance. However, the relative abundances of all three taxa change, because they always sum up to 1. When Taxon 1 increases, the proportions of the other taxa must decrease. This is called compositionality.

  3. The number of reads depends on the sequencing, not on the number of microbes in the sample. A taxon can have more reads in one sample just because that sample was sequenced more deeply. Transformations such as relative abundance or clr make the samples comparable.

  4. Microbiome data is zero-inflated: most of the values are often zeros, and the logarithm of zero is not defined. A common solution is to add a small pseudocount to all values before the transformation. Another solution is the robust clr (rclr) transformation, which does not need a pseudocount.

Exercise 2: Relative abundance and presence/absence

Goal: Transform an assay with transformAssay() and find the transformed values.

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

  2. Transform the counts assay into relative abundances.

  3. Show the first five rows and columns of the relabundance assay.

  4. Calculate the sum of the relative abundances in each sample, that is, the column sums of the relabundance assay. What values do you get, and why?

  5. Apply the presence/absence (pa) transformation to the counts assay and show the first five rows and columns of the pa assay. What do the values mean?

  6. List the names of all assays in tse. Was the original counts assay kept?

Useful functions: data(), mia::transformAssay(), assay(), head(), colSums(), assayNames()

library(mia)

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

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

# 3. First rows of the relabundance assay
assay(tse, "relabundance")[1:5, 1:5]
##                     A110    A111     A12     A13     A14
##  Bacteroides     0.47393 0.28657 0.00000 0.22459 0.27397
##  Bacteroides_1   0.32230 0.00000 0.16664 0.07080 0.08503
##  Parabacteroides 0.00000 0.02390 0.00000 0.01400 0.02283
##  Bacteroides_2   0.00000 0.04709 0.00000 0.14019 0.10376
##  Akkermansia     0.03057 0.04659 0.07539 0.01489 0.01323

# 4. Sum of relative abundances in each sample
colSums(assay(tse, "relabundance")) |> head()
##  A110 A111  A12  A13  A14  A15 
##     1    1    1    1    1    1

# 5. Presence/absence transformation
tse <- transformAssay(tse, assay.type = "counts", method = "pa")
assay(tse, "pa")[1:5, 1:5]
##                  A110 A111 A12 A13 A14
##  Bacteroides        1    1   0   1   1
##  Bacteroides_1      1    0   1   1   1
##  Parabacteroides    0    1   0   1   1
##  Bacteroides_2      0    1   0   1   1
##  Akkermansia        1    1   1   1   1

# 6. Assay names
assayNames(tse)
##  [1] "counts"       "relabundance" "pa"
  1. Every sample sums up to 1. The relative abundance transformation divides each count by the total count of the sample, so the values are proportions of the sample.

  2. A value of 1 means that the feature is detected in the sample, and 0 means that it is not. The abundances are ignored.

  3. Yes. transformAssay() adds the transformed values as a new assay and keeps the original assays in the object.

Exercise 3: Centered log-ratio transformation

Goal: Apply the clr transformation and explain the role of the pseudocount.

  1. Check whether the counts assay contains zeros.

  2. Apply the clr transformation to the counts assay. Add a pseudocount of 0.5, and name the new assay "clr".

  3. Show the first five rows and columns of the clr assay and compare them with those of the counts assay. What happened to the zeros?

  4. Why should the same pseudocount be used when you compare different transformations?

Useful functions: assay(), any(), mia::transformAssay()

# 1. Check for zeros
any(assay(tse, "counts") == 0)
##  [1] TRUE

# 2. clr transformation with a pseudocount
tse <- transformAssay(
    tse,
    assay.type = "counts",
    method = "clr",
    pseudocount = 0.5,
    name = "clr"
)

# 3. Compare clr values with counts
assay(tse, "clr")[1:5, 1:5]
##                    A110   A111    A12   A13   A14
##  Bacteroides      8.250  7.973 -2.264 7.378 6.543
##  Bacteroides_1    7.865 -2.082  6.322 6.224 5.374
##  Parabacteroides -2.226  5.489 -2.264 4.604 4.061
##  Bacteroides_2   -2.226  6.167 -2.264 6.907 5.573
##  Akkermansia      5.509  6.157  5.529 4.665 3.518
assay(tse, "counts")[1:5, 1:5]
##                   A110  A111  A12  A13  A14
##  Bacteroides     17722 11630    0 8806 1740
##  Bacteroides_1   12052     0 2679 2776  540
##  Parabacteroides     0   970    0  549  145
##  Bacteroides_2       0  1911    0 5497  659
##  Akkermansia      1143  1891 1212  584   84
  1. The pseudocount is added to all values before the logarithm is taken, so the zeros become small positive values and get a clr value. The clr values are on a logarithmic scale and centered within each sample: a positive value means that the feature is more abundant than the average feature of the sample (on the log scale), and a negative value means that it is less abundant.

  2. The logarithm is a nonlinear operation, so the size of the pseudocount can change the distribution of the transformed values considerably. If different pseudocounts were used, the differences between the results could be caused by the pseudocounts and not by the transformations.

Exercise 4: Phylogenetic transformation

Goal: Apply the phILR transformation and find where the result is stored.

  1. Apply the phILR transformation to tse. Use MARGIN = "rows" and add a pseudocount of 0.5.

  2. List the assay names and the alternative experiment names of tse. Where was the transformed data stored?

  3. Retrieve the phILR-transformed data from the alternative experiments. Compare its number of rows and its first row names with those of tse. Why do they differ?

Useful functions: mia::transformAssay(), assayNames(), altExpNames(), altExp(), nrow(), rownames(), head()

# 1. phILR transformation
tse <- transformAssay(
    tse,
    method = "philr", MARGIN = "rows", pseudocount = 0.5
)

# 2. Assays and alternative experiments
assayNames(tse)
##  [1] "counts"       "relabundance" "pa"           "clr"
altExpNames(tse)
##  [1] "philr"

# 3. Compare the features
tse_philr <- altExp(tse, "philr")
nrow(tse)
##  [1] 151
nrow(tse_philr)
##  [1] 149
rownames(tse) |> head()
##  [1] "Bacteroides"     "Bacteroides_1"   "Parabacteroides" "Bacteroides_2"  
##  [5] "Akkermansia"     "Bacteroides_3"
rownames(tse_philr) |> head()
##  [1] "node_1" "node_2" "node_3" "node_4" "node_5" "node_6"
  1. The result was not added as an assay but as an alternative experiment called "philr".

  2. In the phILR-transformed data, the rows represent the internal nodes (balances) of the phylogenetic tree, not the original features. The rows no longer match the features of tse, so the data cannot be stored as an assay of tse. Alternative experiments can have different features than the main experiment, as long as the samples are the same.

Exercise 5: Sequencing depth and rarefaction

Goal: Examine variation in sequencing depth and rarefy the data.

  1. Draw rarefaction curves for the samples from the counts assay. Use a step size of 100 reads.

  2. Calculate the library size of each sample and add it to colData.

  3. Visualize the library sizes as boxplots, with one box for each group in patient_status.

  4. Calculate how many times larger the largest library is than the smallest library.

  5. Rarefy the counts assay to the smallest library size, which is the default. Store the result in a variable called tse_rarefied, and list its assay names.

  6. Calculate the library sizes of the rarefied assay. What do you notice?

  7. How do you read a rarefaction curve? What does it mean if a curve has not leveled off?

  8. What is the main criticism of rarefaction, and how can it be reduced when calculating diversity metrics?

Useful functions: assay(), t(), vegan::rarecurve(), mia::addQC(), miaViz::plotBoxplot(), max(), min(), mia::rarefyAssay(), assayNames(), colSums(), head()

library(vegan)
library(miaViz)

# 1. Rarefaction curves
mat <- tse |>
    assay("counts") |>
    t()
rarecurve(
    mat,
    step = 100, label = FALSE,
    xlab = "Number of reads", ylab = "Number of observed taxa"
)


# 2. Library sizes
tse <- addQC(tse, assay.type = "counts")

# 3. Library sizes by group
plotBoxplot(tse, col.var = "total", x = "patient_status") +
    labs(x = "Patient status", y = "Library size")


# 4. Ratio between the largest and smallest library
max(tse$total) / min(tse$total)
##  [1] 22.9

# 5. Rarefy the counts
tse_rarefied <- rarefyAssay(tse, assay.type = "counts")
assayNames(tse_rarefied)
##  [1] "counts"       "relabundance" "pa"           "clr"         
##  [5] "subsampled"

# 6. Library sizes after rarefaction
colSums(assay(tse_rarefied, "subsampled")) |> head()
##  A110 A111  A12  A13  A14  A15 
##  1772 1772 1772 1772 1772 1772
  1. The rarefied values are stored in the subsampled assay. Every sample now has the same number of reads, which equals the smallest library size, because the reads of each sample were randomly subsampled to that depth.

  2. A rarefaction curve shows how many features are observed when an increasing number of reads is sampled. If a curve levels off, sequencing more reads would reveal only few new features, so the sample was sequenced deeply enough. If a curve is still rising at its end, the observed richness of the sample is underestimated because of limited sequencing depth.

  3. Rarefaction discards reads, so part of the data is not used. When rarefaction is repeated many times and the diversity metric is averaged over the iterations, the estimate becomes stable and less data is effectively lost.

Back to top