7  Exploration & quality control

This chapter focuses on the quality control (QC) and exploration of microbiome data and establishes commonly used descriptive summaries. Familiarizing yourself with the peculiarities of a given dataset is essential for data analysis and model building to make justified conclusions.

The dataset should not suffer from severe technical biases, and you should at least be aware of potential challenges, such as outliers, biases, unexpected patterns, and so forth. Standard summaries and visualizations can help, and the rest comes with experience. Moreover, exploration and QC often entail iterative processes.

There are available guidelines for QC, for instance, as described by Zuur et al. (2010). However, it should be noted that one should not follow any protocols strictly but rather use them as a template and customize them to one’s dataset. The goal of QC is not only to improve quality of data, but also to understand it and its limitations. Poor data quality leads to poor results, which is illustrated by a common expression in computer science:

A protocol for data exploration to avoid common statistical problems. Zuur et al. (2010). Methods Ecol Evol 1:3–14. doi:10.1111/j.2041-210X.2009.00001.x.

“Garbage in, garbage out”

Below we download the baboon gut dataset (Grieneisen et al. 2021) (Section D.8) from microbiomeDataSets.

Gut microbiome heritability is nearly universal but environmentally contingent. Grieneisen et al. (2021). Science 373:181–186. doi:10.1126/science.aba5483.
library(microbiomeDataSets)
tse <- baboongut()

7.1 Summarize data

When you first get your hands dirty with the data, the first step is to summarize it and get a sense of what kind of data you’re dealing with. Printing the TreeSummarizedExperiment object (Huang et al. 2021) already provides useful information about the dataset’s dimensions, such as the number of samples and taxonomic features.

TreeSummarizedExperiment: A S4 class for data with hierarchical structure [version 2; peer review: 3 approved]. Huang et al. (2021). F1000Res 9:1246. doi:10.12688/f1000research.26669.2.
tse
##  class: TreeSummarizedExperiment 
##  dim: 613 16234 
##  metadata(0):
##  assays(1): counts
##  rownames(613): asv_10002 asv_10020 ... asv_9990 asv_9991
##  rowData names(7): Domain Phylum ... Genus ASV
##  colnames(16234): sample_11410-AACTCCTGTGGA-396
##    sample_11413-CGGCCTAAGTTC-397 ... sample_11413-ACCCTCAGCCCA-397
##    sample_12049-TCAGCAAATGGT-407
##  colData names(35): sample baboon_id ... pc4_bc pc5_bc
##  reducedDimNames(0):
##  mainExpName: NULL
##  altExpNames(0):
##  rowLinks: a LinkDataFrame (613 rows)
##  rowTree: 1 phylo tree(s) (613 leaves)
##  colLinks: NULL
##  colTree: NULL
##  referenceSeq: a DNAStringSet (613 sequences)

The dataset includes 613 features identified from 16234 samples. mia provides the summary() function for TreeSummarizedExperiment objects which returns the summary of counts for all samples and features including measures of central tendency.

library(mia)

# Calculate summary tables
summary(tse, assay.type = "counts")
##  $samples
##  # A tibble: 1 × 6
##    total_counts min_counts max_counts median_counts mean_counts stdev_counts
##           <dbl>      <dbl>      <dbl>         <dbl>       <dbl>        <dbl>
##  1    787665544        874     467725         47009      48519.       19089.
##  
##  $features
##  # A tibble: 1 × 3
##    total singletons per_sample_avg
##    <int>      <int>          <dbl>
##  1   613          0           209.

The returned tables show that samples exhibit lots of variance in library sizes. Moreover, we can observe that there are no singletons in the dataset (library size and singletons are discussed in more detail in Section 7.2).

Another type of summary can be generated using the summarizeDominance() function. This function identifies the most abundant taxon in each sample and summarizes these results across the entire dataset. It returns a table displaying both the absolute count and the relative frequency (proportion of samples) of each dominant taxon. Below, we create a summary table for genera.

df <- summarizeDominance(tse, rank = "Genus")
df
##  # A tibble: 43 × 3
##    dominant_taxa                   n rel_freq
##    <chr>                       <int>    <dbl>
##  1 Bifidobacterium             11160  0.687  
##  2 Prevotella 9                 2141  0.132  
##  3 Rikenellaceae RC9 gut group  1555  0.0958 
##  4 Candidatus Methanogranum      460  0.0283 
##  5 Megasphaera                   246  0.0152 
##  6 CAG-873                       138  0.00850
##  # ℹ 37 more rows

Based on the summary table, Bifidobacterium appears dominant in a large portion of samples.

mia also provides other functions to summarize the dataset. For example, you can retrieve unique, top, prevalent, or rare features using getUnique(), getTop(), getPrevalent(), and getRare(), respectively.

Let’s first check which phyla are included in the dataset.

uniq <- getUnique(tse, rank = "Phylum")
uniq
##   [1] <NA>               Tenericutes        Firmicutes        
##   [4] Lentisphaerae      Actinobacteria     Elusimicrobia     
##   [7] Kiritimatiellaeota Euryarchaeota      Bacteroidetes     
##  [10] Spirochaetes       Proteobacteria     Epsilonbacteraeota
##  [13] Cyanobacteria     
##  42 Levels: Acidobacteria Actinobacteria Aquificae ... WS4

There are 12 phyla (plus unassigned NA) present in the dataset.

Next, we might be interested in assessing which features are the most abundant. This can be done by utilizing the getTop() function. Below, we pick the top 10 taxonomic features, which are determined based on median abundance.

# Pick the top taxa
top_features <- getTop(tse, method = "median", top = 10)
top_features
##   [1] "asv_8243" "asv_1543" "asv_1874" "asv_9331" "asv_4629" "asv_3018"
##   [7] "asv_2919" "asv_3109" "asv_9212" "asv_7528"

These ten features have the highest median abundance across all samples. getPrevalent() differs from getTop() in that it retrieves which features exceed the specified prevalence and detection thresholds. Here we determine prevalent genera.

prev <- getPrevalent(tse, rank = "Genus", prevalence = 0.2, detection = 0)
prev |> head()
##  [1] "Acidaminococcus"   "Alloprevotella"    "Anaerosporobacter"
##  [4] "Bifidobacterium"   "Brachyspira"       "Butyricicoccus"

Out of 92 genera, 78 of them are detected to be prevalent, meaning they are found in a sufficient number of samples with sufficiently high abundance.

The getRare() function is the counterpart of getPrevalent(). It returns those features that do not exceed the thresholds.

rare <- getRare(tse, rank = "Genus", prevalence = 0.2, detection = 0)
rare |> head()
##  [1] "Acetitomaculum"               "Acholeplasma"                
##  [3] "Candidatus Soleaferrea"       "Catenibacterium"             
##  [5] "Cellulosilyticum"             "Lachnospiraceae NC2004 group"

It returns 14 features, which is expected, as it should match the number of genera after subtracting the prevalent ones.

7.2 Problematic features

Outliers are observations that deviate significantly from the rest of the data. Researchers should be cautious when handling outliers, as what appears to be an outlier may actually result from a valid biological mechanism. This is especially relevant in the microbiome field, where sequenced counts often exhibit seemingly irregular variation. In such cases, transformations (see Chapter 10) are typically the preferred approach for handling these observations. However, if an observation or sample is significantly affected by measurement error, removing it may be a reasonable option. The approach to dealing with outliers in each dataset requires careful consideration by the researcher.

Singletons are sequences that appear only once in a dataset, meaning they are observed in just a single sequencing read. Often rare features are removed from the data, as they usually represent sequencing artifacts. See Section 8.6 and Section 8.6.1 for more details on prevalence filtering and agglomeration.

7.2.1 Library size

Library size refers to the total number of counts found in a single sample. The returned tables in Section 7.1 showed that samples exhibit lots of variance in library sizes. We can then visualize the library sizes. The total counts per sample can be calculated using addQC() from mia. It adds the library size (total) and other sample-level metrics to colData.

# Calculate and add total counts to colData
tse <- addQC(tse)

The results are stored in colData. We can then visualize these results with a box plot and histogram (Figure 7.1).

library(miaViz)
library(patchwork)

p1 <- plotBoxplot(tse, col.var = "total", x = "sex", add.points = FALSE) +
    scale_y_continuous(labels = scales::comma) +
    labs(x = "Sex", y = "Library size")
p2 <- plotHistogram(tse, col.var = "total") +
    scale_x_continuous(labels = scales::comma) +
    labs(x = "Library size", y = "Number of samples")

p1 + p2
Two panels. Left: box plots of total counts per sample, one for each sex. Right: histogram of total counts across samples, which is skewed to the right.
Figure 7.1: Library sizes (total counts per sample) in the baboon gut data. Left: box plot of library size by sex. Right: histogram of library sizes across samples.

As Figure 7.1 shows, the distribution of library size is right-skewed: most samples have library sizes between about 20,000 and 80,000, but a long tail of samples has much larger library sizes. This might be caused by technical variations or biological factors.

Nevertheless, the most important check is to ensure that the sampling depth is sufficient. In case of insufficient sampling depth, one might consider filtering the data based on library size (Section 8.4).

To control uneven sampling depths, one should apply data transformation or apply rarefaction. Both approaches are discussed in Section 10.5.

7.2.2 Contaminant sequences

Samples might be contaminated with exogenous sequences. The impact of each contaminant can be estimated based on its frequencies and concentrations across the samples.

The following mia functions wrap the decontam methods (Davis et al. 2018) for SummarizedExperiment objects and support such functionality:

Simple statistical identification and removal of contaminant sequences in marker-gene and metagenomics data. Davis et al. (2018). Microbiome 6:226. doi:10.1186/s40168-018-0605-2.

Contaminations can be detected using two main approaches: frequency-based and prevalence-based testing. In frequency-based testing, the user must provide the DNA concentration of samples. The abundance of features is then compared to the DNA concentration, as contaminants are expected to show an inverse relationship — they make up a larger fraction in low-DNA samples and a smaller fraction in high-DNA samples.

In the prevalence-based approach, sequence prevalence is compared between true biological samples and control samples. This method assumes that contaminants are more prevalent in negative controls, as these lack true biological DNA and primarily contain background noise from contamination sources.

The dataset contains DNA concentration recorded in the post_pcr_dna_ng column in the sample metadata. This information can be used for frequency-based contamination identification.

library(knitr)

colData(tse)[, c("baboon_id", "sex", "age", "post_pcr_dna_ng")] |>
    head() |>
    kable()
baboon_id sex age post_pcr_dna_ng
sample_11410-AACTCCTGTGGA-396 Baboon_1 M 8.375 78.98
sample_11413-CGGCCTAAGTTC-397 Baboon_1 M 8.123 49.70
sample_11409-CAGAAGGTGTGG-395 Baboon_1 M 8.778 59.16
sample_11412-AAGGCCTTTACG-397 Baboon_1 M 8.638 46.91
sample_11409-GTTGCTGAGTCC-395 Baboon_1 M 8.816 50.14
sample_11408-GGTCTTAGCACC-395 Baboon_1 M 8.542 46.91

Now we can detect contaminant sequences. We run addContaminantQC() which adds results to rowData.

tse <- addContaminantQC(tse, concentration = "post_pcr_dna_ng")

rowData(tse) |>
    head() |>
    kable()
Domain Phylum Class Order Family Genus ASV freq prev p.freq p.prev p contaminant
asv_10002 Bacteria NA NA NA NA NA asv_10002 0.0003 3355 0.6914 NA 0.6914 FALSE
asv_10020 Bacteria Tenericutes Mollicutes Mollicutes RF39 NA NA asv_10020 0.0001 2511 0.7099 NA 0.7099 FALSE
asv_10027 Bacteria Tenericutes Mollicutes Mollicutes RF39 NA NA asv_10027 0.0001 2835 0.7766 NA 0.7766 FALSE
asv_10036 Bacteria Tenericutes Mollicutes Mollicutes RF39 NA NA asv_10036 0.0016 8633 0.7051 NA 0.7051 FALSE
asv_10052 NA NA NA NA NA NA asv_10052 0.0001 2833 0.7341 NA 0.7341 FALSE
asv_10072 Bacteria Firmicutes Clostridia Clostridiales Ruminococcaceae Ruminiclostridium 6 asv_10072 0.0001 2138 0.6394 NA 0.6394 FALSE

The method performs statistical tests to identify contaminants. By default, it uses a 0.1 probability threshold for identifying contaminants, which can be adjusted as needed. In this case, 0% of sequences were detected to be contaminants. If any are detected, they can be filtered out from the data.

tse <- tse[!rowData(tse)[["contaminant"]], ]

As an example, we also demonstrate how to apply the prevalence-based approach. Note that the data used here is arbitrary, and in practice, you should use real control sample information.

First, we add arbitrary control samples:

set.seed(123)
control <- rep(FALSE, ncol(tse))
control[sample(seq_len(ncol(tse)), 1)] <- TRUE
tse[["control"]] <- control

Next, we perform the analysis. Note that we could have applied both frequency-based and prevalence-based methods simultaneously by specifying the method parameter in the previous step.

not_contaminant <- isNotContaminant(tse, control = "control", detailed = FALSE)
not_contaminant |> head()
##  [1] TRUE TRUE TRUE TRUE TRUE TRUE

To identify non-contaminant sequences with the prevalence approach, a threshold of 0.5 is used, by default. As noted in the previous step, the add*() functions add results to rowData. Here, we used a function that returns only the results. By specifying detailed = FALSE, we obtain the results as a vector, which can then be used for subsetting the data.

7.3 Data distribution

Microbiome count data is rarely normally distributed (see Section 10.1). However, many common statistical tests assume normality and using them while violating the assumptions might lead to incorrect conclusions. While several tests for normality exist — such as Shapiro-Wilk test (Shapiro and Wilk 1965) — they do not replace visual observation.

An analysis of variance test for normality (complete samples). Shapiro et al. (1965). Biometrika 52:591–611. doi:10.1093/biomet/52.3-4.591.

The plotHistogram() function provides an easy way to visualize the counts distribution with a histogram (Figure 7.2).

plotHistogram(tse, assay.type = "counts") +
    scale_x_continuous(
        transform = "log1p", breaks = c(0, 10^(1:5)), labels = scales::comma
    ) +
    scale_y_continuous(labels = scales::comma) +
    labs(x = "Count", y = "Number of values")
Histogram of count values on a log-scaled x-axis with a very tall bar at zero and a long, thin tail towards large counts.
Figure 7.2: Histogram of all values in the counts assay of the baboon gut data, showing the zero-inflated, right-skewed distribution of microbiome counts. The x-axis is log-scaled.

The microbiome data is typically zero-inflated, meaning that there are lots of zeros. The same method can also be used to visualize continuous variables from colData. For categorical values, one can utilize plotBarplot() (Figure 7.3).

p1 <- plotHistogram(tse, col.var = "age") +
    labs(x = "Age", y = "Number of samples")
p2 <- plotBarplot(tse, col.var = "sex") +
    labs(x = "Sex", y = "Number of samples")

p1 + p2
Two panels. Left: histogram of sample age. Right: bar chart with one bar per sex showing the number of samples.
Figure 7.3: Distribution of sample metadata in the baboon gut data. Left: histogram of age. Right: bar plot of the number of samples per sex.

7.3.1 Abundance

Abundance visualization is an important data exploration approach. The plotAbundanceDensity() function generates a plot to visualize the most abundant taxonomic features along with several options.

Next, a few demonstrations are shown using the baboon gut data. A jitter plot based on relative abundance data, similar to the one presented by Salosensaari et al. (2021) (Supplementary Fig. 1), can be visualized as follows (Figure 7.4):

Taxonomic signatures of cause-specific mortality risk in human gut microbiome. Salosensaari et al. (2021). Nat Commun 12:2671. doi:10.1038/s41467-021-22962-y.
# Add relative abundances
tse <- transformAssay(tse, method = "relabundance")

plotAbundanceDensity(
    tse,
    layout = "jitter",
    assay.type = "relabundance",
    n = 40,
    # Very transparent points show where the ~16,000 samples concentrate
    point.size = 0.5, point.shape = 19, point.alpha = 0.02
) +
    scale_x_log10(labels = scales::percent) +
    labs(x = "Relative abundance")
Jitter plot with the 40 most abundant taxonomic features as rows on the y-axis and relative abundance on a logarithmic x-axis in percent. Each faint point is one sample's abundance of that feature.
Figure 7.4: Jitter plot of the relative abundances of the 40 most abundant taxonomic features in the baboon gut data. The x-axis shows relative abundance on a log scale and each point is one sample.

The relative abundance values for the top-5 taxonomic features can be visualized as a density plot over a log-scaled axis, with “sex” indicated by colors (Figure 7.5):

plotAbundanceDensity(
    tse,
    layout = "density",
    assay.type = "relabundance",
    n = 5, colour.by = "sex"
) +
    scale_x_log10() +
    labs(x = "Relative abundance", colour = "Sex", fill = "Sex")
Density curves of relative abundance on a logarithmic x-axis for each of the five most abundant taxonomic features, with separate curves colored by sex.
Figure 7.5: Density plot of the relative abundances of the five most abundant taxonomic features on a log-scaled x-axis, with colors indicating sex.

Alternatively, the plotBoxplot() function from the miaViz package can be used to visualize the abundances of taxonomic features with box plots. Below, we visualize top-10 features, selected based on their mean abundance (Figure 7.6).

library(miaViz)

# Select top features
top <- getTop(tse, top = 10L, method = "mean")

plotBoxplot(
    tse,
    assay.type = "relabundance",
    features = top,
    x = "sex",
    fill.by = "sex",
    facet.by = "rownames",
    add.points = FALSE
) +
    scale_y_log10() +
    labs(x = "Sex", y = "Relative abundance", fill = "Sex")
Ten panels, one per taxonomic feature, each with box plots comparing the two sexes on the x-axis with relative abundance on a logarithmic y-axis.
Figure 7.6: Box plots of the relative abundances (log scale) of the ten taxonomic features with the highest mean abundance, shown separately for each sex.

7.3.2 Prevalence

Prevalence quantifies the frequency of samples where certain microbes were detected (above a given detection threshold). Prevalence can be given as sample size (N) or percentage (unit interval).

Investigating prevalence allows you either to focus on changes which pertain to the majority of the samples, or identify rare microbes, which may be conditionally abundant in a small number of samples.

We can plot a histogram of the prevalence of features. This would tell us whether there are many features present in most of the samples or if there are mostly rare taxonomic features. The population prevalence (frequency) at a 0.1% relative abundance threshold (detection = 0.1/100 and as.relative = TRUE) can look like Figure 7.7.

# Add prevalence of features
tse <- addPrevalence(tse, detection = 0.1 / 100, as.relative = TRUE)

# Plot them with a histogram
plotHistogram(tse, row.var = "prevalence") +
    labs(x = "Prevalence", y = "Number of features")
Histogram of prevalence values from 0 to 1 across taxonomic features. Most features fall at low prevalence, meaning they are detected in a minority of samples.
Figure 7.7: Histogram of feature prevalence, i.e. the proportion of samples in which each taxonomic feature exceeds a 0.1% relative abundance detection threshold.

Most of the features are present only in a minority of the samples with a specified abundance threshold. A similar conclusion can be made with visualizations generated with the plotPrevalentAbundance() or plotRowPrevalence() functions (Figure 7.8).

p1 <- plotPrevalentAbundance(tse, assay.type = "relabundance") +
    scale_x_log10()

# Remove y axis text as there are so many features that one cannot read them
p2 <- plotRowPrevalence(
    tse,
    assay.type = "relabundance",
    detection = c(0.0001, 0.001, 0.01, 0.1)
) +
    theme(
        axis.text.y = element_blank(),
        axis.ticks.y = element_blank()
    )

p1 + p2
Two panels. Left: scatter plot of features with relative abundance on the x-axis and prevalence on the y-axis, where most points lie at low abundance. Right: a dense tile plot with detection thresholds on the x-axis and the features on the y-axis, shaded by prevalence.
Figure 7.8: Prevalence and abundance of taxonomic features. Left: prevalence plotted against relative abundance for each feature. Right: prevalence of each feature across detection thresholds, with feature names on the y-axis omitted.

The plots above show that most of the taxonomic features are present with low abundance. However, there are a couple of features that are both highly abundant and prevalent in the dataset.

The figures also show the overall trend that most microbes are low in abundance and occur in a limited number of samples. This is a typical pattern in microbiome datasets, and can be further visualized as follows (Figure 7.9).

plotPrevalence(
    tse,
    assay.type = "relabundance",
    detection = c(0.0001, 0.001, 0.01, 0.1)
) +
    scale_x_log10()
Line plot with relative abundance detection thresholds on the x-axis and the number of taxonomic features on the y-axis, one line per prevalence level colored on a purple-to-yellow scale. The number of features drops as the detection threshold increases.
Figure 7.9: Number of taxonomic features that exceed each relative abundance detection threshold (x-axis), shown as one line per prevalence level (colors).

The plot shows how many features exceed each detection threshold in at least the given proportion of samples. The number drops quickly as either the detection threshold or the prevalence level (from purple to yellow) increases: only a few features are both abundant and prevalent.

To analyze how much the core taxonomic features are present in samples, we can calculate how large a proportion of each sample the core features make up. We can then visualize this distribution again with a histogram (Figure 7.10).

# Calculate the proportion of core taxa
tse <- addPrevalentAbundance(tse, prevalence = 50 / 100, detection = 0.1 / 100)

# Visualize
plotHistogram(tse, col.var = "prevalent_abundance") +
    labs(x = "Abundance of core features", y = "Number of samples")
Histogram of the proportion of each sample made up by core taxonomic features, with the proportion on the x-axis and the number of samples on the y-axis.
Figure 7.10: Histogram of the proportion of each sample made up by core taxonomic features, defined with 50% prevalence and 0.1% detection thresholds.

The histogram shows how many samples have a given proportion of core features. A value close to 1 means that the sample consists mostly of core features, while a small value means that most of the sample consists of features that are not common in the dataset.

7.4 Collinearity

Microbial species are rarely independent; rather, they influence each other’s abundance through complex networks of competition and symbiosis. Collinearity occurs when information from one variable is already included in some other variable. Modeling variables that exhibit collinearity can lead to issues such as reduced interpretability, overfitting and incorrect estimations.

Collinearity of variables can be assessed, for instance, with correlation heatmaps (see Chapter 17) or with scatter plots.

7.5 Batch effects

Batch effects are technical differences between groups of samples that were processed differently, for instance in different sequencing runs, laboratories, extraction kits or studies. They can be as large as the biological differences of interest and, if the batches are confounded with the groups being compared, they can lead to false conclusions. Batch effects in microbiome data, and methods to detect and correct them, are reviewed by Wang and Lê Cao (2020) and, as part of data preprocessing, by Zhou et al. (2023).

Data pre-processing for analyzing microbiome data – a mini review. Zhou et al. (2023). Comput Struct Biotechnol J 21:4804–4815. doi:10.1016/j.csbj.2023.10.001.

Design. Batch effects are best handled in the study design. If samples from all groups are distributed across batches, the batch can be accounted for in the analysis. If each batch contains only one group, the batch and group effects cannot be separated by any method.

Detection. Batch effects can be explored by coloring an ordination by batch (see Section 13.4), and their size can be estimated, for instance, with PERMANOVA that includes batch as a variable (see Section 13.3). Technical controls, such as mock communities or samples sequenced in several batches, make this easier.

Accounting for batch. Often the simplest approach is to include the batch as a covariate in the statistical model, for instance in differential abundance analysis (see Section 15.3.3.3) or in PERMANOVA (see Section 13.3). This keeps the original data unchanged.

Correcting the data. When the batch-corrected data itself is needed, for example for visualization or for methods that cannot include covariates, several Bioconductor packages are available. They differ in whether they were designed for microbiome data and in how directly they work with TreeSummarizedExperiment (TreeSE) data.

Microbiome-specific tools:

  • PLSDAbatch corrects batch effects with a multivariate framework based on partial least squares discriminant analysis (Wang and Lê Cao 2023). Its functions take an abundance matrix, which can be extracted from a TreeSE with assay(). The package provides its example data as TreeSE.
  • MMUPHin adjusts for batch or study effects, especially in meta-analyses of several studies (Ma et al. 2022). It takes an abundance matrix and a data frame of sample metadata, which can be extracted from a TreeSE with assay() and colData(). TreeSE is not supported directly.
PLSDA-batch: A multivariate framework to correct for batch effects in microbiome data. Wang et al. (2023). Brief Bioinform 24:bbac622. doi:10.1093/bib/bbac622.
Population structure discovery in meta-analyzed microbial communities and inflammatory bowel disease using MMUPHin. Ma et al. (2022). Genome Biol 23:208. doi:10.1186/s13059-022-02753-4.

General-purpose tools:

  • batchelor (Haghverdi et al. 2018) was developed for single-cell data. It accepts TreeSE directly, because TreeSE extends SingleCellExperiment. For instance, regressBatches() removes the batch effect from log-transformed data, such as clr-transformed abundances, with a linear model. It returns the corrected values as a new SingleCellExperiment, which can be added as an assay to the original TreeSE.
  • corral (Hsu and Culhane 2023) is based on correspondence analysis and accepts TreeSE directly. Its corralm() function returns the same object with a batch-integrated reduced-dimensional representation that can be used for ordination, but not corrected abundances.
Batch effects in single-cell RNA-sequencing data are corrected by matching mutual nearest neighbors. Haghverdi et al. (2018). Nat Biotechnol 36:421–427. doi:10.1038/nbt.4091.
Correspondence analysis for dimension reduction, batch integration, and visualization of single-cell RNA-seq data. Hsu et al. (2023). Sci Rep 13:1197. doi:10.1038/s41598-022-26434-1.

The general-purpose tools were not designed for microbiome data, so it should be checked that their assumptions suit the data.

Correction methods can remove biological signal together with the batch effect, especially when batch and group are partly confounded, so the results should be checked, for instance by repeating the ordination after correction. An online tutorial by Wang and Lê Cao (2020) demonstrates many of these methods in practice.

Managing batch effects in microbiome data. Wang et al. (2020). Brief Bioinform 21:1954–1970. doi:10.1093/bib/bbz105.

7.6 Exercises

We use the peerj13075 dataset. Note that its taxonomy ranks are written in lowercase (for example, genus).

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: Summarize the data

Goal: Summarize the dataset.

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

  2. Print tse. How many features and samples are there?

  3. Summarize the counts assay with summary().

  4. Summarize the dominant genera of the samples. How do you read the resulting table?

  5. Get the unique phyla in the data. How many phyla are there?

Useful functions: data(), summary(), mia::summarizeDominance(), mia::getUnique(), length()

library(mia)

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

# 2. Print the object
tse
##  class: TreeSummarizedExperiment 
##  dim: 674 58 
##  metadata(0):
##  assays(1): counts
##  rownames(674): OTU1 OTU2 ... OTU2567 OTU2569
##  rowData names(6): kingdom phylum ... family genus
##  colnames(58): ID1 ID2 ... ID57 ID58
##  colData names(5): Sample Geographical_location Gender Age Diet
##  reducedDimNames(0):
##  mainExpName: NULL
##  altExpNames(0):
##  rowLinks: NULL
##  rowTree: NULL
##  colLinks: NULL
##  colTree: NULL

# 3. Summary of counts
summary(tse, assay.type = "counts")
##  $samples
##  # A tibble: 1 × 6
##    total_counts min_counts max_counts median_counts mean_counts stdev_counts
##           <dbl>      <dbl>      <dbl>         <dbl>       <dbl>        <dbl>
##  1       955206        836     101182         8532.      16469.       19897.
##  
##  $features
##  # A tibble: 1 × 3
##    total singletons per_sample_avg
##    <int>      <int>          <dbl>
##  1   674          0           96.7

# 4. Dominant genera
summarizeDominance(tse, rank = "genus")
##  # A tibble: 19 × 3
##    dominant_taxa       n rel_freq
##    <chr>           <int>    <dbl>
##  1 Bacillus           15   0.259 
##  2 Staphylococcus     15   0.259 
##  3 Enterobacter        5   0.0862
##  4 Anaerococcus        4   0.0690
##  5 Corynebacterium     3   0.0517
##  6 Pantoea             2   0.0345
##  # ℹ 13 more rows

# 5. Unique phyla
phyla <- getUnique(tse, rank = "phylum")
phyla
##   [1] "Firmicutes"                 "Proteobacteria"            
##   [3] "Actinobacteria"             "Synergistetes "            
##   [5] "Chloroflexi"                "Tenericutes"               
##   [7] "Verrucomicrobia"            "Bacteroidetes"             
##   [9] "Planctomycetes"             "Caldiserica"               
##  [11] "Fibrobacteres"              "Cyanobacteria"             
##  [13] "Coprothermobacterota "      "Chlamydiae"                
##  [15] "Viridiplantae"              "Deinococcus-Thermus"       
##  [17] "Gemmatimonadetes"           "Pctinobacteria"            
##  [19] "NA"                         "Ignavibacteriae "          
##  [21] "Lentisphaerae"              "Chlorophyta"               
##  [23] "Spirochaetes"               "Acidobacteria"             
##  [25] "Nitrospirae"                "Candidatus Melainabacteria"
length(phyla)
##  [1] 26
  1. The dimensions are shown on the dim line: the first number is the number of features (rows) and the second the number of samples (columns).
  1. Each row is a genus that is the most abundant genus in at least one sample. The columns show in how many samples the genus is dominant, and what proportion of all samples this is. A genus at the top of the table is the most abundant genus in the largest number of samples.

  2. length() returns 26, but one of the values is "NA", and some names contain typos or trailing spaces, so the number of real phyla is smaller. It is good to check the names before counting them.

Exercise 2: Top, prevalent and rare features

Goal: Find the most abundant, prevalent and rare features.

  1. Get the 10 features that have the highest median abundance.

  2. Get the prevalent genera. Use a prevalence threshold of 20% and a detection threshold of 0, and store them in a variable called prev.

  3. Get the rare genera with the same thresholds and store them in a variable called rare.

  4. What is the difference between the features returned by getTop() and getPrevalent()?

Useful functions: mia::getTop(), mia::getPrevalent(), mia::getRare(), length()

# 1. Top 10 features by median abundance
getTop(tse, method = "median", top = 10)
##   [1] "OTU2172" "OTU773"  "OTU367"  "OTU194"  "OTU1893" "OTU1680" "OTU661" 
##   [8] "OTU2377" "OTU53"   "OTU520"

# 2. Prevalent genera
prev <- getPrevalent(tse, rank = "genus", prevalence = 0.2, detection = 0)
length(prev)
##  [1] 147

# 3. Rare genera
rare <- getRare(tse, rank = "genus", prevalence = 0.2, detection = 0)
length(rare)
##  [1] 526
  1. getTop() ranks the features by a summary of their abundance, here the median across samples, and returns a fixed number of them. getPrevalent() returns all features that are detected above the detection threshold in a large enough proportion of samples, so the number of returned features depends on the thresholds. A feature can be prevalent but have a low abundance, or be abundant in a few samples but not prevalent.
Exercise 3: Library size and sample metadata

Goal: Examine the library sizes and the sample metadata.

  1. Calculate the QC metrics of the samples and add them to colData. In which column is the library size stored?

  2. Visualize the distribution of the library sizes with a histogram.

  3. Visualize the number of samples in each group of Diet with a barplot.

  4. What can you do if the library sizes vary a lot between samples?

Useful functions: mia::addQC(), colData(), miaViz::plotHistogram(), miaViz::plotBarplot()

library(miaViz)

# 1. QC metrics
tse <- addQC(tse)
colnames(colData(tse))
##   [1] "Sample"                "Geographical_location" "Gender"               
##   [4] "Age"                   "Diet"                  "total"                
##   [7] "detected"              "mean"                  "sd"                   
##  [10] "cv"                    "q0"                    "q25"                  
##  [13] "q50"                   "q75"                   "q100"

# 2. Histogram of library sizes
plotHistogram(tse, col.var = "total") +
    labs(x = "Library size", y = "Number of samples")


# 3. Number of samples by diet
plotBarplot(tse, col.var = "Diet") +
    labs(y = "Number of samples")

  1. The library size, that is, the total count of each sample, is stored in the total column.

  2. The histogram shows how many samples have a library size in each range. A wide spread or a long tail means that the sequencing depth differs a lot between samples.

  1. First, check that the sampling depth is sufficient. Samples with a very small library size can be removed. Uneven sampling depth can be taken into account with data transformations or rarefaction.
Exercise 4: Distribution and abundance

Goal: Visualize the distribution of the counts and the abundances of the features.

  1. Visualize the distribution of all values in the counts assay with a histogram. What do you notice?

  2. Visualize the abundances of the 20 most abundant features with a jitter plot. Use a log-scaled x-axis.

  3. Visualize the abundances of the 5 most abundant features with a density plot, colored by Diet. Use a log-scaled x-axis.

  4. Why is it important to look at the distribution of the data before choosing a statistical test?

Useful functions: miaViz::plotHistogram(), miaViz::plotAbundanceDensity(), ggplot2::scale_x_log10()

# 1. Histogram of counts
plotHistogram(tse, assay.type = "counts") +
    scale_x_continuous(
        transform = "log1p", breaks = c(0, 10^(1:5)), labels = scales::comma
    ) +
    scale_y_continuous(labels = scales::comma) +
    labs(x = "Count", y = "Number of values")


# 2. Jitter plot of the top 20 features
plotAbundanceDensity(
    tse,
    layout = "jitter",
    assay.type = "counts",
    n = 20
) +
    scale_x_log10() +
    labs(x = "Count")


# 3. Density plot of the top 5 features
plotAbundanceDensity(
    tse,
    layout = "density",
    assay.type = "counts",
    n = 5,
    colour.by = "Diet"
) +
    scale_x_log10() +
    labs(x = "Count")

  1. Microbiome counts are typically zero-inflated and right-skewed: a large bar at zero shows that many values are zeros, and a long tail shows that a few values are very large.

  2. Each row is a feature and each point is one sample. The x-axis shows the abundance of the feature in that sample. A wide spread of points means that the abundance of the feature varies a lot between samples.

  1. Many common statistical tests assume that the data is normally distributed. Microbiome data rarely is, and using such tests anyway can lead to incorrect conclusions.
Exercise 5: Prevalence

Goal: Calculate and visualize the prevalence of features.

  1. Calculate the prevalence of the features and add it to rowData. Use a detection threshold of 0.1% relative abundance, that is, detection = 0.1 / 100 and as.relative = TRUE.

  2. Visualize the distribution of the prevalences with a histogram.

  3. Visualize the prevalence of the features against their relative abundance.

  4. Calculate the proportion of core features in each sample and add it to colData. Use a prevalence threshold of 50% and a detection threshold of 0.1%. Visualize the result with a histogram.

  5. How do you read the prevalence histogram? What does a value of 0.5 mean?

Useful functions: mia::addPrevalence(), miaViz::plotHistogram(), miaViz::plotPrevalentAbundance(), mia::addPrevalentAbundance()

# 1. Prevalence of features
tse <- addPrevalence(tse, detection = 0.1 / 100, as.relative = TRUE)

# 2. Histogram of prevalences
plotHistogram(tse, row.var = "prevalence") +
    labs(x = "Prevalence", y = "Number of features")


# 3. Prevalence against abundance
plotPrevalentAbundance(tse) +
    scale_x_log10()


# 4. Proportion of core features in each sample
tse <- addPrevalentAbundance(
    tse,
    prevalence = 50 / 100,
    detection = 0.1 / 100
)
plotHistogram(tse, col.var = "prevalent_abundance") +
    labs(x = "Abundance of core features", y = "Number of samples")

  1. The histogram shows how large a proportion of each sample consists of the core features, that is, the features that are present in more than half of the samples. A value close to 1 means that the sample consists almost only of core features, and a small value means that most of the sample consists of features that are not common in the dataset.

  2. Prevalence is the proportion of samples in which a feature exceeds the detection threshold. A value of 0.5 means that the feature is detected in half of the samples. If most of the features are on the left side of the histogram, most features are found only in a small part of the samples. If many features are on the right side, many features are found in most samples.

Exercise 6: Contaminants

Goal: Explain how contaminant sequences can be detected.

Answer the following questions without writing any code. The section “Contaminant sequences” will help you.

  1. What are the two main approaches to detect contaminants, and what information does each of them need?

  2. In the frequency-based approach, how is a contaminant expected to behave when the DNA concentration of the samples increases? Why?

  3. Why are contaminants expected to be more prevalent in negative control samples than in true samples?

  4. What is the difference between addContaminantQC() and isContaminant()?

  1. Frequency-based testing needs the DNA concentration of each sample. Prevalence-based testing needs information on which samples are negative controls.

  2. Its relative abundance is expected to decrease. A contaminant adds about the same amount of DNA to every sample, so it makes up a larger fraction of samples with little DNA and a smaller fraction of samples with much DNA.

  3. Negative controls lack true biological DNA, so the sequences found in them mainly come from contamination sources.

  4. addContaminantQC() adds the results to rowData of the object, whereas isContaminant() returns only the results. With detailed = FALSE, the result is a logical vector that can be used for subsetting the data.

Back to top