This chapter introduces several essential techniques for preparing data for analysis. These techniques include splitting data, modifying data, and converting data to a data.frame. Additionally, it explains how to merge multiple SummarizedExperiment(Morgan et al. 2020) objects when needed. For a basic understanding of TreeSummarizedExperiment(Huang et al. 2021) please refer to Chapter 3.
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.
If you want to split the data based on a variable other than taxonomic rank, use splitOn(). It works for row-wise and column-wise splitting. Splitting the data may be useful, for example, if you want to analyze data from different cohorts separately.
The following example demonstrates how to identify the most abundant taxonomic features for each sample type. Given that some samples have a different origin, we expect differences between sample types. While getTop() can be used to determine the most abundant features across the entire dataset, this approach would obscure features that are specific to individual sample types.
library(mia)library(knitr)# Only needed for formatting the tables with kable()data("GlobalPatterns", package ="mia")tse<-GlobalPatterns# Agglomerate to phylatse<-agglomerateByRank(tse, rank ="Phylum")# Split data based on sample typetse_list<-splitOn(tse, by ="samples", group ="SampleType")# Loop over the list of TreeSEs, and get top features for eachtop_taxa<-sapply(tse_list, getTop)top_taxa|>kable()
Soil
Feces
Skin
Tongue
Freshwater
Freshwater (creek)
Ocean
Sediment (estuary)
Mock
Proteobacteria
Firmicutes
Firmicutes
Proteobacteria
Cyanobacteria
Cyanobacteria
Proteobacteria
Proteobacteria
Firmicutes
Acidobacteria
Bacteroidetes
Proteobacteria
Firmicutes
Actinobacteria
Proteobacteria
Bacteroidetes
Bacteroidetes
Bacteroidetes
Verrucomicrobia
Cyanobacteria
Actinobacteria
Bacteroidetes
Proteobacteria
Bacteroidetes
Cyanobacteria
Cyanobacteria
Proteobacteria
Bacteroidetes
Actinobacteria
Bacteroidetes
Actinobacteria
Bacteroidetes
Verrucomicrobia
Actinobacteria
Crenarchaeota
Actinobacteria
Actinobacteria
Proteobacteria
Fusobacteria
Fusobacteria
Verrucomicrobia
Chloroflexi
Euryarchaeota
Planctomycetes
Tenericutes
6.2 Adding variables
The information contained in the colData of a TreeSummarizedExperiment can be added and/or modified by accessing the desired variables. You might want to add or modify this data to include new variables or update existing ones, which can be essential for ensuring that all relevant metadata is available for subsequent analyses.
data("GlobalPatterns", package ="mia")tse<-GlobalPatterns# Modify the Description entriescolData(tse)$Description<-paste(colData(tse)$Description, "modified description")# View modified variabletse$Description|>head()## [1] "Calhoun South Carolina Pine soil, pH 4.9 modified description" ## [2] "Cedar Creek Minnesota, grassland, pH 6.1 modified description" ## [3] "Sevilleta new Mexico, desert scrub, pH 8.3 modified description"## [4] "M3, Day 1, fecal swab, whole body study modified description" ## [5] "M1, Day 1, fecal swab, whole body study modified description" ## [6] "M3, Day 1, right palm, whole body study modified description"
New information can be added to the experiment by creating a new variable.
# Simulate new datanew_data<-runif(ncol(tse))# Store new data as a new variable in colDatacolData(tse)$NewVariable<-new_data# View the new variabletse$NewVariable|>head()## [1] 0.95952 0.01823 0.44617 0.92683 0.73155 0.15687
Alternatively, you can add a whole table by merging it with existing colData.
Similar steps can also be applied to rowData. If you have an assay whose rows and columns align with the existing ones, you can add the assay easily to the TreeSummarizedExperiment object.
Here we add an assay that has random numbers but in real life these steps might come in handy after you have transformed the data with custom transformation that cannot be found from mia.
# Create a matrix with random valuesmat<-rnorm(ncol(tse)*nrow(tse), 0, 1)mat<-matrix(mat, ncol =ncol(tse), nrow =nrow(tse))# Add matrix to tseassay(tse, "random", withDimnames =FALSE)<-matassayNames(tse)## [1] "counts" "random"
Now we can see that the TreeSummarizedExperiment object has an additional assay called “random”. When adding new samples or features to your existing dataset, you can use cbind() to combine columns for new samples or rbind() to add rows for new features.
However, the aforementioned functions assume that the rows align correctly when combining columns, and vice versa. In practice, this is often not the case; for example, samples may have different feature sets. In such situations, using a merging approach is the appropriate method.
By utilizing tidy programming, we could then effortlessly manipulate the data. For instance, we can calculate the mean library size in each sample type. This is done by first calculating library size for each sample and then summarizing total counts in each sample type; all done by using the tidy paradigm. For more information on library size, see Chapter 7.
We can then filter samples and leverage ggplot2(Wickham 2016) for plotting. In the example below, we select soil samples and visualize their abundances with a boxplot (Figure 6.1). Of course, these tidy commands can be combined with mia tools. Before plotting, we apply CLR transformation by using transformAssay() (see more on transformation from Chapter 10).
ggplot2: Elegant graphics for data analysis. Wickham (2016). Springer International Publishing. doi:10.1007/978-3-319-24277-4.
library(mia)# 1. Load the datadata("Tengeler2020", package ="mia")tse<-Tengeler2020# 2. Split by cohorttse_list<-splitOn(tse, by ="samples", group ="cohort")# 3. Number of elements, their names and number of sampleslength(tse_list)## [1] 3names(tse_list)## [1] "Cohort_1" "Cohort_2" "Cohort_3"sapply(tse_list, ncol)## Cohort_1 Cohort_2 Cohort_3 ## 10 10 7# 4. Top 5 features in each cohortsapply(tse_list, getTop, top =5)## Cohort_1 Cohort_2 Cohort_3 ## [1,] "Bacteroides" "Bacteroides" "Bacteroides" ## [2,] "Bacteroides_1" "Parabacteroides" "Parabacteroides" ## [3,] "Bacteroides_3" "Bacteroides_1" "Bacteroides_1" ## [4,] "Bacteroides_2" "Bacteroides_2" "Akkermansia" ## [5,] "Akkermansia" "Akkermansia" "Parabacteroides_1"
The list has one TreeSE for each unique value in cohort, and the elements are named after these values. Each element contains only the samples of one cohort.
The top features of the whole dataset describe all samples together. Features that are abundant only in some of the groups can then be hidden. Splitting the data first gives the top features of each group separately.
Exercise 2: Add and modify data
Goal: Add and modify variables in colData and add a new assay.
Modify the sample_name column of colData(tse) by adding the text "mouse" before each sample name. Show the first values of the modified column.
Calculate the library size of each sample, that is, the sum of counts in each sample, with colSums(assay(tse, "counts")). Store it in colData as a new variable called library_size.
Simulate body weights for the mice with runif(ncol(tse), min = 20, max = 30) and ages with sample(8:12, ncol(tse), replace = TRUE). Store them in a data.frame with the columns weight and age, and set the sample names of tse as its row names. Add the table to colData(tse).
Check the column names of colData(tse). Which columns were added?
Apply the log10 transformation with a pseudocount of 1 to the counts assay with transformAssay(), and store the result as a new assay called "log10_counts". Check the names of the assays.
# 1. Modify an existing variablecolData(tse)$sample_name<-paste("mouse", colData(tse)$sample_name)head(tse$sample_name)## [1] "mouse A110" "mouse A111" "mouse A12" "mouse A13" "mouse A14" ## [6] "mouse A15"# 2. Add a new variablecolData(tse)$library_size<-colSums(assay(tse, "counts"))# 3. Add a table of new variablesnew_data<-data.frame( weight =runif(ncol(tse), min =20, max =30), age =sample(8:12, ncol(tse), replace =TRUE))rownames(new_data)<-colnames(tse)colData(tse)<-cbind(colData(tse), new_data)# 4. Check the columns of colDatacolnames(colData(tse))## [1] "patient_status" "cohort" ## [3] "patient_status_vs_cohort" "sample_name" ## [5] "library_size" "weight" ## [7] "age"# 5. Add a new assaytse<-transformAssay(tse, assay.type ="counts", method ="log10", pseudocount =1, name ="log10_counts")assayNames(tse)## [1] "counts" "log10_counts"
The columns library_size, weight and age were added to the end of colData.
Exercise 3: Combine and merge data
Goal: Combine datasets that have the same features, and merge datasets that have different features.
Split tse by samples based on the patient_status column, and store the result in a variable called status_list. Store its elements in variables called tse_adhd ("ADHD") and tse_control ("Control").
Combine the two subsets back into one TreeSE by their columns. Check the dimensions of the result.
Create two more subsets from tse_list of Exercise 1: tse1 with the rows 1 to 100 of "Cohort_1", and tse2 with the rows 51 to 151 of "Cohort_2". Check their dimensions. How many features do they have in common?
Merge tse1 and tse2 with an inner join. Check the dimensions of the result.
Merge tse1 and tse2 with a left join, and fill the missing values with 0. Check the dimensions of the result.
Why do the inner join and the left join give a different number of rows? Why can cbind() be used in step 2, but not to combine tse1 and tse2?
# 1. Subsets by patient statusstatus_list<-splitOn(tse, by ="samples", group ="patient_status")tse_adhd<-status_list[["ADHD"]]tse_control<-status_list[["Control"]]# 2. Combine by columnstse_combined<-cbind(tse_adhd, tse_control)dim(tse_combined)## [1] 151 27# 3. Subsets with different features and samplestse1<-tse_list[["Cohort_1"]][1:100, ]tse2<-tse_list[["Cohort_2"]][51:151, ]dim(tse1)## [1] 100 10dim(tse2)## [1] 101 10# 4. Inner jointse_inner<-mergeSEs(tse1, tse2, join ="inner")dim(tse_inner)## [1] 50 20# 5. Left jointse_left<-mergeSEs(tse1, tse2, missing.values =0, join ="left")dim(tse_left)## [1] 100 20
Rows 51 to 100 are included in both subsets, so they have 50 features in common.
The inner join keeps only the features that are found in both datasets. The left join keeps all features of the first dataset; the features that are missing from the second dataset get the value given in missing.values. In both cases, all samples are kept. cbind() assumes that the rows of the datasets are the same and in the same order. This is true for tse_adhd and tse_control, which contain all features, but not for tse1 and tse2, which contain different features.
Exercise 4: Melt data
Goal: Convert the data into a long data.frame.
Convert tse from Exercise 2 into a long data.frame with the "log10_counts" assay. Include both the feature information (rowData) and the sample information (colData). Store the result in a variable called molten_tse.
Show the first rows of molten_tse and its column names. Which columns contain the variables that you added in Exercise 2?
Load the HintikkaXOData dataset from the mia package and store it in a variable called mae.
Convert mae into a long format with the assays "counts", "nmr" and "signals", and include the sample variables "Rat" and "Diet". Store the result in a variable called molten_mae and show its first rows.
Each row contains the value of one feature in one sample, together with the information on that feature and that sample. The colData variables library_size, weight and age that you added in Exercise 2 are included as columns, and their values are repeated for each feature of the sample.
Exercise 5: Tidy R programming
Goal: Manipulate a TreeSE with tidy R programming.
Load the tidySingleCellExperiment package and print tse. How does the printed object look now?
With tidy R programming, calculate the library size of each sample and then the mean library size in each group of patient_status. Follow the example in the chapter.
Select the samples of "Cohort_1" with filter() and store the result in a variable called tse_cohort1. Check the number of samples in tse_cohort1.
# 1. Print TreeSE as a tibblelibrary(tidySingleCellExperiment)tse## # A SingleCellExperiment-tibble abstraction: 27 × 8## # [90mFeatures=151 | Cells=27 | Assays=counts, log10_counts[0m## .cell patient_status cohort patient_status_vs_cohort sample_name## <chr> <chr> <chr> <chr> <chr> ## 1 A110 ADHD Cohort_1 ADHD_Cohort_1 mouse A110 ## 2 A111 Control Cohort_1 Control_Cohort_1 mouse A111 ## 3 A12 ADHD Cohort_1 ADHD_Cohort_1 mouse A12 ## 4 A13 Control Cohort_1 Control_Cohort_1 mouse A13 ## 5 A14 Control Cohort_1 Control_Cohort_1 mouse A14 ## 6 A15 ADHD Cohort_1 ADHD_Cohort_1 mouse A15 ## # ℹ 21 more rows## # ℹ 3 more variables: library_size <dbl>, weight <dbl>, age <int>## rowLinks: a LinkDataFrame (151 rows)## rowTree: 1 phylo tree(s) (151 leaves)## colLinks: NULL## colTree: NULL# 2. Mean library size in each grouptse|>join_features(features =rownames(tse), shape ="long")|>group_by(.cell)|>mutate(total_counts =sum(.abundance_counts))|>group_by(patient_status)|>summarise(total_counts =mean(total_counts))## # A tibble: 2 × 2## patient_status total_counts## <chr> <dbl>## 1 ADHD 16130.## 2 Control 19731.# 3. Select samples of Cohort_1tse_cohort1<-tse|>filter(cohort=="Cohort_1")ncol(tse_cohort1)## [1] 10
The object is shown as a tibble, where each row is a sample and the columns are the sample variables in colData. The data is still a TreeSE, and all the usual functions can be used with it.