6  Data wrangling

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.

SummarizedExperiment: SummarizedExperiment container. Morgan et al. (2020). R package version 1.20.0. https://bioconductor.org/packages/SummarizedExperiment.
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.

6.1 Splitting

You can split the data based on variables by using the functions agglomerateByRanks() and splitOn(). The former is detailed in Chapter 9.

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 phyla
tse <- agglomerateByRank(tse, rank = "Phylum")

# Split data based on sample type
tse_list <- splitOn(tse, by = "samples", group = "SampleType")

# Loop over the list of TreeSEs, and get top features for each
top_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 entries
colData(tse)$Description <- paste(
    colData(tse)$Description, "modified description"
)

# View modified variable
tse$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 data
new_data <- runif(ncol(tse))

# Store new data as a new variable in colData
colData(tse)$NewVariable <- new_data

# View the new variable
tse$NewVariable |> head()
##  [1] 0.8348 0.5745 0.4696 0.6285 0.8561 0.6239

Alternatively, you can add a whole table by merging it with existing colData.

# Simulate new data
new_data <- data.frame(var1 = runif(ncol(tse)), var2 = runif(ncol(tse)))
rownames(new_data) <- colnames(tse)

# Combine existing data with new data
colData(tse) <- cbind(colData(tse), new_data)

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 values
mat <- rnorm(ncol(tse) * nrow(tse), 0, 1)
mat <- matrix(mat, ncol = ncol(tse), nrow = nrow(tse))

# Add matrix to tse
assay(tse, "random", withDimnames = FALSE) <- mat

assayNames(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.

tse2 <- cbind(tse, tse)
tse2
##  class: TreeSummarizedExperiment 
##  dim: 19216 52 
##  metadata(0):
##  assays(2): counts random
##  rownames(19216): 549322 522457 ... 200359 271582
##  rowData names(7): Kingdom Phylum ... Genus Species
##  colnames(52): CL3 CC1 ... Even2 Even3
##  colData names(10): X.SampleID Primer ... var1 var2
##  reducedDimNames(0):
##  mainExpName: NULL
##  altExpNames(0):
##  rowLinks: a LinkDataFrame (19216 rows)
##  rowTree: 1 phylo tree(s) (19216 leaves)
##  colLinks: NULL
##  colTree: NULL

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.

6.3 Merging

The mia package has a mergeSEs() function that merges multiple SummarizedExperiment objects. For example, it is possible to combine multiple TreeSummarizedExperiment objects, each of which includes one sample.

mergeSEs() works much like standard joining operations. It combines rows and columns and allows you to specify the merging method.

# Take subsets for demonstration purposes
tse1 <- tse[, 1]
tse2 <- tse[, 2]
tse3 <- tse[, 3]
tse4 <- tse[1:100, 4]
# With inner join, we want to include all shared rows. When using mergeSEs
# function all samples are always preserved.
tse <- mergeSEs(list(tse1, tse2, tse3, tse4), join = "inner")
tse
##  class: TreeSummarizedExperiment 
##  dim: 100 4 
##  metadata(0):
##  assays(1): counts
##  rownames(100): 549322 522457 ... 159421 104332
##  rowData names(7): Kingdom Phylum ... Genus Species
##  colnames(4): CL3 CC1 SV1 M31Fcsw
##  colData names(10): X.SampleID Primer ... var1 var2
##  reducedDimNames(0):
##  mainExpName: NULL
##  altExpNames(0):
##  rowLinks: a LinkDataFrame (100 rows)
##  rowTree: 1 phylo tree(s) (19216 leaves)
##  colLinks: NULL
##  colTree: NULL
# Left join preserves all rows of the 1st object
tse <- mergeSEs(tse1, tse4, missing.values = 0, join = "left")
tse
##  class: TreeSummarizedExperiment 
##  dim: 19216 2 
##  metadata(0):
##  assays(1): counts
##  rownames(19216): 549322 522457 ... 200359 271582
##  rowData names(7): Kingdom Phylum ... Genus Species
##  colnames(2): CL3 M31Fcsw
##  colData names(10): X.SampleID Primer ... var1 var2
##  reducedDimNames(0):
##  mainExpName: NULL
##  altExpNames(0):
##  rowLinks: a LinkDataFrame (19216 rows)
##  rowTree: 1 phylo tree(s) (19216 leaves)
##  colLinks: NULL
##  colTree: NULL

6.4 Melting

For several custom analysis and visualization packages, such as those from tidyverse (Wickham et al. 2019), the SummarizedExperiment data can be converted to a long data.frame format with meltSE().

Welcome to the tidyverse. Wickham et al. (2019). J Open Source Softw 4:1686. doi:10.21105/joss.01686.
# Melt SE object
molten_tse <- meltSE(
    tse,
    assay.type = "counts",
    add.row = "Phylum",
    add.col = "SampleType"
)

molten_tse |>
    head() |>
    kable()
FeatureID SampleID counts Phylum SampleType
549322 CL3 0 Crenarchaeota Soil
549322 M31Fcsw 0 Crenarchaeota Feces
522457 CL3 0 Crenarchaeota Soil
522457 M31Fcsw 0 Crenarchaeota Feces
951 CL3 0 Crenarchaeota Soil
951 M31Fcsw 0 Crenarchaeota Feces

For MultiAssayExperiment (Ramos et al. 2017) data, you can instead utilize longForm().

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("HintikkaXOData", package = "mia")
mae <- HintikkaXOData

molten_mae <- longForm(
    mae,
    i = c("counts", "nmr", "signals"),
    colDataCols = c("Rat", "Diet")
)

molten_mae |>
    head() |>
    kable()
assay primary rowname colname value Rat Diet
microbiota C1 GAYR01026362.62.2014 C1 0 1 High-fat
microbiota C1 CVJT01000011.50.2173 C1 1 1 High-fat
microbiota C1 KF625183.1.1786 C1 0 1 High-fat
microbiota C1 AYSG01000002.292.2076 C1 0 1 High-fat
microbiota C1 CCPS01000022.154.1916 C1 7 1 High-fat
microbiota C1 KJ923794.1.1762 C1 0 1 High-fat

6.5 Tidy programming

The tidy paradigm, first introduced in the tidyverse, promotes an intuitive and easy-to-learn coding style, which has made it popular among users. tidyomics bridges the gap between Bioconductor’s SummarizedExperiment ecosystem and the tidyverse (Hutchison et al. 2024).

The tidyomics ecosystem: Enhancing omic data analyses. Hutchison et al. (2024). Nat Methods 21:1166–1170. doi:10.1038/s41592-024-02299-2.
Orchestrating single-cell analysis with Bioconductor. Amezquita et al. (2020). Nat Methods 17:137–145. doi:10.1038/s41592-019-0654-x.

The package tidySingleCellExperiment can be used to manage data in TreeSE, which extends SingleCellExperiment (Amezquita et al. 2020). For instance, we can easily view the object as a tibble abstraction, familiar from tidyverse.

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

library(tidySingleCellExperiment)

tse
##  # A SingleCellExperiment-tibble abstraction: 26 × 8
##  # Features=19216 | Cells=26 | Assays=counts
##    .cell   X.SampleID Primer  Final_Barcode Barcode_truncated_plus_T
##    <chr>   <fct>      <fct>   <fct>         <fct>                   
##  1 CL3     CL3        ILBC_01 AACGCA        TGCGTT                  
##  2 CC1     CC1        ILBC_02 AACTCG        CGAGTT                  
##  3 SV1     SV1        ILBC_03 AACTGT        ACAGTT                  
##  4 M31Fcsw M31Fcsw    ILBC_04 AAGAGA        TCTCTT                  
##  5 M11Fcsw M11Fcsw    ILBC_05 AAGCTG        CAGCTT                  
##  6 M31Plmr M31Plmr    ILBC_07 AATCGT        ACGATT                  
##  # ℹ 20 more rows
##  # ℹ 3 more variables: Barcode_full_length <fct>, SampleType <fct>, …
##  rowLinks: a LinkDataFrame (19216 rows)
##  rowTree: 1 phylo tree(s) (19216 leaves)
##  colLinks: NULL
##  colTree: NULL

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.

tse |>
    join_features(features = rownames(tse), shape = "long") |>
    group_by(.cell) |>
    mutate(total_counts = sum(.abundance_counts)) |>
    group_by(SampleType) |>
    summarise(total_counts = mean(total_counts))
##  # A tibble: 9 × 2
##    SampleType         total_counts
##    <fct>                     <dbl>
##  1 Feces                  1442116 
##  2 Freshwater             1667452 
##  3 Freshwater (creek)     1741407.
##  4 Mock                   1088484.
##  5 Ocean                  1218451 
##  6 Sediment (estuary)      277173.
##  # ℹ 3 more rows

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(ggplot2)

tse |>
    filter(SampleType == "Soil") |>
    transformAssay(method = "clr", pseudocount = 0.5) |>
    join_features(features = rownames(tse), shape = "long") |>
    ggplot(aes(x = .cell, y = .abundance_clr)) +
    geom_boxplot(outlier.alpha = 0.1) +
    labs(x = "Sample", y = "CLR abundance")
Boxplots of CLR-transformed abundances (y-axis), one box per soil sample (x-axis).
Figure 6.1: Distribution of CLR-transformed feature abundances in each soil sample of the GlobalPatterns dataset. Each box represents one sample.

As demonstrated, tidy R programming can be effectively used to manage TreeSummarizedExperiment objects. Please refer to tidySummarizedExperiment and tidySingleCellExperiment vignettes for more examples.

6.6 Exercises

We use the Tengeler2020 dataset, and in Exercise 4 also the HintikkaXOData dataset.

Solve the exercises in order, as each exercise continues from the previous one. Try to solve each exercise yourself before opening the solution.

TipExercise 1: Split the data

Goal: Split the data into a list of TreeSE objects based on a sample variable.

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

  2. Split tse by samples based on the cohort column. Store the result in a variable called tse_list.

  3. How many elements does tse_list have, and what are their names? How many samples does each element contain?

  4. Get the top 5 features of each cohort by looping over tse_list.

  5. Why would you split the data before getting the top features, instead of getting the top features from the whole dataset?

Useful functions: data(), mia::splitOn(), length(), names(), ncol(), sapply(), mia::getTop()

library(mia)

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

# 2. Split by cohort
tse_list <- splitOn(tse, by = "samples", group = "cohort")

# 3. Number of elements, their names and number of samples
length(tse_list)
##  [1] 3
names(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 cohort
sapply(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"
  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.
  1. 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.
TipExercise 2: Add and modify data

Goal: Add and modify variables in colData and add a new assay.

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

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

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

  4. Check the column names of colData(tse). Which columns were added?

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

Useful functions: colData(), paste(), head(), assay(), colSums(), runif(), sample(), data.frame(), colnames(), cbind(), mia::transformAssay(), assayNames()

# 1. Modify an existing variable
colData(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 variable
colData(tse)$library_size <- colSums(assay(tse, "counts"))

# 3. Add a table of new variables
new_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 colData
colnames(colData(tse))
##  [1] "patient_status"           "cohort"                  
##  [3] "patient_status_vs_cohort" "sample_name"             
##  [5] "library_size"             "weight"                  
##  [7] "age"

# 5. Add a new assay
tse <- transformAssay(
    tse,
    assay.type = "counts",
    method = "log10",
    pseudocount = 1,
    name = "log10_counts"
)
assayNames(tse)
##  [1] "counts"       "log10_counts"
  1. The columns library_size, weight and age were added to the end of colData.
TipExercise 3: Combine and merge data

Goal: Combine datasets that have the same features, and merge datasets that have different features.

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

  2. Combine the two subsets back into one TreeSE by their columns. Check the dimensions of the result.

  3. 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?

  4. Merge tse1 and tse2 with an inner join. Check the dimensions of the result.

  5. Merge tse1 and tse2 with a left join, and fill the missing values with 0. Check the dimensions of the result.

  6. 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?

Useful functions: mia::splitOn(), cbind(), dim(), mia::mergeSEs()

# 1. Subsets by patient status
status_list <- splitOn(tse, by = "samples", group = "patient_status")
tse_adhd <- status_list[["ADHD"]]
tse_control <- status_list[["Control"]]

# 2. Combine by columns
tse_combined <- cbind(tse_adhd, tse_control)
dim(tse_combined)
##  [1] 151  27

# 3. Subsets with different features and samples
tse1 <- tse_list[["Cohort_1"]][1:100, ]
tse2 <- tse_list[["Cohort_2"]][51:151, ]
dim(tse1)
##  [1] 100  10
dim(tse2)
##  [1] 101  10

# 4. Inner join
tse_inner <- mergeSEs(tse1, tse2, join = "inner")
dim(tse_inner)
##  [1] 50 20

# 5. Left join
tse_left <- mergeSEs(tse1, tse2, missing.values = 0, join = "left")
dim(tse_left)
##  [1] 100  20
  1. Rows 51 to 100 are included in both subsets, so they have 50 features in common.
  1. 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.
TipExercise 4: Melt data

Goal: Convert the data into a long data.frame.

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

  2. Show the first rows of molten_tse and its column names. Which columns contain the variables that you added in Exercise 2?

  3. Load the HintikkaXOData dataset from the mia package and store it in a variable called mae.

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

Useful functions: mia::meltSE(), head(), colnames(), data(), MultiAssayExperiment::longForm()

# 1. Melt TreeSE
molten_tse <- meltSE(
    tse,
    assay.type = "log10_counts",
    add.row = TRUE,
    add.col = TRUE
)

# 2. First rows and column names
head(molten_tse)
##  # A tibble: 6 × 16
##    FeatureID   SampleID log10_counts Kingdom  Phylum        Class      
##    <fct>       <fct>           <dbl> <chr>    <chr>         <chr>      
##  1 Bacteroides A110             4.25 Bacteria Bacteroidetes Bacteroidia
##  2 Bacteroides A111             4.07 Bacteria Bacteroidetes Bacteroidia
##  3 Bacteroides A12              0    Bacteria Bacteroidetes Bacteroidia
##  4 Bacteroides A13              3.94 Bacteria Bacteroidetes Bacteroidia
##  5 Bacteroides A14              3.24 Bacteria Bacteroidetes Bacteroidia
##  6 Bacteroides A15              3.25 Bacteria Bacteroidetes Bacteroidia
##  # ℹ 10 more variables: Order <chr>, Family <chr>, Genus <chr>,
##  #   patient_status <chr>, cohort <chr>, patient_status_vs_cohort <chr>, …
colnames(molten_tse)
##   [1] "FeatureID"                "SampleID"                
##   [3] "log10_counts"             "Kingdom"                 
##   [5] "Phylum"                   "Class"                   
##   [7] "Order"                    "Family"                  
##   [9] "Genus"                    "patient_status"          
##  [11] "cohort"                   "patient_status_vs_cohort"
##  [13] "sample_name"              "library_size"            
##  [15] "weight"                   "age"

# 3. Load the MultiAssayExperiment
data("HintikkaXOData", package = "mia")
mae <- HintikkaXOData

# 4. Convert the MultiAssayExperiment into a long format
molten_mae <- longForm(
    mae,
    i = c("counts", "nmr", "signals"),
    colDataCols = c("Rat", "Diet")
)
head(molten_mae)
##  DataFrame with 6 rows and 7 columns
##          assay     primary               rowname  colname     value      Rat
##    <character> <character>           <character> <factor> <numeric> <factor>
##  1  microbiota          C1  GAYR01026362.62.2014       C1         0        1
##  2  microbiota          C1  CVJT01000011.50.2173       C1         1        1
##  3  microbiota          C1       KF625183.1.1786       C1         0        1
##  4  microbiota          C1 AYSG01000002.292.2076       C1         0        1
##  5  microbiota          C1 CCPS01000022.154.1916       C1         7        1
##  6  microbiota          C1       KJ923794.1.1762       C1         0        1
##        Diet
##    <factor>
##  1 High-fat
##  2 High-fat
##  3 High-fat
##  4 High-fat
##  5 High-fat
##  6 High-fat
  1. 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.
TipExercise 5: Tidy R programming

Goal: Manipulate a TreeSE with tidy R programming.

  1. Load the tidySingleCellExperiment package and print tse. How does the printed object look now?

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

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

Useful functions: tidySingleCellExperiment::join_features(), dplyr::group_by(), dplyr::mutate(), dplyr::summarise(), dplyr::filter(), ncol()

# 1. Print TreeSE as a tibble
library(tidySingleCellExperiment)

tse
##  # A SingleCellExperiment-tibble abstraction: 27 × 8
##  # Features=151 | Cells=27 | Assays=counts, log10_counts
##    .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 group
tse |>
    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_1
tse_cohort1 <- tse |>
    filter(cohort == "Cohort_1")
ncol(tse_cohort1)
##  [1] 10
  1. 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.
Back to top