8 Subsetting
In this chapter, we explore the concept of subsetting. Subsetting or filtering is the process of selecting specific rows or columns from a dataset based on certain criteria. When you subset your data, you retain the original values of the selected data points. For example, if you have a dataset of taxonomic features and you choose to keep only certain species, you still have the individual counts for those species. This allows you to analyze the data in detail, but you may lose information about other species that are not included.
Subsetting data helps to draw the focus of an analysis on particular sets of samples and / or features. When dealing with large datasets, the subset of interest can be extracted and investigated separately. This might improve performance and reduce the computational load.
Let us store GlobalPatterns (Caporaso et al. 2011) into tse and check its original number of features (rows) and samples (columns).
When subsetting by sample, expect the number of columns to decrease. When subsetting by feature, expect the number of rows to decrease.
8.1 By sample
Several criteria can be used to subset by sample:
- origin
- sampling time
- sequencing method
- DNA / RNA barcode
- cohort
For the sake of demonstration, here we will extract a subset containing only the samples of human origin (feces, skin or tongue), stored as SampleType within colData(tse) as well as in tse.
First, we would like to see all the possible values that SampleType can have and how frequent those are:
| Var1 | Freq |
|---|---|
| Feces | 4 |
| Freshwater | 2 |
| Freshwater (creek) | 3 |
| Mock | 3 |
| Ocean | 3 |
| Sediment (estuary) | 3 |
| Skin | 3 |
| Soil | 3 |
| Tongue | 2 |
Next, we logically index across the columns of tse (make sure to leave the first index empty to select all rows) and filter for the samples of human origin. For this, we use the information on the samples from the metadata colData(tse).
After subsetting, expect the number of rows to equal the sum of the frequencies of the samples that you are interested in. For instance, ncols = Feces + Skin + Tongue = 4 + 3 + 2 = 9.
8.2 By feature
Similarly, here we will extract a subset containing only the features that belong to the phyla Actinobacteria and Chlamydiae, stored as Phylum within rowData(tse). However, subsetting by feature implies a few more obstacles, such as the presence of NA elements and the possible need for agglomeration.
As previously, we would first like to see all the possible values that Phylum can have and how frequent those are:
| Var1 | Freq |
|---|---|
| ABY1_OD1 | 7 |
| AC1 | 1 |
| AD3 | 9 |
| Acidobacteria | 1021 |
| Actinobacteria | 1631 |
| Armatimonadetes | 61 |
After subsetting, expect the number of rows to equal the sum of the frequencies of the feature(s) that you are interested in. For instance, nrows = Actinobacteria + Chlamydiae = 1631 + 21 = 1652.
Depending on your research question, you might or might not need to agglomerate the data in the first place: if you want to find the abundance of each and every feature that belongs to Actinobacteria and Chlamydiae, agglomeration is not needed. However, if you want to find the total abundance of all features that belong to Actinobacteria or Chlamydiae, agglomeration is recommended (see Chapter 9 for details).
Next, we logically index across the rows of tse (make sure to leave the second index empty to select all columns) and filter for the features that fall in either Actinobacteria or Chlamydiae group. For this, we use the information on the features from the metadata rowData(tse).
The %in% operator selects all the features of interest. It returns FALSE for features that have NA in place of the phylum, so they are left out.
8.3 By sample and feature
Finally, we can subset data by sample and feature at once. The resulting subset contains all the samples of human origin and all the features of phyla Actinobacteria or Chlamydiae.
The dimensions of tse_sub are consistent with the previous subsets (9 columns filtered by sample and 1652 rows filtered by feature).
If a study was to consider and quantify the presence of Actinobacteria as well as Chlamydiae in different sites of the human body, tse_sub might be a suitable subset to start with.
The same subsets can be created with subsetBy(). Its rows and cols arguments take conditions that can refer directly to the columns of rowData and colData. This makes it easier to define more complex filtering rules. In addition, subsetBy() can combine the features that are filtered out into a single feature instead of removing them (Section 8.6.1).
8.4 By library size
As a preprocessing step, one might want to remove samples that do not exceed a certain library size, i.e., total number of counts. Additionally, sometimes data might contain samples that do not contain any of the features present in the dataset. This can occur, for example, after data subsetting. To focus only on samples containing sufficient information, we might want to remove those instances. In this example, we are interested only in those features that belong to the species Achromatiumoxaliferum.
Then we can calculate the total number of counts in each sample.
Now we can see that certain samples do not include any bacteria. We can remove those.
# Remove samples that do not contain any bacteria
tse_sub <- tse_sub[, tse_sub$total != 0]
tse_sub
## class: TreeSummarizedExperiment
## dim: 3 7
## metadata(0):
## assays(1): counts
## rownames(3): 7595 7594 137055
## rowData names(7): Kingdom Phylum ... Genus Species
## colnames(7): AQC1cm AQC4cm ... TRRsed2 TRRsed3
## colData names(17): X.SampleID Primer ... q75 q100
## reducedDimNames(0):
## mainExpName: NULL
## altExpNames(0):
## rowLinks: a LinkDataFrame (3 rows)
## rowTree: 1 phylo tree(s) (19216 leaves)
## colLinks: NULL
## colTree: NULLWe have now subsetted the dataset so that it only includes samples containing the selected features. A similar approach can also be applied to filter features based on the samples they appear in, ensuring both dimensions of the data are relevant to your analysis.
8.5 Zero-variance features
In some datasets, certain features remain constant across all samples — they show no variance. If our goal is to study or model microbial differences between groups, these zero-variance features hold no value. For a feature to reflect differences between groups, it must exhibit variability.
By removing these invariant features, we can sharpen our focus on the more informative features. This not only reduces the number of comparisons but also helps our machine learning models learn from meaningful data without additional noise.
To filter these features, we begin by calculating their standard deviation across samples. Then we visualize the standard deviations with a histogram (Figure 8.1).
library(miaViz)
# Calculate per-feature QC metrics, including standard deviation
tse <- addQC(tse, assay.type = "counts", by = "rows")
# Plot
plotHistogram(tse, row.var = "sd") +
scale_x_log10()
addQC() stores the metrics in rowData(); the standard deviations are in rowData(tse)[["sd"]]. The logarithmic x-axis only makes the range of values easier to inspect; the stored values remain on their original scale. Features with a standard deviation of zero cannot be shown on a logarithmic axis, so they are left out of the histogram.
Features with a standard deviation of zero are constant across all samples. Therefore, selecting values greater than zero removes only these zero-variance features. Because addQC() calculates the SD from the counts assay by default, this identifies features that are invariant in the raw counts. For filtering variance after normalization or transformation, calculate the SD from the corresponding assay instead.
To filter the data, we select the rows whose standard deviation exceeds the desired threshold. Here, the threshold is zero, as we want to keep only features that vary across samples.
tse_sub <- tse[rowData(tse)[["sd"]] > 0, ]
tse_sub
## class: TreeSummarizedExperiment
## dim: 18988 26
## metadata(0):
## assays(1): counts
## rownames(18988): 549322 522457 ... 200359 271582
## rowData names(17): Kingdom Phylum ... q75 q100
## colnames(26): CL3 CC1 ... Even2 Even3
## colData names(7): X.SampleID Primer ... SampleType Description
## reducedDimNames(0):
## mainExpName: NULL
## altExpNames(0):
## rowLinks: a LinkDataFrame (18988 rows)
## rowTree: 1 phylo tree(s) (19216 leaves)
## colLinks: NULL
## colTree: NULLAfter filtering, the dataset now contains 18988 features, compared to the original 19216 features. This means we are left with features that exhibit variance. A larger threshold could be used when the goal is to remove low-variance features as well.
If you are more familiar with tidyverse (Wickham et al. 2019) syntax, the same filtering can be done with the filter() function from the tidySummarizedExperiment package (Hutchison et al. 2024).
library(tidySummarizedExperiment)
tse_sub <- tse |> filter(sd > 0)See Section 6.5 for more information on tidy R programming.
8.6 By prevalence
We can subset the data based on prevalence with subsetBy(). The function keeps the features (rows) and samples (cols) that meet a condition. The condition is an R expression that can refer to the assays by their names (e.g., counts) and to the columns of rowData or colData. Filtering prevalent features helps to remove rare features that may be artifacts. Conversely, keeping only the features below the threshold enables a focus on rare features within the dataset.
Here, we apply a prevalence threshold of 10% and a detection threshold of 0. Both thresholds are strict: a feature is considered detected if it has more than zero counts (i.e., at least one count) in a sample, and prevalent if it is detected in more than 10% of the samples. addPrevalence() calculates the proportion of samples in which each feature is detected and stores it in the prevalence column of rowData. The condition prevalence > 0.1 would retain the prevalent features, while prevalence <= 0.1 keeps the features that are not prevalent.
tse_sub <- addPrevalence(tse)
tse_sub <- subsetBy(tse_sub, rows = prevalence <= 0.1)
tse_sub
## class: TreeSummarizedExperiment
## dim: 6505 26
## metadata(0):
## assays(1): counts
## rownames(6505): 522457 951 ... 579616 463590
## rowData names(18): Kingdom Phylum ... q100 prevalence
## colnames(26): CL3 CC1 ... Even2 Even3
## colData names(7): X.SampleID Primer ... SampleType Description
## reducedDimNames(0):
## mainExpName: NULL
## altExpNames(0):
## rowLinks: a LinkDataFrame (6505 rows)
## rowTree: 1 phylo tree(s) (19216 leaves)
## colLinks: NULL
## colTree: NULL8.6.1 Collapse rare features
Above, we selected only prevalent or rare features. In some cases, it might be beneficial to combine the features that would otherwise be removed. For example, instead of filtering out rare taxa, we can combine the reads from all these rare taxa under a new feature which we can call “Rare taxa”. The function subsetBy() with collapse = TRUE accomplishes this by merging filtered features into a single feature called “Other” by default, preventing unnecessary loss of information. This is particularly useful when working with right-skewed feature data, such as soil microbiome datasets where rare taxa may represent a significant proportion of the reads when combined.
Here, we demonstrate how to combine the rare features using prevalence and abundance thresholds of 20% and 0.1%, respectively. This means that for a feature to be considered detected in a sample, its relative abundance must exceed 0.1% and after this, the feature must be detected in more than 20% of samples. Taxa that do not meet these criteria are combined in the “Other” group.
To use relative abundances for the detection threshold, we must first transform the data to relative abundances (aka normalize as proportions). These kinds of transformations are introduced in more detail in Chapter 10.
# Transform
tse <- transformAssay(tse, method = "relabundance")
# Add prevalence and combine rare features
tse <- addPrevalence(tse, assay.type = "relabundance", detection = 0.001)
tse_prev <- subsetBy(
tse,
rows = prevalence > 0.2,
collapse = TRUE
)
tse_prev
## class: TreeSummarizedExperiment
## dim: 20 26
## metadata(0):
## assays(2): counts relabundance
## rownames(20): 329744 326977 ... 108747 Other
## rowData names(18): Kingdom Phylum ... q100 prevalence
## 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: NULLWe have now combined the rare features into one feature. To combine rare features at a higher taxonomic rank, such as phylum, the data is first agglomerated to that rank (Chapter 9), and then subset as shown above.
8.7 Exercises
We use the Tengeler2020 dataset.
Solve the exercises in order, as each exercise continues from the previous one. Try to solve each exercise yourself before opening the solution.
