# 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"
)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.
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:
- BIOM files (McDonald et al. 2012) (see
help(importBIOM, package = "mia")) - QIIME2 files (Bolyen et al. 2019) (see
help(importQIIME2, package = "mia")) - Mothur files (Schloss et al. 2009) (see
help(importMothur, package = "mia")) - MetaPhlAn files (Beghini et al. 2021) (see
help(importMetaPhlAn, package = "mia")) - HUMAnN files (Beghini et al. 2021) (see
help(importHUMAnN, package = "mia")) - taxpasta files (Beber et al. 2023) (see
help(importTaxpasta, package = "mia"))
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:
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: NULLThe 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 0The 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 BacteroidesWe notice that the imported biom file did not contain any colData yet, so only an empty table appears in this slot.
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 A23You 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 A15Finally, 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: NULLNow 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 withparseTaxonomy()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): numericmatrix, with feature IDs as rownames and sample IDs as column names.rowData(tax):DataFrameordata.frame, with feature IDs as rownames. If this is adata.frame, theTreeSummarizedExperiment()constructor converts the table automatically intoDataFrameformat (you can also do that manually with aDataFrame()function). Column names are free but in microbiome analysis they usually refer to taxonomic ranks. The rownames inrowDatashould match the rownames in the abundance table.colData(samples):DataFrameordata.frame, with sample IDs as rownames. If this is adata.frame, theTreeSummarizedExperiment()constructor converts the table automatically intoDataFrameformat (you can also do that manually with aDataFrame()function). Column names are free. The rownames incolDatashould 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:
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] TRUEEnsure 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→ numericmatrix -
rowData→DataFrameordata.frame -
colData→DataFrameordata.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: NULLNow 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: NULLWhen 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 filesWhen 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.
# 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 files4.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: NULLWe 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.
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: NULLR 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).
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 SprockettTHDataAll 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 <- HintikkaXODataData 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.
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.
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.
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.
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.
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()
|
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().
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.
# 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.
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.
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.qzaAlternatively, 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.