4  Importing and exporting data

This chapter demonstrates how data can be imported into data containers from files (Section 4.1) and converted from other R objects, such as phyloseq (McMurdie and Holmes 2013) (Section 4.2). Additionally, multiple databases offer curated microbiome data, which are introduced in Section 4.3. Finally, Section 4.4 shows how to save the data containers and export them as tables.

phyloseq: An R package for reproducible interactive analysis and graphics of microbiome census data. McMurdie et al. (2013). PLoS One 8:e61217. doi:10.1371/journal.pone.0061217.
DADA2: High-resolution sample inference from Illumina amplicon data. Callahan et al. (2016). Nat Methods 13:581–583. doi:10.1038/nmeth.3869.

Before importing the data into a container, the raw sequences must be mapped to abundances. The specific method depends on the sequencing type and other data-specific factors. There are several resources available to guide this process, Metagenomics wiki being one of them. Here you can find an example workflow for processing 16S rRNA sequences into a data container using dada2 (Callahan et al. 2016).

4.1 Import from files

The data containers can be constructed from scratch. For most common microbiome data formats, there are dedicated importers available that streamline the importing.

4.1.1 Standard data formats

Specific import functions are provided for:

The biological observation matrix (BIOM) format or: How i learned to stop worrying and love the ome-ome. McDonald et al. (2012). GigaScience 1. doi:10.1186/2047-217x-1-7.
Reproducible, interactive, scalable and extensible microbiome data science using QIIME 2. Bolyen et al. (2019). Nat Biotechnol 37:852–857. doi:10.1038/s41587-019-0209-9.
Introducing mothur: Open-source, platform-independent, community-supported software for describing and comparing microbial communities. Schloss et al. (2009). Appl Environ Microbiol 75:7537–7541. doi:10.1128/aem.01541-09.
Integrating taxonomic, functional, and strain-level profiling of diverse microbial communities with bioBakery 3. Beghini et al. (2021). eLife 10. doi:10.7554/elife.65088.
TAXPASTA: TAXonomic profile aggregation and STAndardisation. Beber et al. (2023). J Open Source Softw 8:5627. doi:10.21105/joss.05627.
Gut microbiota from persons with attention-deficit/hyperactivity disorder affects the brain in mice. C Tengeler et al. (2020). Microbiome 8:1–14. doi:10.1186/s40168-020-00816-x.

Here we show how BIOM files are imported into a TreeSE object (Huang et al. 2021) using Tengeler2020 (C Tengeler et al. 2020) as an example, which is further described here. This dataset consists of 3 files, which can be fetched or downloaded from this repository:

  • biom file: abundance table and taxonomy information
  • csv file: sample metadata
  • tree file: phylogenetic tree

In your own analysis, you would store the data in a local directory, such as data/, and define the source file paths. To follow the examples in this chapter, download the example files from the OMA repository to a data/ directory:

# Example files in the OMA GitHub repository
url <- "https://raw.githubusercontent.com/microbiome/OMA/devel/inst/extdata"
files <- c(
    "Aggregated_humanization2.biom",
    "Mapping_file_ADHD_aggregated.csv",
    "Data_humanization_phylo_aggregation.tre",
    "assay_taxa.csv",
    "rowdata_taxa.csv",
    "assay_metabolites.csv",
    "coldata.csv"
)

# Download the files into the folder "data"
dir.create("data", showWarnings = FALSE)
download.file(
    file.path(url, files), file.path("data", files),
    method = "libcurl", mode = "wb"
)

Then we define the paths to the files.

biom_file_path <- "data/Aggregated_humanization2.biom"
sample_meta_file_path <- "data/Mapping_file_ADHD_aggregated.csv"
tree_file_path <- "data/Data_humanization_phylo_aggregation.tre"

Now we can read in the biom file and convert it into a TreeSE object. In addition, we retrieve the rank names from the prefixes of the taxonomic feature names and then remove them with the rank.from.prefix and prefix.rm optional arguments.

library(mia)

# Read biom and convert it to TreeSE
tse <- importBIOM(
    biom_file_path,
    rank.from.prefix = TRUE,
    prefix.rm = TRUE,
    artifact.rm = TRUE
)

# Check
tse
##  class: TreeSummarizedExperiment 
##  dim: 151 27 
##  metadata(0):
##  assays(1): counts
##  rownames(151): 1726470 1726471 ... 17264756 17264757
##  rowData names(6): kingdom phylum ... family genus
##  colnames(27): A110 A111 ... A38 A39
##  colData names(0):
##  reducedDimNames(0):
##  mainExpName: NULL
##  altExpNames(0):
##  rowLinks: NULL
##  rowTree: NULL
##  colLinks: NULL
##  colTree: NULL

The assays slot includes a list of abundance tables. The imported abundance table is named “counts”. Let us inspect only the first columns and rows.

assay(tse, "counts")[1:3, 1:3]
##            A110  A111  A12
##  1726470  17722 11630    0
##  1726471  12052     0 2679
##  17264731     0   970    0

The rowData includes taxonomic information from the biom file. The head() command shows just the beginning of the data table for an overview.

rowData(tse) |> head()
##  DataFrame with 6 rows and 6 columns
##               kingdom          phylum            class              order
##           <character>     <character>      <character>        <character>
##  1726470     Bacteria   Bacteroidetes      Bacteroidia      Bacteroidales
##  1726471     Bacteria   Bacteroidetes      Bacteroidia      Bacteroidales
##  17264731    Bacteria   Bacteroidetes      Bacteroidia      Bacteroidales
##  17264726    Bacteria   Bacteroidetes      Bacteroidia      Bacteroidales
##  1726472     Bacteria Verrucomicrobia Verrucomicrobiae Verrucomicrobiales
##  17264724    Bacteria   Bacteroidetes      Bacteroidia      Bacteroidales
##                        family           genus
##                   <character>     <character>
##  1726470       Bacteroidaceae     Bacteroides
##  1726471       Bacteroidaceae     Bacteroides
##  17264731  Porphyromonadaceae Parabacteroides
##  17264726      Bacteroidaceae     Bacteroides
##  1726472  Verrucomicrobiaceae     Akkermansia
##  17264724      Bacteroidaceae     Bacteroides

We notice that the imported biom file did not contain any colData yet, so only an empty table appears in this slot.

colData(tse) |> head()
##  DataFrame with 6 rows and 0 columns

Let us add colData from the sample metadata, which is stored in a CSV file.

# CSV file with colnames in the first row and rownames in the first column
sample_meta <- read.csv(
    sample_meta_file_path,
    sep = ",", row.names = 1
)

sample_meta |> head()
##       Treatment   Cohort TreatmentxCohort Description
##  A110      ADHD Cohort_1    ADHD_Cohort_1        A110
##  A12       ADHD Cohort_1    ADHD_Cohort_1         A12
##  A15       ADHD Cohort_1    ADHD_Cohort_1         A15
##  A19       ADHD Cohort_1    ADHD_Cohort_1         A19
##  A21       ADHD Cohort_2    ADHD_Cohort_2         A21
##  A23       ADHD Cohort_2    ADHD_Cohort_2         A23

You have to be especially careful when you add sample metadata, effectively replacing the existing, empty colData. The method does not check sample names, which can lead to mistakes. Therefore, you must manually ensure that the sample names in the metadata not only exist but also match those in TreeSE.

# Check that sample names exist
if (is.null(rownames(sample_meta)) || is.null(colnames(tse))) {
    stop("Sample names missing!", call. = FALSE)
}

# Sort rows in sample metadata to match with TreeSE
sample_order <- match(colnames(tse), rownames(sample_meta))
sample_meta <- sample_meta[sample_order, , drop = FALSE]

# If sample metadata did not include all samples, missing ones are now named NA.
# That is why we replace sample metadata names with ones in TreeSE.
rownames(sample_meta) <- colnames(tse)

Now, we can add sample metadata to the colData as DataFrame class. (DataFrame is just like base R data.frame but with some additional functionality.)

colData(tse) <- DataFrame(sample_meta)
colData(tse) |> head()
##  DataFrame with 6 rows and 4 columns
##         Treatment      Cohort TreatmentxCohort Description
##       <character> <character>      <character> <character>
##  A110        ADHD    Cohort_1    ADHD_Cohort_1        A110
##  A111     Control    Cohort_1 Control_Cohort_1        A111
##  A12         ADHD    Cohort_1    ADHD_Cohort_1         A12
##  A13      Control    Cohort_1 Control_Cohort_1         A13
##  A14      Control    Cohort_1 Control_Cohort_1         A14
##  A15         ADHD    Cohort_1    ADHD_Cohort_1         A15

Finally, we add a phylogenetic tree to the rowTree slot. Such a feature is available only in TreeSE objects. Similarly, trees specifying the sample hierarchy can be stored in the colTree slot.

Here, we read in the file containing the phylogenetic tree and insert it into the corresponding slot of the TreeSE object.

# Reads the tree file
tree <- ape::read.tree(tree_file_path)

# Add tree to rowTree
rowTree(tse) <- tree

# Check
tse
##  class: TreeSummarizedExperiment 
##  dim: 151 27 
##  metadata(0):
##  assays(1): counts
##  rownames(151): 1726470 1726471 ... 17264756 17264757
##  rowData names(6): kingdom phylum ... family genus
##  colnames(27): A110 A111 ... A38 A39
##  colData names(4): Treatment Cohort TreatmentxCohort Description
##  reducedDimNames(0):
##  mainExpName: NULL
##  altExpNames(0):
##  rowLinks: a LinkDataFrame (151 rows)
##  rowTree: 1 phylo tree(s) (151 leaves)
##  colLinks: NULL
##  colTree: NULL

Now the rowTree slot contains the phylogenetic tree:

rowTree(tse)
##  
##  Phylogenetic tree with 151 tips and 149 internal nodes.
##  
##  Tip labels:
##    172647198, 1726478, 1726479, 172647201, 172647222, 17264798, ...
##  Node labels:
##    , 0.789, 0.810, 0.844, 0.973, 0.685, ...
##  
##  Unrooted; includes branch length(s).

4.1.2 Non-standard formats

Microbiome (taxonomic) profiling data is commonly distributed in various file formats. You can import such external data files as a TreeSE object, but the details depend on the file format. Here, we provide examples for common formats. Some datasets and raw files to learn how to import raw data and construct TreeSummarizedExperiment / MultiAssayExperiment (Ramos et al. 2017) containers are available in the microbiome data repository.

4.1.2.1 CSV import

CSV data tables can be imported with the standard R functions, then converted to the desired format. For detailed examples, you can check the Bioconductor course material by Martin Morgan. You can also check the example files and construct your own CSV files accordingly.

Recommendations for the CSV files are the following. File names are arbitrary; we refer here to the same names as in the examples:

  • Abundance table (assay_taxa.csv): data matrix (features x samples); first column provides feature IDs, the first row provides sample IDs; other values should be numeric (abundances).

  • Row data (rowdata_taxa.csv): data table (features x info); first column provides feature IDs, the first row provides column headers; this file usually contains the taxonomic mapping between different taxonomic levels. Ideally, the feature IDs (row names) match one-to-one with the abundance table row names. Some pipelines store the taxonomy as a single string per feature, such as "k__Bacteria; p__Firmicutes; c__Bacilli". Such strings can be split into one column per rank with parseTaxonomy() from mia.

  • Column data (coldata.csv): data table (samples x info); first column provides sample IDs, the first row provides column headers; this file usually contains the sample metadata/phenodata (such as subject age, health, etc.). Ideally, the sample IDs match one-to-one with the abundance table column names.

After you have set up the CSV files, you can read them in R:

count_file <- "data/assay_taxa.csv"
tax_file <- "data/rowdata_taxa.csv"
sample_file <- "data/coldata.csv"

# Load files
counts <- read.csv(count_file, row.names = 1) # Abundance table (e.g. ASV data; to assay data)
tax <- read.csv(tax_file, row.names = 1) # Taxonomy table (to rowData)
samples <- read.csv(sample_file, row.names = 1) # Sample data (to colData)

After reading the data in R, ensure the following:

  • abundance table (counts): numeric matrix, with feature IDs as rownames and sample IDs as column names.

  • rowData (tax): DataFrame or data.frame, with feature IDs as rownames. If this is a data.frame, the TreeSummarizedExperiment() constructor converts the table automatically into DataFrame format (you can also do that manually with a DataFrame() function). Column names are free but in microbiome analysis they usually refer to taxonomic ranks. The rownames in rowData should match the rownames in the abundance table.

  • colData (samples): DataFrame or data.frame, with sample IDs as rownames. If this is a data.frame, the TreeSummarizedExperiment() constructor converts the table automatically into DataFrame format (you can also do that manually with a DataFrame() function). Column names are free. The rownames in colData should match the colnames in the abundance table.

Always ensure that the tables have rownames! The TreeSummarizedExperiment (TreeSE) constructor compares rownames and ensures that, for example, the right samples are linked to the right patient.

Also, ensure that the row and column names match one-to-one between abundance table, rowData, and colData:

# Match rows and columns
counts <- counts[rownames(tax), rownames(samples)]

# Let's ensure that the data is in correct (numeric matrix) format:
counts <- as.matrix(counts)

If you are unsure about the format of the data, you can compare to one of the available demonstration datasets, and make sure that your data components have the same format.

There are many different source files and many different ways to read data in R. One can do data manipulation in R as well. Investigate the entries as follows.

# coldata rownames match assay colnames
all(rownames(samples) == colnames(counts)) # our dataset
##  [1] TRUE
class(samples) # should be data.frame or DataFrame
##  [1] "data.frame"

# rowdata rownames match assay rownames
all(rownames(tax) == rownames(counts)) # our dataset
##  [1] TRUE
class(tax) # should be data.frame or DataFrame
##  [1] "data.frame"

# Counts
class(counts) # should be a matrix
##  [1] "matrix" "array"
is.numeric(counts) # should be TRUE
##  [1] TRUE
Important!

Ensure that colnames of assay match with rownames of colData, and rownames of assay match with rownames of rowData.

If your data do not have names, you have to be especially careful, since this can lead to errors!

4.1.2.2 Constructing TreeSE

Now, let’s create the TreeSE object from the input data tables. The input tables should be in these formats:

  • counts → numeric matrix
  • rowData → DataFrame or data.frame
  • colData → DataFrame or data.frame

The SimpleList could be used to include multiple alternative assays, if necessary.

# Create a TreeSE
tse_taxa <- TreeSummarizedExperiment(
    assays = SimpleList(counts = counts),
    colData = samples,
    rowData = tax
)

tse_taxa
##  class: TreeSummarizedExperiment 
##  dim: 12706 40 
##  metadata(0):
##  assays(1): counts
##  rownames(12706): GAYR01026362.62.2014 CVJT01000011.50.2173 ...
##    JRJTB:03787:02429 JRJTB:03787:02478
##  rowData names(7): Phylum Class ... Species OTU
##  colnames(40): C1 C2 ... C39 C40
##  colData names(6): Sample Rat ... Fat XOS
##  reducedDimNames(0):
##  mainExpName: NULL
##  altExpNames(0):
##  rowLinks: NULL
##  rowTree: NULL
##  colLinks: NULL
##  colTree: NULL

Now you should have a ready-made TreeSE data object that can be used in downstream analyses.

4.1.2.3 Constructing an MAE

To construct a MultiAssayExperiment (MAE) object, just combine multiple TreeSE data containers.

Here we import metabolite data from the same study.

conc_file <- "data/assay_metabolites.csv"
sample_file <- "data/coldata.csv"

# Load files
concs <- read.csv(conc_file, row.names = 1)
samples <- read.csv(sample_file, row.names = 1)

# Create a TreeSE for the metabolite data
tse_metabolite <- TreeSummarizedExperiment(
    assays = SimpleList(concs = as.matrix(concs)),
    colData = samples
)

tse_metabolite
##  class: TreeSummarizedExperiment 
##  dim: 38 40 
##  metadata(0):
##  assays(1): concs
##  rownames(38): Butyrate Acetate ... Malonate 1,3-dihydroxyacetone
##  rowData names(0):
##  colnames(40): C1 C2 ... C39 C40
##  colData names(6): Sample Rat ... Fat XOS
##  reducedDimNames(0):
##  mainExpName: NULL
##  altExpNames(0):
##  rowLinks: NULL
##  rowTree: NULL
##  colLinks: NULL
##  colTree: NULL
Important!

When creating TreeSE, assay must be a matrix, and both colData and rowData must be DataFrame or data.frame objects.

Now we can combine these two experiments into MAE.

# Create an ExperimentList that includes experiments
experiments <- ExperimentList(
    microbiome = tse_taxa, metabolite = tse_metabolite
)

# Create a MAE
mae <- MultiAssayExperiment(experiments = experiments)

mae
##  A MultiAssayExperiment object of 2 listed
##   experiments with user-defined names and respective classes.
##   Containing an ExperimentList class object of length 2:
##   [1] microbiome: TreeSummarizedExperiment with 12706 rows and 40 columns
##   [2] metabolite: TreeSummarizedExperiment with 38 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

When the experiments share the same samples, they can also be stored in a single TreeSE, with the other experiments as alternative experiments (altExp()) (Amezquita et al. 2020). convertToTreeSE() and convertToMAE() convert between the two containers.

Orchestrating single-cell analysis with Bioconductor. Amezquita et al. (2020). Nat Methods 17:137–145. doi:10.1038/s41592-019-0654-x.
# MAE to TreeSE: the other experiments become altExps of the first one
tse_all <- convertToTreeSE(mae)
altExpNames(tse_all)
##  [1] "metabolite"

# And back to MAE
convertToMAE(tse_all)
##  A MultiAssayExperiment object of 2 listed
##   experiments with user-defined names and respective classes.
##   Containing an ExperimentList class object of length 2:
##   [1] microbiome: TreeSummarizedExperiment with 12706 rows and 40 columns
##   [2] metabolite: TreeSummarizedExperiment with 38 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

4.2 Import from other R objects

If the data has already been imported in R in another format, it can be readily converted into TreeSE, as shown in our next example. Note that similar conversion functions to TreeSE are available for multiple data formats via the mia package (see convertFrom* for phyloseq, biomformat, and dada2).

library(mia)

# Phyloseq example data
data(GlobalPatterns, package = "phyloseq")
GlobalPatterns_phyloseq <- GlobalPatterns
GlobalPatterns_phyloseq
##  phyloseq-class experiment-level object
##  otu_table()   OTU Table:         [ 19216 taxa and 26 samples ]
##  sample_data() Sample Data:       [ 26 samples by 7 sample variables ]
##  tax_table()   Taxonomy Table:    [ 19216 taxa by 7 taxonomic ranks ]
##  phy_tree()    Phylogenetic Tree: [ 19216 tips and 19215 internal nodes ]
# convert phyloseq to TSE
GlobalPatterns_TSE <- convertFromPhyloseq(GlobalPatterns_phyloseq)
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

We can also convert TreeSE objects into phyloseq with respect to the shared components that are supported by both formats (i.e. taxonomic abundance table, sample metadata, taxonomic table, phylogenetic tree, sequence information). This is useful for instance when additional methods are available for phyloseq.

# convert TSE to phyloseq
GlobalPatterns_phyloseq2 <- convertToPhyloseq(GlobalPatterns_TSE)
GlobalPatterns_phyloseq2
##  phyloseq-class experiment-level object
##  otu_table()   OTU Table:         [ 19216 taxa and 26 samples ]
##  sample_data() Sample Data:       [ 26 samples by 7 sample variables ]
##  tax_table()   Taxonomy Table:    [ 19216 taxa by 7 taxonomic ranks ]
##  phy_tree()    Phylogenetic Tree: [ 19216 tips and 19215 internal nodes ]

Conversion is possible between other data formats. Interested readers can refer to the following functions:

4.3 Open data resources

Open demonstration data for testing and benchmarking purposes is available from multiple locations. This section introduces some options. The datasets used in this book are described in Appendix D.

4.3.1 MGnify

MGnify (Richardson et al. 2022) is EBI’s resource for the analysis of metagenomic, metatranscriptomic and amplicon data. It provides taxonomic and functional profiles for tens of thousands of public studies, all processed with the same pipelines. The MGnifyR package fetches these profiles directly as TreeSE objects, or as an MAE when several types of profiles are fetched.

MGnify: The microbiome sequence data analysis resource in 2023. Richardson et al. (2022). Nucleic Acids Res 51:D753–D759. doi:10.1093/nar/gkac1080.
library(MGnifyR)

# Search studies from a biome
studies <- searchStudies(
    biome = "root:Engineered:Built environment"
)

# Fetch the data of a study as a TreeSE
tse <- fetchStudies("MGYS00005116")

See the MGnifyR vignette for more examples of how to search and fetch the data.

4.3.2 Package data

The mia R package contains example datasets that are direct conversions from the alternative phyloseq container to the TreeSummarizedExperiment (TreeSE) container.

List the available datasets in the mia package:

data(package = "mia")$results[, "Item"]
##  [1] "GlobalPatterns" "HintikkaXOData" "Tengeler2020"   "Tito2024QMP"   
##  [5] "dmn_se"         "enterotype"     "esophagus"      "ibdmdb"        
##  [9] "peerj13075"

Load the GlobalPatterns data from the mia package:

data("GlobalPatterns", package = "mia")
GlobalPatterns
##  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

R packages contain additional demonstration datasets (see the Datasets section of the reference page):

4.3.3 ExperimentHub data

ExperimentHub provides a variety of data resources, including the microbiomeDataSets package (Lahti et al. 2021; Morgan and Shepherd 2021).

microbiomeDataSets: Experiment Hub based microbiome datasets. Lahti et al. (2021). R package version 1.2.0.
ExperimentHub: Client to access ExperimentHub resources. Morgan et al. (2021). R package version 2.2.0.

A table of the available datasets is available through the availableDataSets() function.

library(microbiomeDataSets)
availableDataSets()
##              Dataset
##  1  GrieneisenTSData
##  2       LahtiMLData
##  3        LahtiMData
##  4      OKeefeDSData
##  5 SilvermanAGutData
##  6        SongQAData
##  7   SprockettTHData

All data are downloaded from ExperimentHub and cached for local re-use. Check the manual pages of each function for detailed documentation of the data contents and references. Let us retrieve a MultiAssayExperiment dataset. The HintikkaXOData dataset was originally distributed through microbiomeDataSets and is now also included in mia, so here we load it from there:

# mae <- HintikkaXOData()
# Since HintikkaXOData is now added to mia, we can load it directly from there
# We suggest to check other datasets from microbiomeDataSets
data(HintikkaXOData, package = "mia")
mae <- HintikkaXOData

Data is available in SummarizedExperiment (SE) (Morgan et al. 2020), TreeSummarizedExperiment (TreeSE), and MultiAssayExperiment (MAE) data containers; see Chapter 3 and Section 3.8 for more details.

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

4.3.4 Curated metagenomic data

curatedMetagenomicData is a large collection of curated human microbiome datasets, provided as TreeSE objects (Pasolli et al. 2017; Manghi et al. 2026). The resource provides curated human microbiome data including gene families, marker abundance, marker presence, pathway abundance, pathway coverage, and relative abundance for samples from different body sites. See the package homepage for more details on data availability and access.

Accessible, curated metagenomic data through ExperimentHub. Pasolli et al. (2017). Nat Methods 14:1023–1024. doi:10.1038/nmeth.4468.
Meta-analysis of 22,710 human microbiome metagenomes defines an oral-to-gut microbial enrichment score and associations with host health and disease. Manghi et al. (2026). Nat Commun 17:196. doi:10.1038/s41467-025-66888-1.
Variation in microbiome LPS immunogenicity contributes to autoimmunity in humans. Vatanen et al. (2016). Cell 165:842–853. doi:10.1016/j.cell.2016.04.007.

As one example, let us retrieve the Vatanen et al. (2016) dataset. This is a larger collection with a bit longer download time. The function returns a list with one object for each data type.

library(curatedMetagenomicData)
tse_list <- curatedMetagenomicData("Vatanen*", dryrun = FALSE, counts = TRUE)

4.3.5 Microbiome compendium

The MicroBioMap dataset includes almost 170k samples of publicly available 16S rRNA amplicon sequencing data, all processed using the same pipeline and reference database (Davis et al. 2024; Abdill et al. 2025). After installing the MicroBioMap package (see their GitHub page for instructions), you can load the compendium as below.

MicroBioMap: Access the microbiome compendium from R. Davis et al. (2024). R package version 0.99.13, commit bbb29aa746a3023ac331f62b8a47fbfc30441f8e. https://github.com/seandavi/MicroBioMap.
Integration of 168,000 samples reveals global patterns of the human gut microbiome. Abdill et al. (2025). Cell 188:1100–1118.e17. doi:10.1016/j.cell.2024.12.017.
library(MicroBioMap)
cpd <- getCompendium()

This returns a TreeSE object. Currently, the rowTree slot of the TreeSE is not populated.

After loading the compendium, you will have immediate access to nearly 170,000 microbiome samples of publicly available 16S rRNA amplicon sequencing data, all processed using the same pipeline and reference database. For more use examples in R/Bioconductor, see the MicroBioMap vignette.

4.3.6 iHMP data

HMP2Data provides 16S rRNA sequencing data from the second phase of the Human Microbiome Project, also known as the Integrative Human Microbiome Project (iHMP) (Integrative HMP (iHMP) Research Network Consortium et al. 2019; Stansfield et al. 2025). Additional data, e.g. cytokines, are included when available. The data are offered as SummarizedExperiment and MultiAssayExperiment objects.

The integrative human microbiome project. Integrative HMP (iHMP) Research Network Consortium et al. (2019). Nature 569:641–648. doi:10.1038/s41586-019-1238-8.
HMP2Data: 16s rRNA sequencing data from the Human Microbiome Project 2. Stansfield et al. (2025). R package version 1.22.0. doi:10.18129/B9.bioc.HMP2Data.

4.3.7 Microbiome benchmark data

MicrobiomeBenchmarkData provides datasets with a known biological ground truth (Gamboa-Tuz et al. 2025). The datasets were compiled for benchmarking differential abundance methods, but the ground truth can be useful for other benchmarking applications as well. The datasets are offered directly as TreeSE objects.

Commonly used compositional data analysis implementations are not advantageous in microbial differential abundance analyses benchmarked against biological ground truth. Gamboa-Tuz et al. (2025). bioRxiv 2025.02.13.638109. doi:10.1101/2025.02.13.638109.

4.3.8 Other data sources

The following packages provide access to further microbiome data resources and return the data as TreeSE or MAE objects.

Package Resource
HoloFoodR (Borman et al. 2025) EBI/HoloFood
qiime2R QIIME2 artifacts with qza_to_tse()
HoloFoodR: A statistical programming framework for holo-omics data integration workflows. Borman et al. (2025). Bioinformatics 41. doi:10.1093/bioinformatics/btaf605.

QIIME2 artifacts can also be imported with importQIIME2() from mia (see Section 4.1).

4.4 Exporting data

There are two main ways to export data. The whole data container can be saved to a file, which preserves all of its components and allows loading it back later as the same object. Alternatively, the data can be exported as tables, which can be opened with other tools, such as spreadsheet programs or other programming languages, but which do not preserve the structure of the object. The data can also be exported in formats that other microbiome analysis tools can read (Section 4.5).

4.4.1 Save the data container

4.4.1.1 RDS files

The simplest way to save any R object, including TreeSE (Huang et al. 2021) and MultiAssayExperiment (Ramos et al. 2017), is to write it to an RDS file with saveRDS(). The file can be loaded back with readRDS().

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.
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.
data(GlobalPatterns, package = "mia")
tse <- GlobalPatterns

# Save TreeSE as an RDS file
saveRDS(tse, "path/to/tse.rds")

# Load the TreeSE back
tse <- readRDS("path/to/tse.rds")

RDS files are convenient for saving and reloading data in R, for example between analysis sessions. However, they can only be read in R, and files saved with old package versions are not always fully compatible with newer versions. For long-term storage or for sharing data across tools, the alabaster format described below is more robust.

4.4.1.2 alabaster

The alabaster framework (Lun 2026) provides an alternative to RDS files. It saves the data container as a directory of files in standard formats, which are not tied to R. This makes the data easier to store long term and to share with other programming languages. The saveObject() function writes the data to a directory, and readObject() loads it back.

Alabaster: Umbrella for the alabaster framework. Lun (2026). R/Bioconductor package. doi:10.18129/B9.bioc.alabaster.
# Requires the alabaster.treese package to be installed
library(alabaster.treese)

# Save TreeSE into a directory
saveObject(tse, "path/to/tse")

# Load the TreeSE back
tse <- readObject("path/to/tse")

The same functions can be used to save and load MultiAssayExperiment objects.

4.4.2 Export as table

4.4.2.1 TreeSummarizedExperiment

Transforming a TreeSE object into a data frame is straightforward with the mia package. The meltSE function is particularly handy for this purpose. It allows you to melt various parts of a TreeSE object into a data frame based on the parameters you specify.

Exporting a TreeSE data container can be done using the feather package, which builds on the arrow implementation of the Feather format; the same files can also be written with arrow::write_feather(). The TreeSE object has to be converted into a data frame (data.frame and not DataFrame). The output file is a .feather file, which can be imported in other languages such as Julia or Python. For more information, have a look at the FeatherFiles Julia package and feather-format Python library.

molten_tse <- meltSE(
    tse,
    add.row = TRUE,
    add.col = TRUE,
    assay.type = "counts"
)

# Export as a feather file
library(feather)
write_feather(molten_tse, "path/to/tse.feather")

Another way could be using a CSV file. This works the same way as for a feather file: make sure you have converted your TreeSE data container into a data frame. Note that you can decide whether you want to write the row names or not.

write.csv(molten_tse, "path/to/tse.csv", row.names = FALSE)

To share the data with collaborators who work with spreadsheets, the se2xls() function from the SEtools package writes a TreeSE to an Excel file without melting it first. The sample data (colData), feature data (rowData) and each assay are saved on separate sheets. Note that the phylogenetic tree is not included.

library(SEtools)
se2xls(tse, filename = "path/to/tse.xlsx")

4.4.2.2 MultiAssayExperiment

Exporting a MultiAssayExperiment data container can also be done using the feather package.

# Convert into a data.frame
molten_mae <- longForm(mae)
molten_mae <- data.frame(molten_mae)
write_feather(molten_mae, "path/to/mae.feather")

And as a CSV file.

write.csv(molten_mae, "path/to/mae.csv", row.names = FALSE)

4.5 Export to standard data formats

Inspired by the rbiom vignettes, exportQIIME2() and exportMothur() allow to save the data in a near-ready format for analysis with QIIME2 and mothur, respectively. The output will need additional processing in the target framework.

exportQIIME2(tse, "qiime2_folder")

Conversion is completed in the terminal using QIIME2. The output files can be converted to the standard QZA format as follows:

# Navigate to output folder
cd qiime2_folder

# Convert classic BIOM table to HDF5
biom convert -i counts.tsv -o counts.hdf5 --to-hdf5

# Convert counts to QZA
qiime tools import \
  --input-path counts.hdf5 \
  --type 'FeatureTable[Frequency]' \
  --input-format BIOMV210Format \
  --output-path counts.qza

# Convert taxonomy to QZA
qiime tools import \
 --input-path taxonomy.tsv \
 --type FeatureData[Taxonomy] \
 --output-path taxonomy.qza

# Convert tree to QZA
qiime tools import \
  --input-path tree.nwk \
  --type 'Phylogeny[Rooted]' \
  --output-path tree.qza

Alternatively, data can be exported to be used with mothur:

exportMothur(tse, "path/to/mothur_folder")

Again, conversion can be completed in the terminal using mothur:

# Navigate to output folder
cd mothur_folder

# Create shared file from counts table
mothur "#make.shared(count=counts.tsv, label=asv);"

The data can also be saved in the BIOM format. convertToBIOM() converts the TreeSE into a biom object, which biomformat writes to a file. The file can be read back with importBIOM().

# Convert TreeSE to BIOM and write it to a file
biom <- convertToBIOM(tse)
biomformat::write_biom(biom, "path/to/tse.biom")

Finally, exportRaw() saves all components of the TreeSE as plain files in a folder: the assays, the sample and feature metadata as TSV files, and the trees.

exportRaw(tse, "path/to/raw_folder")

4.6 Exercises

In Exercises 1 and 2, we use the files of the Tengeler2020 dataset, and in Exercises 3 and 4 CSV files of the HintikkaXOData dataset. Use the files that you downloaded to data/ at the beginning of this chapter (Section 4.1). In Exercises 5-9, we use the Tengeler2020 dataset from the mia package, and in Exercise 10 the HintikkaXOData dataset.

In Exercises 8-11, the files that you create are written to a temporary directory with tempfile(), so that they do not end up in your working directory. In your own work, you would give a path to the location where you want to keep the file.

Solve the exercises in order. Exercise 2 continues from Exercise 1, Exercise 4 from Exercise 3, Exercises 5 and 6 from the previous exercises, and Exercises 9 and 11 from Exercise 8. Try to solve each exercise yourself before opening the solution.

Exercise 1: Import a BIOM file

Goal: Import a BIOM file into a TreeSE object.

  1. Store the path to the BIOM file "Aggregated_humanization2.biom" in the data/ folder in a variable called biom_file_path.

  2. Import the BIOM file with importBIOM() without any optional arguments, and store the result in a variable called tse_raw. Show the first rows of its rowData. What are the column names, and what do the values look like?

  3. Import the BIOM file again, now with the arguments rank.from.prefix = TRUE, prefix.rm = TRUE and artifact.rm = TRUE. Store the result in a variable called tse. Show the first rows of its rowData. What changed?

  4. Check the colData and the rowTree of tse. Do they contain any data yet?

  5. Which function would you use to import data from QIIME2? And from MetaPhlAn?

Useful functions: mia::importBIOM(), SummarizedExperiment::rowData(), SummarizedExperiment::colData(), TreeSummarizedExperiment::rowTree(), head()

library(mia)

# 1. Path to the BIOM file
biom_file_path <- "data/Aggregated_humanization2.biom"

# 2. Import without optional arguments
tse_raw <- importBIOM(biom_file_path)
rowData(tse_raw) |> head()
##  DataFrame with 6 rows and 6 columns
##              taxonomy1          taxonomy2           taxonomy3
##            <character>        <character>         <character>
##  1726470  "k__Bacteria   p__Bacteroidetes      c__Bacteroidia
##  1726471  "k__Bacteria   p__Bacteroidetes      c__Bacteroidia
##  17264731 "k__Bacteria   p__Bacteroidetes      c__Bacteroidia
##  17264726 "k__Bacteria   p__Bacteroidetes      c__Bacteroidia
##  1726472  "k__Bacteria p__Verrucomicrobia c__Verrucomicrobiae
##  17264724 "k__Bacteria   p__Bacteroidetes      c__Bacteroidia
##                       taxonomy4              taxonomy5           taxonomy6
##                     <character>            <character>         <character>
##  1726470       o__Bacteroidales      f__Bacteroidaceae     g__Bacteroides"
##  1726471       o__Bacteroidales      f__Bacteroidaceae     g__Bacteroides"
##  17264731      o__Bacteroidales  f__Porphyromonadaceae g__Parabacteroides"
##  17264726      o__Bacteroidales      f__Bacteroidaceae     g__Bacteroides"
##  1726472  o__Verrucomicrobiales f__Verrucomicrobiaceae     g__Akkermansia"
##  17264724      o__Bacteroidales      f__Bacteroidaceae     g__Bacteroides"

# 3. Import with optional arguments
tse <- importBIOM(
    biom_file_path,
    rank.from.prefix = TRUE,
    prefix.rm = TRUE,
    artifact.rm = TRUE
)
rowData(tse) |> head()
##  DataFrame with 6 rows and 6 columns
##               kingdom          phylum            class              order
##           <character>     <character>      <character>        <character>
##  1726470     Bacteria   Bacteroidetes      Bacteroidia      Bacteroidales
##  1726471     Bacteria   Bacteroidetes      Bacteroidia      Bacteroidales
##  17264731    Bacteria   Bacteroidetes      Bacteroidia      Bacteroidales
##  17264726    Bacteria   Bacteroidetes      Bacteroidia      Bacteroidales
##  1726472     Bacteria Verrucomicrobia Verrucomicrobiae Verrucomicrobiales
##  17264724    Bacteria   Bacteroidetes      Bacteroidia      Bacteroidales
##                        family           genus
##                   <character>     <character>
##  1726470       Bacteroidaceae     Bacteroides
##  1726471       Bacteroidaceae     Bacteroides
##  17264731  Porphyromonadaceae Parabacteroides
##  17264726      Bacteroidaceae     Bacteroides
##  1726472  Verrucomicrobiaceae     Akkermansia
##  17264724      Bacteroidaceae     Bacteroides

# 4. Sample metadata and phylogenetic tree
colData(tse)
##  DataFrame with 27 rows and 0 columns
rowTree(tse)
##  NULL
  1. Without the optional arguments, the columns get generic names, and the values contain prefixes such as k__ and p__ that tell the taxonomic rank. The values can also contain artifacts, such as extra quotation marks.

  2. With rank.from.prefix = TRUE, the column names are taken from the prefixes, so they are taxonomic ranks. prefix.rm = TRUE removes the prefixes from the values, and artifact.rm = TRUE removes artifacts, such as extra quotation marks.

  3. No. colData has no columns, and rowTree is NULL. The BIOM file contains only the abundance table and the taxonomy. The sample metadata and the tree are added in Exercise 2.

  4. importQIIME2() for QIIME2 files and importMetaPhlAn() for MetaPhlAn files.

Exercise 2: Add sample metadata and a phylogenetic tree

Goal: Add sample metadata and a phylogenetic tree to a TreeSE object.

  1. Read the sample metadata from the file "Mapping_file_ADHD_aggregated.csv" in the data/ folder. Use the first column as row names, and store the result in a variable called sample_meta. Show the first rows.

  2. Check that both sample_meta and tse from Exercise 1 have sample names. Then reorder the rows of sample_meta so that they are in the same order as the columns of tse.

  3. Add sample_meta to tse as colData. Show the first rows of the new colData.

  4. Read the phylogenetic tree from the file "Data_humanization_phylo_aggregation.tre" in the same folder, and add it to the rowTree slot of tse. Print tse.

  5. Why must you check the order of the samples yourself before you add the sample metadata?

Useful functions: read.csv(), rownames(), colnames(), match(), S4Vectors::DataFrame(), SummarizedExperiment::colData(), ape::read.tree(), TreeSummarizedExperiment::rowTree()

# 1. Read the sample metadata
sample_meta_file_path <- "data/Mapping_file_ADHD_aggregated.csv"
sample_meta <- read.csv(sample_meta_file_path, row.names = 1)
sample_meta |> head()
##       Treatment   Cohort TreatmentxCohort Description
##  A110      ADHD Cohort_1    ADHD_Cohort_1        A110
##  A12       ADHD Cohort_1    ADHD_Cohort_1         A12
##  A15       ADHD Cohort_1    ADHD_Cohort_1         A15
##  A19       ADHD Cohort_1    ADHD_Cohort_1         A19
##  A21       ADHD Cohort_2    ADHD_Cohort_2         A21
##  A23       ADHD Cohort_2    ADHD_Cohort_2         A23

# 2. Check the sample names and reorder the sample metadata
if (is.null(rownames(sample_meta)) || is.null(colnames(tse))) {
    stop("Sample names missing!", call. = FALSE)
}
sample_order <- match(colnames(tse), rownames(sample_meta))
sample_meta <- sample_meta[sample_order, , drop = FALSE]
rownames(sample_meta) <- colnames(tse)

# 3. Add the sample metadata
colData(tse) <- DataFrame(sample_meta)
colData(tse) |> head()
##  DataFrame with 6 rows and 4 columns
##         Treatment      Cohort TreatmentxCohort Description
##       <character> <character>      <character> <character>
##  A110        ADHD    Cohort_1    ADHD_Cohort_1        A110
##  A111     Control    Cohort_1 Control_Cohort_1        A111
##  A12         ADHD    Cohort_1    ADHD_Cohort_1         A12
##  A13      Control    Cohort_1 Control_Cohort_1         A13
##  A14      Control    Cohort_1 Control_Cohort_1         A14
##  A15         ADHD    Cohort_1    ADHD_Cohort_1         A15

# 4. Read and add the phylogenetic tree
tree_file_path <- "data/Data_humanization_phylo_aggregation.tre"
tree <- ape::read.tree(tree_file_path)
rowTree(tse) <- tree
tse
##  class: TreeSummarizedExperiment 
##  dim: 151 27 
##  metadata(0):
##  assays(1): counts
##  rownames(151): 1726470 1726471 ... 17264756 17264757
##  rowData names(6): kingdom phylum ... family genus
##  colnames(27): A110 A111 ... A38 A39
##  colData names(4): Treatment Cohort TreatmentxCohort Description
##  reducedDimNames(0):
##  mainExpName: NULL
##  altExpNames(0):
##  rowLinks: a LinkDataFrame (151 rows)
##  rowTree: 1 phylo tree(s) (151 leaves)
##  colLinks: NULL
##  colTree: NULL
  1. Replacing colData does not check the sample names. The rows of the sample metadata are matched to the columns of the abundance table by their position. If the order differs, the metadata of one sample is attached to another sample, and all later analyses that use the metadata are wrong.
Exercise 3: Construct a TreeSE from CSV files

Goal: Construct a TreeSE object from an abundance table, a taxonomy table and a sample metadata table.

  1. Read the files "assay_taxa.csv", "rowdata_taxa.csv" and "coldata.csv" from the data/ folder. Use the first column of each file as row names, and store the tables in variables called counts, tax and samples, respectively.

  2. Reorder the rows of counts to match the rows of tax, and its columns to match the rows of samples. Then convert counts into a matrix.

  3. Check that the row names of samples match the column names of counts, and that the row names of tax match the row names of counts. Check also the classes of the three tables.

  4. Create a TreeSE object from the three tables, with the abundance table as an assay called "counts". Store it in a variable called tse_taxa and print it.

  5. Verify the import. Read "assay_taxa.csv" again and compare the value of the feature "CVJT01000011.50.2173" in the sample "C1" with the same value in the counts assay of tse_taxa.

  6. Why should all the tables have row names?

Useful functions: read.csv(), as.matrix(), rownames(), colnames(), all(), class(), TreeSummarizedExperiment::TreeSummarizedExperiment(), S4Vectors::SimpleList(), SummarizedExperiment::assay()

# 1. Read the files
count_file <- "data/assay_taxa.csv"
tax_file <- "data/rowdata_taxa.csv"
sample_file <- "data/coldata.csv"

counts <- read.csv(count_file, row.names = 1)
tax <- read.csv(tax_file, row.names = 1)
samples <- read.csv(sample_file, row.names = 1)

# 2. Match the rows and columns, and convert into a matrix
counts <- counts[rownames(tax), rownames(samples)]
counts <- as.matrix(counts)

# 3. Check the names and the classes
all(rownames(samples) == colnames(counts))
##  [1] TRUE
all(rownames(tax) == rownames(counts))
##  [1] TRUE
class(samples)
##  [1] "data.frame"
class(tax)
##  [1] "data.frame"
class(counts)
##  [1] "matrix" "array"

# 4. Create the TreeSE
tse_taxa <- TreeSummarizedExperiment(
    assays = SimpleList(counts = counts),
    colData = samples,
    rowData = tax
)
tse_taxa
##  class: TreeSummarizedExperiment 
##  dim: 12706 40 
##  metadata(0):
##  assays(1): counts
##  rownames(12706): GAYR01026362.62.2014 CVJT01000011.50.2173 ...
##    JRJTB:03787:02429 JRJTB:03787:02478
##  rowData names(7): Phylum Class ... Species OTU
##  colnames(40): C1 C2 ... C39 C40
##  colData names(6): Sample Rat ... Fat XOS
##  reducedDimNames(0):
##  mainExpName: NULL
##  altExpNames(0):
##  rowLinks: NULL
##  rowTree: NULL
##  colLinks: NULL
##  colTree: NULL

# 5. Compare a value in the file and in the TreeSE
counts_file <- read.csv(count_file, row.names = 1)
counts_file["CVJT01000011.50.2173", "C1"]
##  [1] 1
assay(tse_taxa, "counts")["CVJT01000011.50.2173", "C1"]
##  [1] 1
  1. The two values should be the same. If they differ, the rows or columns of the tables were not matched correctly.

  2. The TreeSummarizedExperiment() constructor uses the row names to make sure that the right features and samples are linked to each other. Without names, the tables can only be matched by their position, and a mistake in the order goes unnoticed.

Exercise 4: Construct an MAE

Goal: Combine several experiments into an MAE object.

  1. Read the file "assay_metabolites.csv" from the data/ folder, using the first column as row names. Create a TreeSE object from it with the metabolite concentrations as an assay called "concs" and the samples table from Exercise 3 as colData. Store it in a variable called tse_metabolite.

  2. Combine tse_taxa from Exercise 3 and tse_metabolite into an ExperimentList, with the names "microbiome" and "metabolite".

  3. Create an MAE object from the ExperimentList, store it in a variable called mae, and print it.

  4. The two experiments have very different numbers of features. Why can they still be stored in the same MAE object?

Useful functions: read.csv(), as.matrix(), TreeSummarizedExperiment::TreeSummarizedExperiment(), S4Vectors::SimpleList(), MultiAssayExperiment::ExperimentList(), MultiAssayExperiment::MultiAssayExperiment()

# 1. Create a TreeSE for the metabolite data
metabolite_file <- "data/assay_metabolites.csv"
concs <- read.csv(metabolite_file, row.names = 1)

tse_metabolite <- TreeSummarizedExperiment(
    assays = SimpleList(concs = as.matrix(concs)),
    colData = samples
)

# 2. Create an ExperimentList
experiments <- ExperimentList(
    microbiome = tse_taxa, metabolite = tse_metabolite
)

# 3. Create the MAE
mae <- MultiAssayExperiment(experiments = experiments)
mae
##  A MultiAssayExperiment object of 2 listed
##   experiments with user-defined names and respective classes.
##   Containing an ExperimentList class object of length 2:
##   [1] microbiome: TreeSummarizedExperiment with 12706 rows and 40 columns
##   [2] metabolite: TreeSummarizedExperiment with 38 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
  1. Each experiment in an MAE object is a separate data container with its own features. Only the samples are linked between the experiments, so the numbers of features can differ.
Exercise 5: Example datasets in packages

Goal: Find and load example datasets from packages.

  1. List the datasets that are available in the mia package.

  2. Load the Tengeler2020 dataset from the mia package and print it.

  3. Compare the Tengeler2020 dataset with the tse object that you imported from files in Exercises 1 and 2. Do they have the same number of features and samples? Do they have a phylogenetic tree?

  4. When are example datasets from packages useful, and when do you need to import data from files?

Useful functions: data(), dim()

# 1. List the datasets in mia
data(package = "mia")$results[, "Item"]
##  [1] "GlobalPatterns" "HintikkaXOData" "Tengeler2020"   "Tito2024QMP"   
##  [5] "dmn_se"         "enterotype"     "esophagus"      "ibdmdb"        
##  [9] "peerj13075"

# 2. Load Tengeler2020
data("Tengeler2020", package = "mia")
Tengeler2020
##  class: TreeSummarizedExperiment 
##  dim: 151 27 
##  metadata(0):
##  assays(1): counts
##  rownames(151): Bacteroides Bacteroides_1 ... Parabacteroides_8
##    Unidentified_Lachnospiraceae_14
##  rowData names(6): Kingdom Phylum ... Family Genus
##  colnames(27): A110 A111 ... A38 A39
##  colData names(4): patient_status cohort patient_status_vs_cohort
##    sample_name
##  reducedDimNames(0):
##  mainExpName: NULL
##  altExpNames(0):
##  rowLinks: a LinkDataFrame (151 rows)
##  rowTree: 1 phylo tree(s) (151 leaves)
##  colLinks: NULL
##  colTree: NULL

# 3. Compare the dimensions
dim(Tengeler2020)
##  [1] 151  27
dim(tse)
##  [1] 151  27
  1. dim() shows the number of features and samples, and the rowTree line of the printed object tells whether a phylogenetic tree is available. The same numbers do not mean that the objects are identical: the feature names and the colData columns can still differ, because the package version of the data was prepared separately from the files.

  2. Example datasets are ready to use, so they are useful for learning, testing methods and benchmarking. Your own data, or other data that is not available in a package or database, must be imported from files.

Exercise 6: Convert between TreeSE and phyloseq

Goal: Convert data from TreeSE to phyloseq and back.

  1. Convert the Tengeler2020 dataset that you loaded in Exercise 5 into a phyloseq object and store it in a variable called ps. Print it.

  2. Look at the printed phyloseq object. Which components of the TreeSE can you find in it?

  3. Convert ps back into a TreeSE and store it in a variable called tse_ps. Print it and compare its dimensions to those of Tengeler2020.

  4. Why can only some components of a TreeSE be converted into phyloseq?

Useful functions: mia::convertToPhyloseq(), mia::convertFromPhyloseq(), dim()

# 1. Convert TreeSE to phyloseq
ps <- convertToPhyloseq(Tengeler2020)
ps
##  phyloseq-class experiment-level object
##  otu_table()   OTU Table:         [ 151 taxa and 27 samples ]
##  sample_data() Sample Data:       [ 27 samples by 4 sample variables ]
##  tax_table()   Taxonomy Table:    [ 151 taxa by 6 taxonomic ranks ]
##  phy_tree()    Phylogenetic Tree: [ 151 tips and 149 internal nodes ]

# 3. Convert phyloseq back to TreeSE
tse_ps <- convertFromPhyloseq(ps)
tse_ps
##  class: TreeSummarizedExperiment 
##  dim: 151 27 
##  metadata(0):
##  assays(1): counts
##  rownames(151): [Eubacterium]_coprostanoligenes_group
##    [Clostridium]_innocuum_group ... Blautia_2 Blautia_3
##  rowData names(6): Kingdom Phylum ... Family Genus
##  colnames(27): A110 A111 ... A38 A39
##  colData names(4): patient_status cohort patient_status_vs_cohort
##    sample_name
##  reducedDimNames(0):
##  mainExpName: NULL
##  altExpNames(0):
##  rowLinks: a LinkDataFrame (151 rows)
##  rowTree: 1 phylo tree(s) (151 leaves)
##  colLinks: NULL
##  colTree: NULL

dim(Tengeler2020)
##  [1] 151  27
dim(tse_ps)
##  [1] 151  27
  1. The phyloseq object contains the abundance table (otu_table()), the sample information (sample_data()), the taxonomy table (tax_table()) and the phylogenetic tree (phy_tree()). They correspond to the counts assay, colData, rowData and rowTree of the TreeSE.
  1. Only the components that are supported by both formats can be converted: the abundance table, sample metadata, taxonomy table, phylogenetic tree and sequence information. A TreeSE can contain components that phyloseq does not support, such as several assays or alternative experiments. These components are not included in the phyloseq object.
Exercise 7: Choose how to save the data

Goal: Explain the difference between saving the data container and exporting the data as a table.

Answer the following questions without writing any code. Section 4.4 will help you.

  1. You want to continue your analysis in R tomorrow. How would you save the data?

  2. You want to archive the data together with a publication, so that it can still be loaded years later, also with other programming languages than R. How would you save the data?

  3. A collaborator wants to open the abundances and sample information in a spreadsheet program. How would you export the data?

  4. Which parts of a TreeSE are lost when the data is exported as a table?

  1. Save the data container as an RDS file with saveRDS(). It is the simplest way to save and load an R object, and the object is loaded back exactly as it was.

  2. Save the data container with the alabaster framework (saveObject()). It stores the data in standard file formats that are not tied to R, which makes it more robust for long-term storage and sharing across tools than an RDS file.

  3. Export the data as a table, for example as a CSV file with meltSE() and write.csv(), or as an Excel file with SEtools::se2xls().

  4. A table does not preserve the structure of the object. For example, the phylogenetic tree is not included, and the links between the assay, rowData and colData are no longer kept automatically. The table cannot be loaded back as the same TreeSE object.

Exercise 8: Save the data container

Goal: Save a TreeSE to a file and load it back.

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

  2. Create a path for an RDS file with tempfile(fileext = ".rds") and store it in a variable called rds_file.

  3. Save tse to rds_file as an RDS file.

  4. Load the file back into a variable called tse_rds. Check that it is identical to tse.

  5. Create a path for a directory with tempfile() and store it in a variable called alabaster_dir. Save tse to this directory with alabaster. Saving a TreeSE requires the alabaster.treese package to be installed.

  6. List the files that were written to alabaster_dir, including the files in its subdirectories.

  7. Load the data back from alabaster_dir into a variable called tse_alabaster and print it.

  8. An RDS file is a single file, while alabaster writes a directory of files. Why might the alabaster format be easier to share with others and to read years later?

Useful functions: data(), tempfile(), saveRDS(), readRDS(), identical(), library(), alabaster.base::saveObject(), alabaster.base::readObject(), list.files()

library(mia)

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

# 2. Path for the RDS file
rds_file <- tempfile(fileext = ".rds")

# 3. Save TreeSE as an RDS file
saveRDS(tse, rds_file)

# 4. Load the RDS file and compare it to the original
tse_rds <- readRDS(rds_file)
identical(tse, tse_rds)
##  [1] TRUE
# 5. Save TreeSE with alabaster (requires the alabaster.treese package)
library(alabaster.treese)

alabaster_dir <- tempfile()
saveObject(tse, alabaster_dir)

# 6. List the files written by alabaster
list.files(alabaster_dir, recursive = TRUE)

# 7. Load the TreeSE back
tse_alabaster <- readObject(alabaster_dir)
tse_alabaster
  1. alabaster saves each component of the object, such as the assay, rowData, colData and the tree, into its own file in a standard format. These files can be read with other programming languages and do not depend on the internal structure of R objects. An RDS file can only be read in R, and files saved with old package versions are not always fully compatible with newer versions.
Exercise 9: Export TreeSE as a table

Goal: Convert a TreeSE into a long table and save it as a CSV file.

  1. Convert tse into a long data.frame with the counts assay. Include both the feature information (rowData) and the sample information (colData). Store the result in a variable called molten_tse.

  2. Show the first rows of molten_tse and check its dimensions.

  3. How many rows does molten_tse have compared to the number of features and samples in tse? What does one row represent?

  4. Create a path with tempfile(fileext = ".csv") and save molten_tse to it as a CSV file without row names.

  5. Read the CSV file back with read.csv() and check that it has the same dimensions as molten_tse.

  6. Save tse as an Excel file with SEtools. Create the path with tempfile(fileext = ".xlsx").

Useful functions: mia::meltSE(), head(), dim(), nrow(), ncol(), tempfile(), write.csv(), read.csv(), SEtools::se2xls()

# 1. Melt TreeSE into a long data.frame
molten_tse <- meltSE(
    tse,
    assay.type = "counts",
    add.row = TRUE,
    add.col = TRUE
)

# 2. First rows and dimensions
head(molten_tse)
##  # A tibble: 6 × 13
##    FeatureID   SampleID counts Kingdom  Phylum        Class      
##    <fct>       <fct>     <dbl> <chr>    <chr>         <chr>      
##  1 Bacteroides A110      17722 Bacteria Bacteroidetes Bacteroidia
##  2 Bacteroides A111      11630 Bacteria Bacteroidetes Bacteroidia
##  3 Bacteroides A12           0 Bacteria Bacteroidetes Bacteroidia
##  4 Bacteroides A13        8806 Bacteria Bacteroidetes Bacteroidia
##  5 Bacteroides A14        1740 Bacteria Bacteroidetes Bacteroidia
##  6 Bacteroides A15        1791 Bacteria Bacteroidetes Bacteroidia
##  # ℹ 7 more variables: Order <chr>, Family <chr>, Genus <chr>,
##  #   patient_status <chr>, cohort <chr>, patient_status_vs_cohort <chr>, …
dim(molten_tse)
##  [1] 4077   13

# 3. Compare to the number of features and samples
nrow(tse) * ncol(tse)
##  [1] 4077

# 4. Save as a CSV file
csv_file <- tempfile(fileext = ".csv")
write.csv(molten_tse, csv_file, row.names = FALSE)

# 5. Read the CSV file back
df <- read.csv(csv_file)
dim(df)
##  [1] 4077   13
# 6. Save as an Excel file
xlsx_file <- tempfile(fileext = ".xlsx")
SEtools::se2xls(tse, filename = xlsx_file)
  1. The number of rows equals the number of features multiplied by the number of samples. In the long format, each row contains the count of one feature in one sample, together with the information on that feature and that sample.
Exercise 10: Export MultiAssayExperiment as a table

Goal: Export a MultiAssayExperiment as a table.

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

  2. Convert mae into a long format and then into a data.frame. Store the result in a variable called molten_mae.

  3. Show the first rows of molten_mae. Which column tells which experiment each value comes from?

  4. Save molten_mae as a CSV file without row names. Create the path with tempfile(fileext = ".csv").

Useful functions: data(), MultiAssayExperiment::longForm(), data.frame(), head(), tempfile(), write.csv()

# 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. Convert into a long data.frame
molten_mae <- longForm(mae)
molten_mae <- data.frame(molten_mae)

# 3. First rows
head(molten_mae)
##         assay primary               rowname colname value
##  1 microbiota      C1  GAYR01026362.62.2014      C1     0
##  2 microbiota      C1  CVJT01000011.50.2173      C1     1
##  3 microbiota      C1       KF625183.1.1786      C1     0
##  4 microbiota      C1 AYSG01000002.292.2076      C1     0
##  5 microbiota      C1 CCPS01000022.154.1916      C1     7
##  6 microbiota      C1       KJ923794.1.1762      C1     0

# 4. Save as a CSV file
csv_file_mae <- tempfile(fileext = ".csv")
write.csv(molten_mae, csv_file_mae, row.names = FALSE)
  1. The printed object lists the experiments; HintikkaXOData contains three experiments: microbiota, metabolites and biomarkers.
  1. The assay column tells which experiment each value comes from. The other columns give the subject (primary), the sample (colname), the feature (rowname) and the value.
Exercise 11: Export to standard data formats

Goal: Export the data for other microbiome analysis tools.

  1. Create a path for a folder with tempfile(). Export tse to the folder for QIIME2.

  2. List the files in the folder. Which component of tse does each file contain?

  3. Which steps are still needed before the files can be used in QIIME2?

Useful functions: tempfile(), mia::exportQIIME2(), list.files()

# 1. Export for QIIME2
qiime2_dir <- tempfile()
exportQIIME2(tse, qiime2_dir)

# 2. List the files
list.files(qiime2_dir)
##  [1] "counts.tsv"   "metadata.tsv" "taxonomy.tsv" "tree.nwk"
  1. counts.tsv contains the abundance table, taxonomy.tsv the taxonomy table (rowData), metadata.tsv the sample metadata (colData) and tree.nwk the phylogenetic tree (rowTree).

  2. The files must be imported into QIIME2 artifacts (QZA files) in the terminal. The abundance table is first converted to the BIOM format and then imported with qiime tools import, as are the taxonomy table and the tree (Section 4.5).

Back to top