3  Data elements

This chapter provides an introduction to the TreeSummarizedExperiment (TreeSE) (Huang et al. 2021) and MultiAssayExperiment (MAE) data containers introduced in Section 1.2. In microbiome data science, these containers link taxonomic abundance tables with rich side information on the features and samples.

SummarizedExperiment: SummarizedExperiment container. Morgan et al. (2020). R package version 1.20.0. https://bioconductor.org/packages/SummarizedExperiment.

One key advantage of the SummarizedExperiment (Morgan et al. 2020) ecosystem is its flexibility and generalizability. While taxonomic features remain central in microbiome studies, there is growing interest in analyzing and integrating diverse types of features. These may include:

In addition, these data tables often exist in multiple versions, derived through transformations or agglomerations. We start by providing recommendations on how to represent different varieties of multi-table data within the TreeSE class. The options and recommendations are summarized in Table 3.1.

3.1 Structure of TreeSE

TreeSE contains several distinct slots, each holding a specific type of data. The assays slot is the core of TreeSE, storing abundance tables that contain the counts or concentrations of features in each sample. Features can be taxonomic, metabolomic, antimicrobial resistance genes, or other measured entities, and are represented as rows. The columns correspond to unique samples.

Building upon the assays, TreeSE accommodates various data types for both features and samples. In rowData, the rows correspond to the same features (rows) as in the abundance tables, while the columns represent variables such as taxonomy ranks. Similarly, in colData, each row matches the samples (columns) from the abundance tables, with the columns of colData containing metadata like disease status or patient ID and time point if the dataset includes time series.

The slots in TreeSE are outlined below:

  • assays: Stores a list of abundance tables. Each table has consistent rows and columns, where rows represent features and columns represent samples.
  • rowData: Contains metadata about the rows (features). For example, this slot can include a taxonomy table.
  • colData: Holds metadata about the columns (samples), such as patient information or the time points when samples were collected.
  • rowTree: Stores a hierarchical tree for the rows, such as a phylogenetic tree representing the relationships between features.
  • colTree: Includes a hierarchical tree for the columns, which can represent relationships between samples, for example, indicating whether patients are relatives and the structure of those relationships.
  • rowLinks: Contains information about the linkages between rows and the nodes in the rowTree.
  • colLinks: Contains information about the linkages between columns and the nodes in the colTree.
  • referenceSeq: Holds reference sequences, i.e., the sequences that correspond to each taxon identified in the rows.
  • metadata: Contains metadata about the experiment, such as the date it was conducted and the researchers involved.

These slots are illustrated in Figure 3.1.

TreeSE slots: assays with samples as columns and features as rows, rowData and rowLinks, colData and colLinks, rowTree and colTree, referenceSeq and metadata.
Figure 3.1: The structure of a TreeSummarizedExperiment (TreeSE) object (Huang et al. 2021).
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.

Additionally, TreeSE includes:

  • reducedDim: Contains reduced dimensionality representations of the samples, such as Principal Component Analysis (PCA) results (see Chapter 13).
  • altExp: Stores alternative experiments, which are TreeSE objects sharing the same samples but with different feature sets.

Among these, assays, rowData, colData, and metadata are shared with the SummarizedExperiment (SE) data container. reducedDim and altExp come from inheriting the SingleCellExperiment (SCE) class (Amezquita et al. 2020). The rowTree, colTree, rowLinks, colLinks, and referenceSeq slots are unique to TreeSE.

Orchestrating single-cell analysis with Bioconductor. Amezquita et al. (2020). Nat Methods 17:137–145. doi:10.1038/s41592-019-0654-x.

3.2 Rows and columns

Let us load the GlobalPatterns data (Caporaso et al. 2011) (Section D.1) and store it in variable tse.

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.
library(mia)
data("GlobalPatterns", package = "mia")
tse <- GlobalPatterns
tse
##  class: TreeSummarizedExperiment 
##  dim: 19216 26 
##  metadata(0):
##  assays(1): counts
##  rownames(19216): 549322 522457 ... 200359 271582
##  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: a LinkDataFrame (19216 rows)
##  rowTree: 1 phylo tree(s) (19216 leaves)
##  colLinks: NULL
##  colTree: NULL

The TreeSE object, similar to a standard data.frame or matrix, has rows and columns. Typically, samples are stored in columns, while features are stored in rows. You can extract subsets of the data, such as the first five rows (first five features) and certain three columns (certain three samples). The object manages the linkages between data (e.g., the assay data and the sample metadata), ensuring that when you subset the data object, all its parts are subsetted simultaneously, such that they remain matched with each other.

tse <- tse[1:5, c(1, 19, 16)]
tse
##  class: TreeSummarizedExperiment 
##  dim: 5 3 
##  metadata(0):
##  assays(1): counts
##  rownames(5): 549322 522457 951 244423 586076
##  rowData names(7): Kingdom Phylum ... Genus Species
##  colnames(3): CL3 TRRsed1 NP2
##  colData names(7): X.SampleID Primer ... SampleType Description
##  reducedDimNames(0):
##  mainExpName: NULL
##  altExpNames(0):
##  rowLinks: a LinkDataFrame (5 rows)
##  rowTree: 1 phylo tree(s) (19216 leaves)
##  colLinks: NULL
##  colTree: NULL

Compared to the original data, the dimensions for rows and columns are 5 and 3, respectively.

Note

SummarizedExperiment objects have rows and columns. MultiAssayExperiment objects, introduced in Section 3.8, also have rows and columns but the structure is more complicated. You can find more examples of subsetting in Chapter 8.

3.3 Assay data

When studying microbiomes, the primary type of data is in the form of abundance of given microbes in given samples. This sample per feature table forms the core of the TreeSE object, called the ‘assay data’.

An assay is a measurement of the presence and abundance of different taxonomic features in a sample. The assay data records this in a table where rows are unique features and columns are unique samples and each entry contains a number describing the amount a given feature is present in a given sample. Note that when storing assays, the original data is count-based. However, due to the nature of how microbiome data is produced, these count-based abundances rarely reflect the true counts of features in the sample, and thus the abundance tables often undergo different transformations, such as logarithmic, Centered Log-Ratio (CLR), or relative abundance to make these abundance values comparable with each other. See Chapter 10 for more information on transformations.

The microbial abundance tables are stored in assays. The assays slot contains the abundance data as one or more matrices (e.g. counts and their transformations). The result of assays is a list of matrices.

assays(tse)
##  List of length 1
##  names(1): counts

Individual assays can be accessed via assay.

assay(tse, "counts") |> head()
##         CL3 TRRsed1 NP2
##  549322   0       0   1
##  522457   0       0   0
##  951      0       0   0
##  244423   0       0   0
##  586076   0       0   0

In summary, in the world of microbiome analysis, an assay is essentially a way to describe the composition of microbes in a given sample. This way we can summarize the microbiome profile of a human gut or a sample of soil.

Furthermore, to illustrate the use of multiple assays, we can create an empty matrix and add it to the object.

mat <- matrix(nrow = nrow(tse), ncol = ncol(tse))
assay(tse, "empty_table", withDimnames = FALSE) <- mat
assays(tse)
##  List of length 2
##  names(2): counts empty_table

Now there are two assays available in the tse object, counts and empty_table.

assay(tse, "empty_table") |> head()
##         CL3 TRRsed1 NP2
##  549322  NA      NA  NA
##  522457  NA      NA  NA
##  951     NA      NA  NA
##  244423  NA      NA  NA
##  586076  NA      NA  NA

Here the dimension of the assay data remains unchanged. This is, in fact, a requirement for the assays.

3.4 Sample data (colData)

colData contains information about the samples used in the study. This sample metadata can include details such as the sample ID, the primers used in the analysis, the barcodes associated with the sample (truncated or complete), the type of sample (e.g. soil, fecal, mock) and a description of the sample.

colData(tse)
##  DataFrame with 3 rows and 7 columns
##          X.SampleID   Primer Final_Barcode Barcode_truncated_plus_T
##            <factor> <factor>      <factor>                 <factor>
##  CL3        CL3      ILBC_01        AACGCA                   TGCGTT
##  TRRsed1    TRRsed1  ILBC_22        ACATGT                   ACATGT
##  NP2        NP2      ILBC_19        ACAGTT                   AACTGT
##          Barcode_full_length         SampleType
##                     <factor>           <factor>
##  CL3             CTAGCGTGCGT Soil              
##  TRRsed1         CACGTGACATG Sediment (estuary)
##  NP2             TCGCGCAACTG Ocean             
##                                       Description
##                                          <factor>
##  CL3     Calhoun South Carolina Pine soil, pH 4.9
##  TRRsed1 Tijuana River Reserve, depth 1          
##  NP2     Newport Pier, CA surface water, Time 1

To illustrate, X.SampleID gives the sample identifier, SampleType indicates the sample type (e.g. soil, fecal matter, control) and Description provides an additional description of the sample.

3.5 Feature data (rowData)

rowData contains data on the features, such as taxonomic features of the analyzed samples. This is particularly important in the microbiome field for storing taxonomic information, such as the Species, Genus or Family of the different microorganisms present in samples. This taxonomic information is extremely important for understanding the composition and diversity of the microbiome in each sample.

rowData(tse)
##  DataFrame with 5 rows and 7 columns
##             Kingdom        Phylum        Class        Order        Family
##         <character>   <character>  <character>  <character>   <character>
##  549322     Archaea Crenarchaeota Thermoprotei           NA            NA
##  522457     Archaea Crenarchaeota Thermoprotei           NA            NA
##  951        Archaea Crenarchaeota Thermoprotei Sulfolobales Sulfolobaceae
##  244423     Archaea Crenarchaeota        Sd-NA           NA            NA
##  586076     Archaea Crenarchaeota        Sd-NA           NA            NA
##               Genus                Species
##         <character>            <character>
##  549322          NA                     NA
##  522457          NA                     NA
##  951     Sulfolobus Sulfolobusacidocalda..
##  244423          NA                     NA
##  586076          NA                     NA

3.6 Trees (row/colTree)

Phylogenetic trees play an important role in the microbiome field. Many times it is useful to know how closely related the taxonomic features present in the data are. For example, to calculate widely-used phylogenetically weighted microbiome dissimilarity metrics such as UniFrac (Lozupone and Knight 2005), we need information on not only the presence and abundance of taxonomic features in each sample but also the evolutionary relatedness among these taxonomic features. The TreeSE class can keep track of relations among features via two functions, rowTree and rowLinks.

UniFrac: A new phylogenetic method for comparing microbial communities. Lozupone et al. (2005). Appl Environ Microbiol 71:8228–8235. doi:10.1128/aem.71.12.8228-8235.2005.

A tree can be accessed via rowTree as a phylo object.

rowTree(tse)
##  
##  Phylogenetic tree with 19216 tips and 19215 internal nodes.
##  
##  Tip labels:
##    549322, 522457, 951, 244423, 586076, 246140, ...
##  Node labels:
##    , 0.858.4, 1.000.154, 0.764.3, 0.995.2, 1.000.2, ...
##  
##  Rooted; includes branch length(s).

Note that subsetting the rows does not prune the tree; it still contains all 19216 tips of the original data.

Each row in TreeSE is linked to a specific node in a tree. This relationship is stored in the rowLinks slot, which has the same rows as TreeSE. The rowLinks slot contains information about which tree node corresponds to each row and whether the node is a leaf (tip) or an internal node, among other details.

rowLinks(tse)
##  LinkDataFrame with 5 rows and 5 columns
##        nodeLab   nodeNum nodeLab_alias    isLeaf   whichTree
##    <character> <integer>   <character> <logical> <character>
##  1      549322         1       alias_1      TRUE       phylo
##  2      522457         2       alias_2      TRUE       phylo
##  3         951         3       alias_3      TRUE       phylo
##  4      244423         4       alias_4      TRUE       phylo
##  5      586076         5       alias_5      TRUE       phylo

Please note that there can be a 1:1 relationship between tree nodes and features; however, this is not required. This means there can be features that are not linked to nodes, and nodes that are not linked to features. To change the links in an existing object, the changeTree() function is available.

Similarly, a tree for the samples can be stored with colTree, and the links between samples and tree nodes in colLinks. This can hold, for instance, a hierarchical clustering of the samples.

3.7 Alternative experiments

Alternative experiments (altExp) complement assays. They can contain complementary data, which is no longer tied to the same dimensions as the assay data. However, the number of samples (columns) must be the same.

This can come into play, for instance, when one has taxonomic abundance profiles quantified using different measurement technologies, such as phylogenetic microarrays, amplicon sequencing, or metagenomic sequencing. Another common use case is including abundance tables for different taxonomic ranks. Such alternative experiments concerning the same set of samples can be stored as

  1. Separate assays assuming that the taxonomic information can be mapped between features directly 1:1; or
  2. Data in the altExp slot of the TreeSE, if the feature dimensions differ. Each element of the altExp slot is an SE or an object from a derived class with independent feature data.

The following shows how to store a subset of the features as an alternative experiment. In practice, it could be, e.g., the data agglomerated to another taxonomic rank, or data from an entirely different measurement source (e.g., 16S amplicon and metagenomic sequence data), as long as the samples match (Figure 3.2).

Three stacked grids with the same six columns: a main experiment with eight species rows, an altExp called genus with four rows and an altExp called phylum with two rows. A dashed box around the first column spans all three grids.
Figure 3.2: Alternative experiments. The main experiment and each alternative experiment have their own features (rows) but share the same samples (columns). Subsetting the samples, for example with tse[, 1], therefore applies to all of them.

Let us first subset the data so that it has only two rows.

tse_sub <- tse[1:2, ]

# Both have the same number of columns (samples)
dim(tse)
##  [1] 5 3
dim(tse_sub)
##  [1] 2 3

Then we can add the new data object as an alternative experiment in the original data.

# Add the new data object to the original data object as an alternative
# experiment with the specified name
altExp(tse, "subsetted") <- tse_sub

# Retrieve and display the names of alternative experiments available
altExpNames(tse)
##  [1] "subsetted"

Now, if we subset the data, this acts on both the altExp and the assay data.

tse_single_sample <- tse[, 1]
dim(altExp(tse_single_sample, "subsetted"))
##  [1] 2 1

When an analysis expects the data of interest in the main experiment, an alternative experiment can be promoted temporarily with swapAltExp(). The previous main experiment is retained as an alternative experiment, so the operation can be reversed without losing any data. We set withColData = FALSE, because by default swapAltExp() adds the colData of the main experiment to that of the promoted experiment, which would duplicate the colData columns.

# Give a name for the main experiment, if it doesn't already have one
mainExpName(tse) <- "original"

# Promote the alternative experiment for an analysis
tse <- swapAltExp(tse, "subsetted", withColData = FALSE)
tse
##  class: TreeSummarizedExperiment 
##  dim: 2 3 
##  metadata(0):
##  assays(2): counts empty_table
##  rownames(2): 549322 522457
##  rowData names(7): Kingdom Phylum ... Genus Species
##  colnames(3): CL3 TRRsed1 NP2
##  colData names(7): X.SampleID Primer ... SampleType Description
##  reducedDimNames(0):
##  mainExpName: subsetted
##  altExpNames(1): original
##  rowLinks: a LinkDataFrame (2 rows)
##  rowTree: 1 phylo tree(s) (19216 leaves)
##  colLinks: NULL
##  colTree: NULL

# Restore the original main experiment
tse <- swapAltExp(tse, "original", withColData = FALSE)
tse
##  class: TreeSummarizedExperiment 
##  dim: 5 3 
##  metadata(0):
##  assays(2): counts empty_table
##  rownames(5): 549322 522457 951 244423 586076
##  rowData names(7): Kingdom Phylum ... Genus Species
##  colnames(3): CL3 TRRsed1 NP2
##  colData names(7): X.SampleID Primer ... SampleType Description
##  reducedDimNames(0):
##  mainExpName: original
##  altExpNames(1): subsetted
##  rowLinks: a LinkDataFrame (5 rows)
##  rowTree: 1 phylo tree(s) (19216 leaves)
##  colLinks: NULL
##  colTree: NULL

For more details on altExp, you can check the introduction to the SingleCellExperiment package (Lun and Risso 2020).

SingleCellExperiment: S4 classes for single cell data. Lun et al. (2020). R package version 1.12.0.

3.8 Multiple experiments

Multiple experiments relate to complementary measurement types from the same samples, such as transcriptomic or metabolomic profiling of the microbiome. Multiple experiments can be represented using the same options as alternative experiments, or by using the MAE class (Ramos et al. 2017). Depending on how the datasets relate to each other the data can be stored as:

  1. altExp if the samples can be matched directly 1:1; or
  2. As MAE objects, in which the connections between samples are defined through a sampleMap. Each element of the ExperimentList of an MAE is a matrix or a matrix-like object, including SE objects, and the number of samples can differ between the elements.

In an MAE, the “subjects” represent patients. The MAE has three main slots, with experiments being the core. This slot holds a list of experiments, each in (Tree)SE format. To handle complex mappings between samples (observations) across different experiments, the sampleMap slot stores information about how each sample in the experiments is linked to a patient. Metadata for each patient is stored in the colData slot. Unlike the colData in TreeSE, this colData is meant to store only metadata that remains constant throughout the trial.

  • experiments: Contains experiments, such as different omics data, in TreeSE format.
  • sampleMap: Holds linkages between patients (subjects) and samples in the experiments (observations).
  • colData: Includes patient metadata that remains unchanged throughout the trial.

These slots are illustrated in Figure 3.3.

MAE slots: experiments holding several assays, colData with one row per subject, and sampleMap linking each assay column to a subject.
Figure 3.3: The structure of MultiAssayExperiment (MAE) object (Ramos et al. 2017).
Software for the integration of multiomics experiments in Bioconductor. Ramos et al. (2017). Cancer Res 77:e39–e42. doi:10.1158/0008-5472.CAN-17-0344.

Additionally, the object includes a metadata slot that contains information about the dataset, such as the trial period and the creator of the MAE object.

The MAE object can handle more complex relationships between experiments. It manages the linkages between samples and experiments, ensuring that the data remains consistent and well-organized.

data("HintikkaXOData", package = "mia")
mae <- HintikkaXOData
mae
##  A MultiAssayExperiment object of 3 listed
##   experiments with user-defined names and respective classes.
##   Containing an ExperimentList class object of length 3:
##   [1] microbiota: TreeSummarizedExperiment with 12706 rows and 40 columns
##   [2] metabolites: TreeSummarizedExperiment with 38 rows and 40 columns
##   [3] biomarkers: TreeSummarizedExperiment with 39 rows and 40 columns
##  Functionality:
##   experiments() - obtain the ExperimentList instance
##   colData() - the primary/phenotype DataFrame
##   sampleMap() - the sample coordination DataFrame
##   `$`, `[`, `[[` - extract colData columns, subset, or experiment
##   *Format() - convert into a long or wide DataFrame
##   assays() - convert ExperimentList to a SimpleList of matrices
##   exportClass() - save data to flat files

The sampleMap is a crucial component of the MAE object as it acts as an important bookkeeper, maintaining the information about which samples are associated with which experiments. This ensures that data linkages are correctly managed and preserved across different types of measurements.

sampleMap(mae) |> head()
##  DataFrame with 6 rows and 3 columns
##         assay     primary     colname
##      <factor> <character> <character>
##  1 microbiota          C1          C1
##  2 microbiota          C2          C2
##  3 microbiota          C3          C3
##  4 microbiota          C4          C4
##  5 microbiota          C5          C5
##  6 microbiota          C6          C6

For illustration, let’s subset the data by taking the first five samples.

mae <- mae[, 1:5, ]
mae
##  A MultiAssayExperiment object of 3 listed
##   experiments with user-defined names and respective classes.
##   Containing an ExperimentList class object of length 3:
##   [1] microbiota: TreeSummarizedExperiment with 12706 rows and 5 columns
##   [2] metabolites: TreeSummarizedExperiment with 38 rows and 5 columns
##   [3] biomarkers: TreeSummarizedExperiment with 39 rows and 5 columns
##  Functionality:
##   experiments() - obtain the ExperimentList instance
##   colData() - the primary/phenotype DataFrame
##   sampleMap() - the sample coordination DataFrame
##   `$`, `[`, `[[` - extract colData columns, subset, or experiment
##   *Format() - convert into a long or wide DataFrame
##   assays() - convert ExperimentList to a SimpleList of matrices
##   exportClass() - save data to flat files
Note

If you have multiple experiments containing multiple measures from the same sources (e.g., patients/host, individuals/sites), you can utilize the MultiAssayExperiment object to keep track of which samples belong to which patient.

The following dataset (Section D.10) illustrates how to utilize the sample mapping system in MAE. It includes two omics datasets: biogenic amines and fatty acids, collected from 10 chickens.

mae
##  A MultiAssayExperiment object of 2 listed
##   experiments with user-defined names and respective classes.
##   Containing an ExperimentList class object of length 2:
##   [1] BIOGENIC AMINES: TreeSummarizedExperiment with 7 rows and 14 columns
##   [2] FATTY ACIDS: TreeSummarizedExperiment with 19 rows and 19 columns
##  Functionality:
##   experiments() - obtain the ExperimentList instance
##   colData() - the primary/phenotype DataFrame
##   sampleMap() - the sample coordination DataFrame
##   `$`, `[`, `[[` - extract colData columns, subset, or experiment
##   *Format() - convert into a long or wide DataFrame
##   assays() - convert ExperimentList to a SimpleList of matrices
##   exportClass() - save data to flat files

We can see that there are more than ten samples per omic dataset due to multiple samples from different time points collected for some animals. From the colData of MAE, we can observe the individual animal metadata, including information that remains constant throughout the trial.

colData(mae)[, c("Treatment name", "Trial description", "animal")]
##  DataFrame with 10 rows and 3 columns
##                 Treatment name Trial description         animal
##                    <character>       <character>    <character>
##  SAMEA112904734      Probiotic           Trial 2 SAMEA112904734
##  SAMEA112904735        Control           Trial 3 SAMEA112904735
##  SAMEA112904737        Control           Trial 2 SAMEA112904737
##  SAMEA112904741        Control           Trial 3 SAMEA112904741
##  SAMEA112904746        Control           Trial 2 SAMEA112904746
##  SAMEA112904748      Probiotic           Trial 3 SAMEA112904748
##  SAMEA112904749        Control           Trial 1 SAMEA112904749
##  SAMEA112904755        Control           Trial 2 SAMEA112904755
##  SAMEA112904762      Probiotic           Trial 3 SAMEA112904762
##  SAMEA112904763        Control           Trial 1 SAMEA112904763

The sampleMap slot now contains mappings between each unique sample and the corresponding individual animal. There are as many rows as there are total samples.

The “colname” column refers to the samples in the omic dataset identified in the “assay” column, while the “primary” column provides information about the animals. You will notice that some animals are listed multiple times, reflecting the multiple omics and time points collected for those individuals.

sampleMap(mae)
##  DataFrame with 33 rows and 3 columns
##                assay        primary        colname
##             <factor>    <character>    <character>
##  1   BIOGENIC AMINES SAMEA112904734 SAMEA112906114
##  2   BIOGENIC AMINES SAMEA112904734 SAMEA112906592
##  3   BIOGENIC AMINES SAMEA112904735 SAMEA112906338
##  4   BIOGENIC AMINES SAMEA112904735 SAMEA112906810
##  5   BIOGENIC AMINES SAMEA112904737 SAMEA112906123
##  ...             ...            ...            ...
##  29      FATTY ACIDS SAMEA112904755 SAMEA112906112
##  30      FATTY ACIDS SAMEA112904755 SAMEA112906590
##  31      FATTY ACIDS SAMEA112904762 SAMEA112906315
##  32      FATTY ACIDS SAMEA112904762 SAMEA112906787
##  33      FATTY ACIDS SAMEA112904763 SAMEA112905916

For more information, have a look at the intro vignette of the MultiAssayExperiment package.

Storing multiple data tables
Table 3.1: The assays are best suited for data transformations (one-to-one match between rows and columns across the assays). The alternative experiments are particularly suitable for alternative versions of the data that are of same type but may have a different number of features (e.g. taxonomic groups); this is for instance the case with taxonomic abundance tables agglomerated at different levels (e.g. genus vs. phylum) or alternative profiling technologies (e.g. amplicon sequencing vs. shallow shotgun metagenomics). For alternative experiments one-to-one match between samples (cols) is required but the alternative experiment tables can have different numbers of features (rows). Finally, elements of the MAE provide the most flexible way to incorporate multi-omic data tables with flexible numbers of samples and features. We recommend these conventions as the basis for methods development and application in microbiome studies.
Option Rows (features) Cols (samples) Recommended
assays match match Data transformations
altExp free match Alternative experiments
MultiAssay free free (mapping) Multi-omic experiments

Multi-assay analyses, discussed in Introduction to multi-omics can be facilitated by the multi-assay data containers, TreeSummarizedExperiment and MultiAssayExperiment. These are scalable and contain different types of data in a single container, making this framework particularly suited for multi-assay microbiome data incorporating different types of complementary data sources in a single, reproducible workflow. An alternative experiment can be stored in the altExp slot of the SCE (and thus TreeSE) data container. Alternatively, both experiments can be stored side-by-side in an MAE data container.

3.9 Exercises

In Exercises 2-5, we use the GlobalPatterns dataset, and in Exercise 6 the HintikkaXOData dataset.

Solve the exercises in order, as Exercises 2-5 continue from each other. Try to solve each exercise yourself before opening the solution.

Exercise 1: Where is the data stored?

Goal: Choose a suitable slot or data container for each type of data.

Answer the following questions without writing any code. The list of slots in the beginning of this chapter and Table 3.1 will help you.

In which slot of a TreeSE object, or in which data container, would you store each of the following?

  1. The abundance table of counts

  2. A transformed copy of the abundance table, for example relative abundances

  3. The taxonomic classification of each feature

  4. The age and sex of the subject from whom each sample was collected

  5. A phylogenetic tree of the features

  6. An abundance table of the same samples agglomerated to the genus level

  7. Metabolomic data from the same subjects, measured from a different set of samples

  1. assays

  2. assays. A transformed table has the same features and samples as the original table, so it can be stored as another assay.

  3. rowData

  4. colData

  5. rowTree. The links between the features and the nodes of the tree are stored in rowLinks.

  6. altExp. The table has the same samples but fewer features than the original table, so it cannot be stored as an assay.

  7. An MAE object. The samples do not match one-to-one with the microbiome samples, so the connections between the samples and the subjects are stored in the sampleMap.

Exercise 2: Rows, columns and assays

Goal: Explore the dimensions and the assays of a TreeSE object, and subset it.

  1. Load the GlobalPatterns dataset from the mia package and store it in a variable called tse. Print tse to see an overview of the object.

  2. How many features (rows) and samples (columns) does tse have? Show the first names of the features and the samples.

  3. Fetch the list of assays. How many assays are there, and what are their names?

  4. Show the first rows and columns of the counts assay. Do you see many zeros? Why does microbiome data often contain many zeros?

  5. Subset tse to the first 10 features and the first 5 samples, and store the result in a variable called tse_sub. Check the dimensions of tse_sub and the number of rows in its colData.

  6. Create an empty matrix with the same dimensions as tse_sub, and add it to tse_sub as an assay called "empty_table". Fetch the list of assays again.

  7. Why must all the assays of a TreeSE object have the same dimensions?

Useful functions: data(), dim(), rownames(), colnames(), head(), SummarizedExperiment::assays(), SummarizedExperiment::assay(), SummarizedExperiment::colData(), matrix(), nrow(), ncol()

library(mia)

# 1. Load the data
data("GlobalPatterns", package = "mia")
tse <- GlobalPatterns
tse
##  class: TreeSummarizedExperiment 
##  dim: 19216 26 
##  metadata(0):
##  assays(1): counts
##  rownames(19216): 549322 522457 ... 200359 271582
##  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: a LinkDataFrame (19216 rows)
##  rowTree: 1 phylo tree(s) (19216 leaves)
##  colLinks: NULL
##  colTree: NULL

# 2. Dimensions and names of features and samples
dim(tse)
##  [1] 19216    26
head(rownames(tse))
##  [1] "549322" "522457" "951"    "244423" "586076" "246140"
head(colnames(tse))
##  [1] "CL3"     "CC1"     "SV1"     "M31Fcsw" "M11Fcsw" "M31Plmr"

# 3. List of assays
assays(tse)
##  List of length 1
##  names(1): counts

# 4. First rows and columns of the counts assay
assay(tse, "counts")[1:5, 1:5]
##         CL3 CC1 SV1 M31Fcsw M11Fcsw
##  549322   0   0   0       0       0
##  522457   0   0   0       0       0
##  951      0   0   0       0       0
##  244423   0   0   0       0       0
##  586076   0   0   0       0       0

# 5. Subset the data
tse_sub <- tse[1:10, 1:5]
dim(tse_sub)
##  [1] 10  5
nrow(colData(tse_sub))
##  [1] 5

# 6. Add an empty assay
mat <- matrix(nrow = nrow(tse_sub), ncol = ncol(tse_sub))
assay(tse_sub, "empty_table", withDimnames = FALSE) <- mat
assays(tse_sub)
##  List of length 2
##  names(2): counts empty_table
  1. Yes, most of the values are zeros. Most taxa are present only in some samples, and rare taxa might not be detected because only a limited number of reads is sequenced from each sample.

  2. When the TreeSE object is subsetted, all its parts are subsetted at the same time. Therefore, colData has 5 rows, one for each remaining sample, and it stays matched with the assays.

  1. Each row of an assay corresponds to a feature in rowData, and each column corresponds to a sample in colData. The assays can be linked to the feature and sample information only if they all have the same features and samples. Data with different features is stored in altExp instead.
Exercise 3: Sample and feature information

Goal: Explore the sample metadata and the feature metadata.

  1. Show the sample metadata of tse from Exercise 2. Which columns are available?

  2. Which sample types are found in the SampleType column, and how many samples are there of each type?

  3. Show the feature metadata of tse. Which columns are available, and what do they describe?

  4. Check that the row names of the sample metadata are the same as the column names of tse, and that the row names of the feature metadata are the same as the row names of tse. What do these names correspond to?

Useful functions: SummarizedExperiment::colData(), SummarizedExperiment::rowData(), colnames(), rownames(), table(), all()

# 1. Sample metadata
colData(tse)
##  DataFrame with 26 rows and 7 columns
##          X.SampleID   Primer Final_Barcode Barcode_truncated_plus_T
##            <factor> <factor>      <factor>                 <factor>
##  CL3        CL3      ILBC_01        AACGCA                   TGCGTT
##  CC1        CC1      ILBC_02        AACTCG                   CGAGTT
##  SV1        SV1      ILBC_03        AACTGT                   ACAGTT
##  M31Fcsw    M31Fcsw  ILBC_04        AAGAGA                   TCTCTT
##  M11Fcsw    M11Fcsw  ILBC_05        AAGCTG                   CAGCTT
##  ...            ...      ...           ...                      ...
##  TS28         TS28   ILBC_25        ACCAGA                   TCTGGT
##  TS29         TS29   ILBC_26        ACCAGC                   GCTGGT
##  Even1        Even1  ILBC_27        ACCGCA                   TGCGGT
##  Even2        Even2  ILBC_28        ACCTCG                   CGAGGT
##  Even3        Even3  ILBC_29        ACCTGT                   ACAGGT
##          Barcode_full_length SampleType
##                     <factor>   <factor>
##  CL3             CTAGCGTGCGT      Soil 
##  CC1             CATCGACGAGT      Soil 
##  SV1             GTACGCACAGT      Soil 
##  M31Fcsw         TCGACATCTCT      Feces
##  M11Fcsw         CGACTGCAGCT      Feces
##  ...                     ...        ...
##  TS28            GCATCGTCTGG      Feces
##  TS29            CTAGTCGCTGG      Feces
##  Even1           TGACTCTGCGG      Mock 
##  Even2           TCTGATCGAGG      Mock 
##  Even3           AGAGAGACAGG      Mock 
##                                         Description
##                                            <factor>
##  CL3     Calhoun South Carolina Pine soil, pH 4.9  
##  CC1     Cedar Creek Minnesota, grassland, pH 6.1  
##  SV1     Sevilleta new Mexico, desert scrub, pH 8.3
##  M31Fcsw M3, Day 1, fecal swab, whole body study   
##  M11Fcsw M1, Day 1, fecal swab, whole body study   
##  ...                                            ...
##  TS28                                       Twin #1
##  TS29                                       Twin #2
##  Even1                                      Even1  
##  Even2                                      Even2  
##  Even3                                      Even3
colnames(colData(tse))
##  [1] "X.SampleID"               "Primer"                  
##  [3] "Final_Barcode"            "Barcode_truncated_plus_T"
##  [5] "Barcode_full_length"      "SampleType"              
##  [7] "Description"

# 2. Number of samples of each sample type
table(colData(tse)[["SampleType"]])
##  
##               Feces         Freshwater Freshwater (creek)               Mock 
##                   4                  2                  3                  3 
##               Ocean Sediment (estuary)               Skin               Soil 
##                   3                  3                  3                  3 
##              Tongue 
##                   2

# 3. Feature metadata
rowData(tse)
##  DataFrame with 19216 rows and 7 columns
##             Kingdom        Phylum        Class        Order        Family
##         <character>   <character>  <character>  <character>   <character>
##  549322     Archaea Crenarchaeota Thermoprotei           NA            NA
##  522457     Archaea Crenarchaeota Thermoprotei           NA            NA
##  951        Archaea Crenarchaeota Thermoprotei Sulfolobales Sulfolobaceae
##  244423     Archaea Crenarchaeota        Sd-NA           NA            NA
##  586076     Archaea Crenarchaeota        Sd-NA           NA            NA
##  ...            ...           ...          ...          ...           ...
##  278222    Bacteria           SR1           NA           NA            NA
##  463590    Bacteria           SR1           NA           NA            NA
##  535321    Bacteria           SR1           NA           NA            NA
##  200359    Bacteria           SR1           NA           NA            NA
##  271582    Bacteria           SR1           NA           NA            NA
##               Genus                Species
##         <character>            <character>
##  549322          NA                     NA
##  522457          NA                     NA
##  951     Sulfolobus Sulfolobusacidocalda..
##  244423          NA                     NA
##  586076          NA                     NA
##  ...            ...                    ...
##  278222          NA                     NA
##  463590          NA                     NA
##  535321          NA                     NA
##  200359          NA                     NA
##  271582          NA                     NA
colnames(rowData(tse))
##  [1] "Kingdom" "Phylum"  "Class"   "Order"   "Family"  "Genus"   "Species"

# 4. Compare the names
all(rownames(colData(tse)) == colnames(tse))
##  [1] TRUE
all(rownames(rowData(tse)) == rownames(tse))
##  [1] TRUE
  1. The columns of the feature metadata are taxonomic ranks, from kingdom to species. Together they give the taxonomic classification of each feature.

  2. The row names of colData are the sample names, and the row names of rowData are the feature names. Both comparisons return TRUE: each row of colData describes one column of the assays, and each row of rowData describes one row of the assays.

Exercise 4: Phylogenetic tree and other slots

Goal: Access the phylogenetic tree and the other slots of a TreeSE object.

  1. Access the phylogenetic tree of tse. How many tips and internal nodes does it have? Compare the number of tips with the number of features in tse.

  2. Show the first rows of the links between the features and the nodes of the tree. Which column tells whether a feature is linked to a tip (leaf) of the tree?

  3. Check whether tse contains a sample tree, reference sequences and metadata about the experiment.

  4. Which of the slots that you accessed in Exercises 2-4 are shared with the SummarizedExperiment class, and which are unique to TreeSE?

Useful functions: TreeSummarizedExperiment::rowTree(), TreeSummarizedExperiment::rowLinks(), TreeSummarizedExperiment::colTree(), TreeSummarizedExperiment::referenceSeq(), S4Vectors::metadata()

# 1. Phylogenetic tree
rowTree(tse)
##  
##  Phylogenetic tree with 19216 tips and 19215 internal nodes.
##  
##  Tip labels:
##    549322, 522457, 951, 244423, 586076, 246140, ...
##  Node labels:
##    , 0.858.4, 1.000.154, 0.764.3, 0.995.2, 1.000.2, ...
##  
##  Rooted; includes branch length(s).

# 2. Links between the features and the tree
rowLinks(tse) |> head()
##  LinkDataFrame with 6 rows and 5 columns
##        nodeLab   nodeNum nodeLab_alias    isLeaf   whichTree
##    <character> <integer>   <character> <logical> <character>
##  1      549322         1       alias_1      TRUE       phylo
##  2      522457         2       alias_2      TRUE       phylo
##  3         951         3       alias_3      TRUE       phylo
##  4      244423         4       alias_4      TRUE       phylo
##  5      586076         5       alias_5      TRUE       phylo
##  6      246140         6       alias_6      TRUE       phylo

# 3. Sample tree, reference sequences and metadata
colTree(tse)
##  NULL
referenceSeq(tse)
##  NULL
metadata(tse)
##  list()
  1. The number of tips and internal nodes is printed with the tree. Each feature is linked to a node of the tree, so here the number of tips equals the number of features. This is not required, as features can also be linked to internal nodes or to no node at all.

  2. The isLeaf column tells whether the node is a tip (TRUE) or an internal node (FALSE).

  3. NULL or an empty list means that the slot is empty. Not all datasets contain data in all slots.

  4. assays, rowData, colData and metadata are shared with SummarizedExperiment. rowTree, rowLinks, colTree and referenceSeq are unique to TreeSE.

Exercise 5: Alternative experiments

Goal: Store data with a different set of features as an alternative experiment.

  1. Subset tse to its first 10 features and store the result in a variable called tse_first10. Check that tse and tse_first10 have the same number of samples.

  2. Add tse_first10 to tse as an alternative experiment called "first10". List the names of the alternative experiments in tse.

  3. Subset tse to its first 3 samples and store the result in a variable called tse_3. What are the dimensions of the alternative experiment in tse_3?

  4. Name the main experiment of tse "original". Then promote the alternative experiment "first10" to the main experiment and print the object. Finally, restore the original main experiment.

  5. Why is tse_first10 stored as an alternative experiment and not as an assay?

Useful functions: dim(), SingleCellExperiment::altExp(), SingleCellExperiment::altExpNames(), SingleCellExperiment::mainExpName(), SingleCellExperiment::swapAltExp()

# 1. Subset the features
tse_first10 <- tse[1:10, ]
dim(tse)
##  [1] 19216    26
dim(tse_first10)
##  [1] 10 26

# 2. Add the alternative experiment
altExp(tse, "first10") <- tse_first10
altExpNames(tse)
##  [1] "first10"

# 3. Subset the samples
tse_3 <- tse[, 1:3]
dim(altExp(tse_3, "first10"))
##  [1] 10  3

# 4. Promote the alternative experiment and restore the original
mainExpName(tse) <- "original"
tse <- swapAltExp(tse, "first10", withColData = FALSE)
tse
##  class: TreeSummarizedExperiment 
##  dim: 10 26 
##  metadata(0):
##  assays(1): counts
##  rownames(10): 549322 522457 ... 255340 144887
##  rowData names(7): Kingdom Phylum ... Genus Species
##  colnames(26): CL3 CC1 ... Even2 Even3
##  colData names(7): X.SampleID Primer ... SampleType Description
##  reducedDimNames(0):
##  mainExpName: first10
##  altExpNames(1): original
##  rowLinks: a LinkDataFrame (10 rows)
##  rowTree: 1 phylo tree(s) (19216 leaves)
##  colLinks: NULL
##  colTree: NULL
tse <- swapAltExp(tse, "original", withColData = FALSE)
  1. The alternative experiment has 10 features and 3 samples. Subsetting the samples of the main experiment subsets the alternative experiments as well, so they stay matched.

  2. The printed object has the same colData columns as tse, because withColData = FALSE is used. By default, swapAltExp() combines the colData of the main experiment with the colData of the alternative experiment, and here both contain the same columns, so they would be duplicated.

  3. An assay must have the same features as the main experiment, but tse_first10 has fewer features. An alternative experiment must have only the same samples. This is the case, for example, with abundance tables that are agglomerated to different taxonomic ranks.

Exercise 6: MultiAssayExperiment

Goal: Explore an MAE object and how it links samples to subjects.

  1. Load the HintikkaXOData dataset from the mia package and store it in a variable called mae. Print mae. How many experiments does it contain, and what are their names?

  2. Show the colData of mae. What does each row describe?

  3. Show the first rows of the sampleMap of mae. What do the columns assay, primary and colname contain?

  4. Subset mae to its first 5 columns, store the result in a variable called mae_sub, and print it. How many samples are left in each experiment?

  5. When would you store experiments in an MAE object instead of as alternative experiments in a TreeSE object?

Useful functions: data(), MultiAssayExperiment::colData(), MultiAssayExperiment::sampleMap(), head()

# 1. Load the data
data("HintikkaXOData", package = "mia")
mae <- HintikkaXOData
mae
##  A MultiAssayExperiment object of 3 listed
##   experiments with user-defined names and respective classes.
##   Containing an ExperimentList class object of length 3:
##   [1] microbiota: TreeSummarizedExperiment with 12706 rows and 40 columns
##   [2] metabolites: TreeSummarizedExperiment with 38 rows and 40 columns
##   [3] biomarkers: TreeSummarizedExperiment with 39 rows and 40 columns
##  Functionality:
##   experiments() - obtain the ExperimentList instance
##   colData() - the primary/phenotype DataFrame
##   sampleMap() - the sample coordination DataFrame
##   `$`, `[`, `[[` - extract colData columns, subset, or experiment
##   *Format() - convert into a long or wide DataFrame
##   assays() - convert ExperimentList to a SimpleList of matrices
##   exportClass() - save data to flat files

# 2. colData of the MAE
colData(mae)
##  DataFrame with 40 rows and 6 columns
##           Sample      Rat        Site          Diet      Fat       XOS
##      <character> <factor> <character>      <factor> <factor> <numeric>
##  C1           C1        1       Cecum      High-fat     High         0
##  C2           C2        2       Cecum      High-fat     High         0
##  C3           C3        3       Cecum      High-fat     High         0
##  C4           C4        4       Cecum      High-fat     High         0
##  C5           C5        5       Cecum      High-fat     High         0
##  ...         ...      ...         ...           ...      ...       ...
##  C36         C36       36       Cecum Low-fat + XOS      Low         1
##  C37         C37       37       Cecum Low-fat + XOS      Low         1
##  C38         C38       38       Cecum Low-fat + XOS      Low         1
##  C39         C39       39       Cecum Low-fat + XOS      Low         1
##  C40         C40       40       Cecum Low-fat + XOS      Low         1

# 3. sampleMap
sampleMap(mae) |> head()
##  DataFrame with 6 rows and 3 columns
##         assay     primary     colname
##      <factor> <character> <character>
##  1 microbiota          C1          C1
##  2 microbiota          C2          C2
##  3 microbiota          C3          C3
##  4 microbiota          C4          C4
##  5 microbiota          C5          C5
##  6 microbiota          C6          C6

# 4. Subset the MAE
mae_sub <- mae[, 1:5, ]
mae_sub
##  A MultiAssayExperiment object of 3 listed
##   experiments with user-defined names and respective classes.
##   Containing an ExperimentList class object of length 3:
##   [1] microbiota: TreeSummarizedExperiment with 12706 rows and 5 columns
##   [2] metabolites: TreeSummarizedExperiment with 38 rows and 5 columns
##   [3] biomarkers: TreeSummarizedExperiment with 39 rows and 5 columns
##  Functionality:
##   experiments() - obtain the ExperimentList instance
##   colData() - the primary/phenotype DataFrame
##   sampleMap() - the sample coordination DataFrame
##   `$`, `[`, `[[` - extract colData columns, subset, or experiment
##   *Format() - convert into a long or wide DataFrame
##   assays() - convert ExperimentList to a SimpleList of matrices
##   exportClass() - save data to flat files
  1. The number and names of the experiments are listed when the object is printed. Here, there are three experiments: microbiota, metabolites and biomarkers.

  2. Each row describes one subject, here one rat. The colData of an MAE stores information that stays constant during the study.

  3. assay is the name of the experiment, colname is the name of the sample in that experiment, and primary is the subject from whom the sample was collected. In this dataset, each rat has one sample in each experiment. In the HoloFood example of this chapter, some animals have several samples, and the sampleMap links all of them to the same animal.

  4. The printed object shows the number of rows and columns of each experiment. Subsetting the columns of an MAE subsets the samples in all experiments at the same time, based on the sampleMap.

  5. Use an MAE object when the samples do not match one-to-one between the experiments, for example when some subjects are missing from one experiment or a subject has several samples. Alternative experiments require exactly the same samples as the main experiment.

Back to top