9  Agglomeration

In Chapter 8, we covered how to select features from the dataset. Agglomeration, on the other hand, involves combining data points into broader feature categories by summing their values. For instance, if you have counts for individual species, you might agglomerate them into groups based on the family of each species. This means you would add up the counts of all species within a particular family to get a single value that represents that family (Figure 9.1). While this method simplifies your dataset and you lose the specific information about individual species, it can be useful in highlighting overall trends.

flowchart LR
    subgraph sp["Species"]
        direction TB
        s1["<i>Roseburia intestinalis</i><br/>6"]
        s2["<i>Roseburia hominis</i><br/>3"]
        s3["<i>Blautia obeum</i><br/>4"]
        s4["<i>Bacteroides fragilis</i><br/>5"]
    end
    subgraph ge["Genus"]
        direction TB
        g1["<i>Roseburia</i><br/>6 + 3 = 9"]
        g2["<i>Blautia</i><br/>4"]
        g3["<i>Bacteroides</i><br/>5"]
    end
    subgraph fa["Family"]
        direction TB
        f1["Lachnospiraceae<br/>9 + 4 = 13"]
        f2["Bacteroidaceae<br/>5"]
    end
    s1 --> g1
    s2 --> g1
    s3 --> g2
    s4 --> g3
    g1 --> f1
    g2 --> f1
    g3 --> f2
    classDef leaf fill:#ffffff,stroke:#6c757d,color:#070707
    classDef agg fill:#e6f3f7,stroke:#0087af,color:#070707
    class s1,s2,s3,s4 leaf
    class g1,g2,g3,f1,f2 agg
Figure 9.1: Agglomeration sums the counts of features up the taxonomy tree. In this sample, four species are agglomerated into three genera and two families; the total count (18) stays the same.

The choice between subsetting and agglomeration depends on your research goals and the type of insights you want to gain from your data. For example, if you are interested in comparing compositions of two types of microbiomes (e.g., gut microbiome and soil microbiome), you might want to first examine their taxonomic profiles at the level of phyla or families, rather than species, to get an idea of their broad similarities or differences. Agglomeration is most often used to reduce the number of features, especially in sequencing data, where there may not be enough resolution to reliably differentiate between closely related species. Combining data at higher taxonomic levels allows you to focus on broader patterns in the community while managing the complexity of the dataset. Similarly, in addition to agglomerating features to higher categories, you might want to agglomerate samples within the given sample type, to examine these broad differences across sample types rather than samples.

NoteNote

When you are interested in the total feature abundances of certain taxonomy ranks, the data should first be agglomerated to the specified taxonomy level. Afterward, we can then select the desired taxa from the dataset.

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

9.1 By taxonomy rank

One of the main applications of taxonomic information in sequencing data is to agglomerate counts (such as ASV counts) to specific taxonomic levels and to model how different sample-specific variables may influence the feature composition at different taxonomic levels. For this, mia contains the agglomerateByRank() function.

At its simplest, the function takes a TreeSE object as input and outputs a TreeSE object agglomerated to a specified taxonomy level using the rank parameter. Note that we can also choose to prune the phylogenetic tree to correspond to the agglomerated data, by setting update.tree = TRUE. The tree can be pruned only if the features of each group form a subtree of their own, i.e., the groups are monophyletic. Otherwise, the tree is removed.

# Agglomerate
tse_phylum <- agglomerateByRank(tse, rank = "Phylum", update.tree = TRUE)
tse_phylum
##  class: TreeSummarizedExperiment 
##  dim: 66 26 
##  metadata(1): agglomerated_by_rank
##  assays(1): counts
##  rownames(66): ABY1_OD1 AC1 ... ZB2 ZB3
##  rowData names(7): Kingdom Phylum ... Genus Species
##  colnames(26): CL3 CC1 ... Even2 Even3
##  colData names(7): X.SampleID Primer ... SampleType Description
##  reducedDimNames(0):
##  mainExpName: NULL
##  altExpNames(0):
##  rowLinks: NULL
##  rowTree: NULL
##  colLinks: NULL
##  colTree: NULL

The output now contains 66 features, a reduction from the original 19216 rows. Agglomeration has combined features together to higher feature categories, but the samples remain unchanged from the original dataset. Let’s take a look at the rowData to see how it looks.

rowData(tse_phylum)
##  DataFrame with 66 rows and 7 columns
##                     Kingdom         Phylum       Class       Order
##                 <character>    <character> <character> <character>
##  ABY1_OD1          Bacteria       ABY1_OD1          NA          NA
##  AC1               Bacteria            AC1          NA          NA
##  AD3               Bacteria            AD3          NA          NA
##  Acidobacteria     Bacteria  Acidobacteria          NA          NA
##  Actinobacteria    Bacteria Actinobacteria          NA          NA
##  ...                    ...            ...         ...         ...
##  WS1               Bacteria            WS1          NA          NA
##  WS2               Bacteria            WS2          NA          NA
##  WS3               Bacteria            WS3          NA          NA
##  ZB2               Bacteria            ZB2          NA          NA
##  ZB3               Bacteria            ZB3          NA          NA
##                      Family       Genus     Species
##                 <character> <character> <character>
##  ABY1_OD1                NA          NA          NA
##  AC1                     NA          NA          NA
##  AD3                     NA          NA          NA
##  Acidobacteria           NA          NA          NA
##  Actinobacteria          NA          NA          NA
##  ...                    ...         ...         ...
##  WS1                     NA          NA          NA
##  WS2                     NA          NA          NA
##  WS3                     NA          NA          NA
##  ZB2                     NA          NA          NA
##  ZB3                     NA          NA          NA

As we observe from the taxonomy table, all lower ranks below Phylum now contain NA values. This is expected, as we have agglomerated the data to the Phylum level, meaning that the lowest rank that rows can be uniquely mapped to is the Phylum rank.

Since we specified update.tree = TRUE, the function tried to prune the phylogenetic tree. In this dataset, however, some phyla are not monophyletic: their features are spread across different branches of the tree. The tree could therefore not be agglomerated, and it was removed.

rowTree(tse_phylum)
##  NULL

If a tree is needed for the agglomerated data, a hierarchy tree can be created from the taxonomy table instead (see Section 5.4).

Additionally, we can examine the counts assay table to assess how the agglomeration has affected the counts of unique features per sample.

assay(tse_phylum, "counts")[1:5, 1:5]
##                    CL3    CC1    SV1 M31Fcsw M11Fcsw
##  ABY1_OD1           11     33      0       0       0
##  AC1                 0      0      0       0       0
##  AD3              1299  15577     17       2       1
##  Acidobacteria  269202 183132  92863     120     115
##  Actinobacteria  39601  90280 121703    2540     841

The values in the counts assay are considerably larger than in the original data, indicating that the values have been summed during agglomeration.

Now that the data is agglomerated, we can check the abundances of certain phyla across the samples.

# Store features of interest into phyla
phyla <- c("Actinobacteria", "Chlamydiae")

# Subset by feature
tse_sub <- tse_phylum[phyla, ]

# Show counts
assay(tse_sub)
##                   CL3   CC1    SV1 M31Fcsw M11Fcsw M31Plmr M11Plmr F21Plmr
##  Actinobacteria 39601 90280 121703    2540     841   85825  103067   27295
##  Chlamydiae       265   702     22       0       1       5      22       0
##                 M31Tong M11Tong LMEpi24M SLEpi20M AQC1cm AQC4cm AQC7cm   NP2
##  Actinobacteria  123464    8822   444605   648008  26392  27519  30304 20047
##  Chlamydiae           0       0        3        8      9     26     35     6
##                   NP3    NP5 TRRsed1 TRRsed2 TRRsed3  TS28   TS29  Even1
##  Actinobacteria 19592 168762    1058    2290    2351 27569 130158 105541
##  Chlamydiae        36      9       2      85      62     2      0      1
##                 Even2 Even3
##  Actinobacteria 79261 89965
##  Chlamydiae         1     0
NoteNote

As data was agglomerated and then further subsetted, the number of rows should equal the number of phyla used in subsetting (in this case, just 2).

Furthermore, we can observe that the agglomeration will be applied to every assay in the dataset. Let’s add another assay to the original dataset and then perform agglomeration again, this time at the Family level.

# Add another assay
assay(tse, "another_assay", withDimnames = FALSE) <- matrix(
    runif(ncol(tse) * nrow(tse), 0, 1),
    ncol = ncol(tse), nrow = nrow(tse)
)

# Agglomerate
tse_family <- agglomerateByRank(tse, rank = "Family")

assayNames(tse_family)
##  [1] "counts"        "another_assay"

We can now confirm that the agglomerated dataset contains two assays: “counts” and “another_assay”, consistent with the original data structure.

If the data is agglomerated by features, the ideal location to store the resulting dataset is the alternative experiment, altExp, slot (see Section 3.7). Let’s add the Phylum data there.

altExp(tse, "phylum") <- tse_phylum
altExpNames(tse)
##  [1] "phylum"

altExp now contains the Phylum-level data under the name phylum. This can be extended to any taxonomic level listed in taxonomyRanks(tse). While it is certainly possible to agglomerate data one taxonomic level at a time, you can also aggregate data across all available ranks in a single step using the agglomerateByRanks() function. This function returns a TreeSE object that includes the agglomerated datasets in the altExp slot.

If you want the data as a list as discussed in Section 6.1, you can achieve this by specifying as.list = TRUE.

tse <- agglomerateByRanks(tse)
altExpNames(tse)
##  [1] "phylum"  "Kingdom" "Phylum"  "Class"   "Order"   "Family"  "Genus"  
##  [8] "Species"

9.2 By variable

The agglomerateByRank() function aggregates data based on rowData, that is, the agglomerates are made based on features, such as taxonomy information. Alternatively, you can use agglomerateByVariable() to aggregate the data.

agglomerateByVariable() is designed to aggregate data based on criteria other than taxa, such as sample groups or clusters. The by parameter specifies whether features (by = "rows") or samples (by = "cols") are aggregated, and group names the rowData or colData variable that defines the groups. Below, we aggregate samples by their sample type.

NoteNote

Note that a feature dataset might contain taxa with the same lower-level rank, even if their higher-level ranks differ. For this reason, agglomerateByVariable() should not be used for aggregating taxonomy ranks.

# Agglomerate samples based on type
tse_sub <- agglomerateByVariable(tse, by = "cols", group = "SampleType")
tse_sub
##  class: TreeSummarizedExperiment 
##  dim: 19216 9 
##  metadata(0):
##  assays(2): counts another_assay
##  rownames(19216): 549322 522457 ... 200359 271582
##  rowData names(7): Kingdom Phylum ... Genus Species
##  colnames(9): Feces Freshwater ... Soil Tongue
##  colData names(7): X.SampleID Primer ... SampleType Description
##  reducedDimNames(0):
##  mainExpName: NULL
##  altExpNames(8): phylum Kingdom ... Genus Species
##  rowLinks: a LinkDataFrame (19216 rows)
##  rowTree: 1 phylo tree(s) (19216 leaves)
##  colLinks: NULL
##  colTree: NULL

Now, the data includes as many columns as there are sample types.

In Section 14.1.2, we will explore how cluster information can be used to agglomerate data effectively.

9.3 Choosing a taxonomic level

There is no single correct taxonomic level for an analysis; the choice depends on the data and the research question. Some general considerations:

  • Use the finest level that the data supports. Agglomeration discards information, so analyses such as alpha and beta diversity, ordination and PERMANOVA are often done at the finest available level. Phylogenetic measures, such as Faith’s diversity and UniFrac, use the tree and do not need agglomeration.
  • Consider the sequencing method. Short-read 16S rRNA amplicon data often cannot reliably resolve species, so the genus level is a common choice, while full-length 16S rRNA sequencing can resolve many species (Johnson et al. 2019). Shotgun metagenomic data are commonly analyzed at the species level.
  • Consider interpretation. Higher levels, such as phylum or family, give fewer features that are easier to summarize and report, which is why they are common in composition barplots (Section 11.1). At very fine levels, many features are found only in a few samples, which can make samples look more different from each other.
  • Consider multiple testing. Fewer features mean fewer tests, for example in differential abundance analysis, and thus a smaller correction for multiple testing. However, choose the level before looking at the results, not based on which level gives the smallest p-values.
Evaluation of 16S rRNA gene sequencing for species and strain-level microbiome analysis. Johnson et al. (2019). Nat Commun 10:5029. doi:10.1038/s41467-019-13036-1.

It can be useful to check whether the main results hold at more than one level. For choosing the transformation, see Section 10.4.

9.4 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.

TipExercise 1: What happens in agglomeration

Goal: Explain how agglomeration combines features.

Imagine a dataset with four bacterial species from two genera, measured in two samples:

Species Genus Sample A Sample B
Bacteroides fragilis Bacteroides 10 0
Bacteroides ovatus Bacteroides 30 5
Prevotella copri Prevotella 55 90
Prevotella bivia Prevotella 5 5

Answer the following questions without writing any code. The beginning of this chapter and Section 8.6.1 will help you.

  1. What are the counts of Bacteroides and Prevotella in both samples after the data is agglomerated to the Genus rank?

  2. How many rows and columns does the agglomerated data have?

  3. After agglomeration, what value would you expect in the Species column of the taxonomy table? Why?

  4. Does the total number of reads in each sample change in agglomeration?

  5. Suppose Prevotella bivia is considered rare. What happens to its reads if rare features are removed, and what happens if they are agglomerated based on prevalence instead?

  1. The counts of the species in the same genus are summed. Bacteroides has 10 + 30 = 40 reads in Sample A and 0 + 5 = 5 reads in Sample B. Prevotella has 55 + 5 = 60 reads in Sample A and 90 + 5 = 95 reads in Sample B.

  2. The data has two rows, one for each genus, and two columns. Agglomeration of features does not change the samples.

  3. The Species column would contain NA. Each row now represents a whole genus that contains several species, so it cannot be mapped to a single species.

  4. No. The counts are only summed into larger groups, so each sample has the same total number of reads as before (100 reads in both samples here). This holds as long as all features have a value in the chosen rank.

  5. If rare features are removed, the reads of Prevotella bivia are lost. In agglomeration based on prevalence, the rare features are combined into a single feature called “Other”, so their reads are kept in the data.

TipExercise 2: Agglomerate to a taxonomy rank

Goal: Agglomerate features to a taxonomy rank and explore the agglomerated data.

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

  2. List the taxonomy ranks available in the data.

  3. Agglomerate the data to the Phylum rank and store the result in a variable called tse_phylum.

  4. Compare the number of rows in tse and tse_phylum. What does one row represent in each object?

  5. Look at the rowData of tse_phylum. Why do the columns below Phylum contain only NA values?

  6. Calculate the total number of reads in each sample, that is, the column sums of the counts assay, in both tse and tse_phylum. Do they differ?

  7. Subset tse_phylum to the phyla "Bacteroidetes" and "Firmicutes", and show their counts.

Useful functions: data(), mia::taxonomyRanks(), mia::agglomerateByRank(), nrow(), rowData(), assay(), colSums(), head()

library(mia)

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

# 2. Available taxonomy ranks
taxonomyRanks(tse)
##  [1] "Kingdom" "Phylum"  "Class"   "Order"   "Family"  "Genus"

# 3. Agglomerate to Phylum rank
tse_phylum <- agglomerateByRank(tse, rank = "Phylum")

# 4. Number of rows
nrow(tse)
##  [1] 151
nrow(tse_phylum)
##  [1] 5

# 5. Taxonomy table of the agglomerated data
rowData(tse_phylum)
##  DataFrame with 5 rows and 6 columns
##                      Kingdom          Phylum       Class       Order
##                  <character>     <character> <character> <character>
##  Bacteroidetes      Bacteria   Bacteroidetes          NA          NA
##  Cyanobacteria      Bacteria   Cyanobacteria          NA          NA
##  Firmicutes         Bacteria      Firmicutes          NA          NA
##  Proteobacteria     Bacteria  Proteobacteria          NA          NA
##  Verrucomicrobia    Bacteria Verrucomicrobia          NA          NA
##                       Family       Genus
##                  <character> <character>
##  Bacteroidetes            NA          NA
##  Cyanobacteria            NA          NA
##  Firmicutes               NA          NA
##  Proteobacteria           NA          NA
##  Verrucomicrobia          NA          NA

# 6. Total number of reads per sample
colSums(assay(tse, "counts")) |> head()
##   A110  A111   A12   A13   A14   A15 
##  37394 40584 16077 39210  6351  5461
colSums(assay(tse_phylum, "counts")) |> head()
##   A110  A111   A12   A13   A14   A15 
##  37394 40584 16077 39210  6351  5461

# 7. Subset to two phyla
phyla <- c("Bacteroidetes", "Firmicutes")
tse_sub <- tse_phylum[phyla, ]
assay(tse_sub, "counts")
##                 A110  A111   A12   A13  A14  A15  A16  A17  A18   A19  A21
##  Bacteroidetes 31534 32123  4392 28356 4927 3029 6386 4187 1494 13567 6295
##  Firmicutes     4584  4611 10445  9058 1024 1726 3484 2208  168  5512  927
##                 A210   A22   A23   A24  A25   A26  A27   A28  A29   A33  A34
##  Bacteroidetes 27375 14271 19005 13232 5760 11132 9418 14153 6087 12646 6184
##  Firmicutes     3041  5918   760  6840 7821  7468 9533  1928 8792  5079 1673
##                 A35  A36  A37  A38   A39
##  Bacteroidetes 7784 9265 9134 7672 11941
##  Firmicutes    9637 4132 3520 3861  2794
  1. In tse, each row is a single taxonomic feature. In tse_phylum, each row is a phylum, and its values are the sums of all features that belong to that phylum. The number of rows equals the number of phyla in the data.

  2. Each row now represents a whole phylum, which can contain many classes, orders, families and genera. Therefore, the lowest rank that the rows can be uniquely mapped to is Phylum.

  3. If the totals are equal, all reads were kept and only summed into larger groups. Features that have no value in the chosen rank are not assigned to any group, so the totals can become smaller when you agglomerate to a rank with missing values.

TipExercise 3: Store agglomerated data in altExp

Goal: Store agglomerated data in the alternative experiment slot, and agglomerate the data to all ranks at once.

  1. Add tse_phylum to the alternative experiments of tse under the name "phylum". List the names of the alternative experiments.

  2. Agglomerate tse to all taxonomy ranks at once and store the result back in tse. List the names of the alternative experiments again. What do the new names correspond to?

  3. Retrieve the Genus-level data from the alternative experiments and store it in a variable called tse_genus. How many rows and columns does it have?

  4. Why is the alternative experiment slot a suitable place for data that is agglomerated by features?

Useful functions: altExp()<-, altExpNames(), mia::agglomerateByRanks(), altExp(), dim()

# 1. Add Phylum data to altExp
altExp(tse, "phylum") <- tse_phylum
altExpNames(tse)
##  [1] "phylum"

# 2. Agglomerate to all ranks
tse <- agglomerateByRanks(tse)
altExpNames(tse)
##  [1] "phylum"  "Kingdom" "Phylum"  "Class"   "Order"   "Family"  "Genus"

# 3. Retrieve Genus-level data
tse_genus <- altExp(tse, "Genus")
dim(tse_genus)
##  [1] 49 27
  1. The new names correspond to the taxonomy ranks of the data. Each alternative experiment contains the data agglomerated to that rank.

  2. The number of columns is the same as in tse, because the samples do not change. The number of rows is the number of genera.

  3. An alternative experiment must have the same samples as the main experiment, but it can have different features. Data agglomerated by features fulfills this, so all the agglomerated datasets can be kept together with the original data in one object.

TipExercise 4: Agglomerate samples

Goal: Agglomerate samples based on a variable in colData.

  1. Agglomerate the samples of tse based on the patient_status column of colData, and store the result in a variable called tse_status.

  2. How many rows and columns does tse_status have? What are its column names?

  3. Why can tse_status not be added to the alternative experiments of tse?

Useful functions: mia::agglomerateByVariable(), dim(), colnames()

# 1. Agglomerate samples by patient status
tse_status <- agglomerateByVariable(
    tse,
    by = "cols",
    group = "patient_status"
)

# 2. Dimensions and column names
dim(tse_status)
##  [1] 151   2
colnames(tse_status)
##  [1] "ADHD"    "Control"
  1. The features do not change, so the number of rows is the same as in tse. There is one column for each group in patient_status, and the columns are named after the groups. The counts of the samples in each group are summed.

  2. An alternative experiment must have the same samples as the main experiment. Here, the samples were combined into groups, so the columns no longer match those of tse.

TipExercise 5: Combine rare phyla

Goal: Agglomerate the data to a taxonomy rank and combine the rare features.

  1. Agglomerate tse to the Phylum rank, and store the result in a variable called tse_prev_phylum.

  2. Add the prevalence of each phylum to rowData with a detection threshold of 1.

  3. Keep the phyla with a prevalence over 0.2 and combine the rest into a single feature with subsetBy() and collapse = TRUE. Show the row names of the result.

  4. Why is the prevalence calculated after the agglomeration?

Useful functions: mia::agglomerateByRank(), mia::addPrevalence(), mia::subsetBy(), rownames()

# 1. Agglomerate to Phylum rank
tse_prev_phylum <- agglomerateByRank(tse, rank = "Phylum")

# 2. Add prevalence
tse_prev_phylum <- addPrevalence(tse_prev_phylum, detection = 1)

# 3. Keep prevalent phyla and combine the rest
tse_prev_phylum <- subsetBy(
    tse_prev_phylum,
    rows = prevalence > 0.2, collapse = TRUE
)
rownames(tse_prev_phylum)
##  [1] "Bacteroidetes"   "Firmicutes"      "Proteobacteria"  "Verrucomicrobia"
##  [5] "Other"
  1. The phyla that have more than 1 count in more than 20% of the samples are kept as they are. The other phyla are combined into “Other”.

  2. The prevalence of a phylum differs from the prevalence of the features that it contains. A phylum is detected in a sample when the sum of its features exceeds the detection threshold, so the prevalence must be calculated from the agglomerated data.

Back to top