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

Global patterns of 16S rRNA diversity at a depth of millions of sequences per sample. Caporaso et al. (2011). Proc Natl Acad Sci USA 108:4516–4522. doi:10.1073/pnas.1000080107.
# Load libraries and data
library(mia)
library(knitr)

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

dim(tse)
##  [1] 19216    26
Note

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:

# Show the frequency of each value
tse$SampleType |>
    table() |>
    kable()
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).

# Subset by sample
tse_sub <- tse[, tse$SampleType %in% c("Feces", "Skin", "Tongue")]

# Show dimensions
dim(tse_sub)
##  [1] 19216     9
Note

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:

# Show the frequency of each value
rowData(tse)$Phylum |>
    table() |>
    head() |>
    kable()
Var1 Freq
ABY1_OD1 7
AC1 1
AD3 9
Acidobacteria 1021
Actinobacteria 1631
Armatimonadetes 61
Note

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.

# Subset by feature
selected <- rowData(tse)$Phylum %in% c("Actinobacteria", "Chlamydiae")
tse_sub <- tse[selected, ]

# Show dimensions
dim(tse_sub)
##  [1] 1652   26

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.

# Subset by sample and feature
selected_rows <- rowData(tse)$Phylum %in% c("Actinobacteria", "Chlamydiae")
selected_cols <- tse$SampleType %in% c("Feces", "Skin", "Tongue")
tse_sub <- tse[selected_rows, selected_cols]

# Show dimensions
dim(tse_sub)
##  [1] 1652    9
Note

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

tse_sub <- subsetBy(
    tse,
    rows = Phylum %in% c("Actinobacteria", "Chlamydiae"),
    cols = SampleType %in% c("Feces", "Skin", "Tongue")
)

# Show dimensions
dim(tse_sub)
##  [1] 1652    9

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.

ind <- rowData(tse)$Species %in% "Achromatiumoxaliferum"
tse_sub <- tse[ind, ]

Then we can calculate the total number of counts in each sample.

tse_sub <- addQC(tse_sub)
# List total counts of each sample
tse_sub$total |> head()
##  [1] 0 0 0 0 0 0

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: NULL

We 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()
Histogram with the standard deviation of feature counts on a log10 x-axis and the number of features on the y-axis.
Figure 8.1: Histogram of the standard deviations of feature counts in the GlobalPatterns dataset, shown on a logarithmic x-axis.

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: NULL

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

Tidy alternative

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.

The tidyomics ecosystem: Enhancing omic data analyses. Hutchison et al. (2024). Nat Methods 21:1166–1170. doi:10.1038/s41592-024-02299-2.
Welcome to the tidyverse. Wickham et al. (2019). J Open Source Softw 4:1686. doi:10.21105/joss.01686.

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: NULL

8.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: NULL

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

Exercise 1: Rows and columns

Goal: Predict how subsetting changes the dimensions of the data.

The Tengeler2020 dataset has 151 features and 27 samples, so dim(tse) returns 151 27. The samples come from three cohorts: 10 samples from "Cohort_1", 10 from "Cohort_2" and 7 from "Cohort_3".

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

  1. What is the difference between tse[x, ] and tse[, x]?

  2. You select the samples of "Cohort_1" and "Cohort_3". What are the dimensions of the result?

  3. You select the features of a phylum. Which dimension of the data changes, and which stays the same?

  4. When you select features based on a rowData column, why might you need to remove the NA values?

  1. tse[x, ] selects rows, that is, features, and keeps all samples. tse[, x] selects columns, that is, samples, and keeps all features.

  2. The number of samples is 10 + 7 = 17, and all features are kept, so the dimensions are 151 17.

  3. The number of rows (features) decreases, while the number of columns (samples) stays the same.

  4. Features with an unknown taxonomy can have NA in the rowData column. For example, comparing NA with == gives NA instead of TRUE or FALSE, and subsetting the data with a vector that contains NA values gives an error. Removing the NA values from the selection makes sure that only the features of interest are selected. Note that %in% never returns NA: it returns FALSE for the NA values.

Exercise 2: Subset by sample

Goal: Subset the data by samples based on a colData variable.

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

  2. Show the frequency of each value in the cohort column.

  3. Select the samples of "Cohort_1" and "Cohort_2". Store the result in a variable called tse_samples.

  4. Check the dimensions of tse_samples. Is the number of samples equal to the sum of the frequencies of the selected cohorts?

Useful functions: data(), dim(), table(), %in%

library(mia)

# 1. Load the data
data("Tengeler2020", package = "mia")
tse <- Tengeler2020
dim(tse)
##  [1] 151  27

# 2. Frequency of each cohort
table(tse$cohort)
##  
##  Cohort_1 Cohort_2 Cohort_3 
##        10       10        7

# 3. Subset by sample
tse_samples <- tse[, tse$cohort %in% c("Cohort_1", "Cohort_2")]

# 4. Check the dimensions
dim(tse_samples)
##  [1] 151  20
  1. The number of columns should equal the sum of the frequencies of "Cohort_1" and "Cohort_2" in the table, while the number of rows stays the same.
Exercise 3: Subset by feature

Goal: Subset the data by features based on a rowData variable, and by samples and features at once.

  1. Show the frequency of each value in the Phylum column of rowData.

  2. Select the features that belong to the phyla Proteobacteria and Verrucomicrobia. Make sure that features with NA as their phylum are not selected. Store the result in a variable called tse_features.

  3. Check the dimensions of tse_features. Is the number of features equal to the sum of the frequencies of the selected phyla?

  4. Select the features of step 2 and the samples of Exercise 2 at once. Store the result in a variable called tse_both. Check its dimensions.

Useful functions: rowData(), table(), %in%, dim()

# 1. Frequency of each phylum
table(rowData(tse)$Phylum)
##  
##    Bacteroidetes   Cyanobacteria      Firmicutes  Proteobacteria 
##               44               1              97               7 
##  Verrucomicrobia 
##                2

# 2. Subset by feature
selected_rows <- rowData(tse)$Phylum %in%
    c("Proteobacteria", "Verrucomicrobia")
tse_features <- tse[selected_rows, ]

# 3. Check the dimensions
dim(tse_features)
##  [1]  9 27

# 4. Subset by sample and feature
selected_cols <- tse$cohort %in% c("Cohort_1", "Cohort_2")
tse_both <- tse[selected_rows, selected_cols]
dim(tse_both)
##  [1]  9 20
  1. %in% returns FALSE for the features whose phylum is NA, so they are not selected.

  2. The number of rows should equal the sum of the frequencies of Proteobacteria and Verrucomicrobia in the table, while the number of columns stays the same.

  3. The number of rows equals that of tse_features and the number of columns equals that of tse_samples from Exercise 2.

Exercise 4: Remove empty samples

Goal: Remove samples that do not contain any counts after subsetting.

  1. Select the features whose genus is Blautia. Store the result in a variable called tse_blautia. Make sure that features with NA as their genus are not selected.

  2. Calculate the total number of counts in each sample of tse_blautia. Show the first values.

  3. Remove the samples whose total number of counts is 0. Check the dimensions of the result.

  4. Why can samples become empty after subsetting features?

Useful functions: rowData(), %in%, mia::addQC(), head(), dim()

# 1. Select the features of Blautia
ind <- rowData(tse)$Genus %in% c("Blautia")
tse_blautia <- tse[ind, ]

# 2. Total number of counts in each sample
tse_blautia <- addQC(tse_blautia)
head(tse_blautia$total)
##  [1]  422  388 1622    0    0  234

# 3. Remove empty samples
tse_blautia <- tse_blautia[, tse_blautia$total != 0]
dim(tse_blautia)
##  [1]  8 20
  1. As in Exercise 3, %in% returns FALSE for the features whose genus is NA, so they are not selected.

  2. After subsetting, the data contains only the selected features. If none of these features was detected in a sample, all its counts are zero. Such a sample does not contain any information on the selected features.

Exercise 5: Filter out zero-variance features

Goal: Find and remove features that do not vary across samples.

  1. Select the samples of "Cohort_3" and store the result in a variable called tse_cohort3.

  2. Calculate the quality control metrics for each feature of tse_cohort3 from the counts assay.

  3. Visualize the standard deviations of the features with a histogram. Use a logarithmic x-axis.

  4. Remove the features whose standard deviation is 0. Store the result in a variable called tse_var. Compare the number of features in tse_cohort3 and tse_var.

  5. All features vary across the samples of the whole dataset. Why can zero-variance features appear after selecting only some of the samples?

Useful functions: mia::addQC(), miaViz::plotHistogram(), ggplot2::scale_x_log10(), rowData(), nrow()

library(miaViz)

# 1. Select the samples of Cohort_3
tse_cohort3 <- tse[, tse$cohort == "Cohort_3"]

# 2. Quality control metrics for each feature
tse_cohort3 <- addQC(tse_cohort3, assay.type = "counts", by = "rows")

# 3. Histogram of standard deviations
plotHistogram(tse_cohort3, row.var = "sd") +
    scale_x_log10()


# 4. Remove zero-variance features
tse_var <- tse_cohort3[rowData(tse_cohort3)[["sd"]] > 0, ]
nrow(tse_cohort3)
##  [1] 151
nrow(tse_var)
##  [1] 129
  1. Features with a standard deviation of zero cannot be shown on a logarithmic axis, so they are left out of the histogram.

  2. A feature has zero variance when it has the same count in every sample. Typically, this happens when a feature is not detected in any of the selected samples, so all its counts are zero. The fewer samples there are, the more likely this is.

Exercise 6: Subset based on prevalence

Goal: Subset the data to prevalent or rare features.

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

  2. Subset tse to the features with a prevalence over 0.2. Store the result in a variable called tse_prevalent.

  3. Subset tse to the rest of the features, that is, the rare features. Store the result in a variable called tse_rare.

  4. Check the number of features in tse_prevalent and tse_rare.

  5. What does it mean that a feature is prevalent with these thresholds?

  6. How are the features in tse_prevalent and tse_rare related to each other?

Useful functions: mia::addPrevalence(), mia::subsetBy(), nrow()

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

# 2. Prevalent features
tse_prevalent <- subsetBy(tse, rows = prevalence > 0.2)

# 3. Rare features
tse_rare <- subsetBy(tse, rows = prevalence <= 0.2)

# 4. Number of features
nrow(tse_prevalent)
##  [1] 120
nrow(tse_rare)
##  [1] 31
  1. A feature is detected in a sample if it has more than 1 count in it. It is prevalent if it is detected in more than 20% of the samples.

  2. The two subsets are complementary: each feature is either prevalent or rare. Together, they contain all features of the data.

Exercise 7: Collapse rare features

Goal: Combine rare features into a single feature.

  1. Keep the features with a prevalence over 0.2 and combine the rest into a single feature with subsetBy() and collapse = TRUE. Use the prevalence that you added in Exercise 6. Store the result in a variable called tse_prev.

  2. How many rows does tse_prev have? Show the last row names. Which feature contains the rare features?

Useful functions: mia::subsetBy(), nrow(), rownames(), tail()

# 1. Keep prevalent features and combine the rest
tse_prev <- subsetBy(tse, rows = prevalence > 0.2, collapse = TRUE)

# 2. Number of rows and the last row names
nrow(tse_prev)
##  [1] 121
rownames(tse_prev) |> tail()
##  [1] "Unidentified_Ruminococcaceae_1"  "Catabacter_1"                   
##  [3] "Bacteroides_17"                  "Lachnoclostridium_4"            
##  [5] "Unidentified_Lachnospiraceae_14" "Other"
  1. The features that have more than 1 count in more than 20% of the samples are kept as they are. All other features are summed into the last row, which is called “Other”.
Exercise 8: Keep top features

Goal: Keep the most abundant features and combine the rest into a single feature.

  1. Find the 10 features with the highest mean counts with getTop(). Store the result in a variable called top_features.

  2. Keep the top features and combine the rest into a single feature with subsetBy() and collapse = TRUE. Store the result in a variable called tse_top.

  3. How many rows does tse_top have? Show its row names.

  4. Calculate the total counts of the samples in tse and tse_top with addQC(), and compare them. Why are they the same?

Useful functions: mia::getTop(), mia::subsetBy(), %in%, nrow(), rownames(), mia::addQC(), all()

# 1. Top 10 features by mean
top_features <- getTop(tse, top = 10, method = "mean")

# 2. Keep top features and combine the rest
tse_top <- subsetBy(
    tse,
    rows = rownames(tse) %in% top_features, collapse = TRUE
)

# 3. Number of rows and row names
nrow(tse_top)
##  [1] 11
rownames(tse_top)
##   [1] "Bacteroides"       "Bacteroides_1"     "Parabacteroides"  
##   [4] "Bacteroides_2"     "Akkermansia"       "Bacteroides_3"    
##   [7] "Parabacteroides_1" "Bacteroides_4"     "Bacteroides_5"    
##  [10] "Parabacteroides_2" "Other"

# 4. Total counts of the samples
tse <- addQC(tse)
tse_top <- addQC(tse_top)
all(tse$total == tse_top$total)
##  [1] TRUE
  1. tse_top has 11 rows: the 10 top features and “Other”, which contains the sum of all other features.

  2. The features that are not among the top features are not removed but summed into “Other”. Therefore, the total counts of the samples do not change.

Back to top