Appendix C — Example solutions for exercises

C.1 Introduction

These example solutions are related to exercises in Chapter 1 and Chapter 2.

C.2 Data containers

These example solutions are related to exercises in Chapter 3.

C.3 Import

These example solutions are related to exercises in Chapter 4.

C.4 Convert & export

These example solutions are related to exercises in Chapter 5.

Show the solution
# Load example dataset
library(mia)
data("GlobalPatterns", package = "mia")
tse <- GlobalPatterns

# Convert to Phyloseq and reconvert to a new Dataset
ps <- convertToPhyloseq(tse)
tse_new <- convertFromPhyloseq(ps)

# Save the reconverted file to a RDS file and read it
saveRDS(tse_new, "tse.rds")
tse_read <- readRDS("tse.rds")

# Converting TreeSE to long format and writing it in a CSV file
lf <- meltSE(tse_read)
write.csv(lf, "long_format_tse.csv")

C.5 Taxonomic information

These example solutions are related to exercises in Chapter 6.

Show the solution
# load example dataset
library(mia)
library(miaViz)
data("Tengeler2020", package = "mia")
tse <- Tengeler2020

# Available taxonomic ranks
taxonomyRanks(tse)

# Unique taxonomic features from class
getUnique(tse, rank = "Order")

# Subsets the data and aligns the tree
tse_sub <- tse[1:15, ]
rowTree(tse_sub)$Nnode

tse_sub <- subsetByLeaf(tse_sub, rowLeaf = rownames(tse_sub))
rowTree(tse_sub)$Nnode

# Creates plot for the phylogeny
p1 <- plotRowTree(tse_sub)

# Creates taxonomic tree
tse_sub_hierarchy <- tse_sub
tse_sub_hierarchy <- addHierarchyTree(tse_sub_hierarchy)

# Creates plot for the taxonomic tree
p2 <- plotRowTree(tse_sub_hierarchy)

# Plots trees
library(patchwork)
p1 + p2

C.6 Data wrangling

These example solutions are related to exercises in Chapter 7.

Show the solution
# Load first example dataset
library(mia)
data("enterotype", package = "mia")
tse <- enterotype

# Visualize column metadata
colData(tse) |> head()

# Create variable 'group' containing 3 random classifications for each entry
tse[["group"]] <- sample(
    c("group_1", "group_2", "group_3"),
    ncol(tse),
    replace = TRUE
)

# Plot how groups are distributed
library(miaViz)
plotBarplot(tse, col.var = "group")

# Split groups into two different tse objects and outputs a list
tse_list <- splitOn(tse, by = 2, group = "group")

# Count numbers of entries in the group
tse_list[[1]][["group"]] |> table()
tse_list[[2]][["group"]] |> table()
tse_list[[3]][["group"]] |> table()

# Sum the abundances correspondent to each group and
# merge them back into a single tse object
tse_list <- lapply(tse_list, function(x) {
    mat <- assay(x, "counts")
    sum_val <- sum(mat)
    x[["summed_value"]] <- sum_val
    return(x)
})
tse <- unsplitOn(tse_list)

# Load second example dataset and merges them
data("GlobalPatterns")
tse <- mergeSEs(tse, GlobalPatterns)
colData(tse)

C.7 Exploration & quality control

These example solutions are related to exercises in Chapter 8.

Show the solution
# Load example dataset
library(mia)
library(miaViz)
data("GlobalPatterns")
tse <- GlobalPatterns

# Plot counts with a histogram
plotHistogram(tse, assay.type = "counts")

# Add prevalence to rowData
tse <- addPrevalence(tse)

# Plot the distribution of prevalence values
plotHistogram(tse, row.var = "prevalence")

# Add library size to colData
tse <- addQC(tse)
# And visualize them
plotHistogram(tse, col.var = "total")

# Plot categorical values with a barplot
plotBarplot(tse, col.var = "SampleType")

# Available taxonomic ranks
taxonomyRanks(tse)

# Checks the dominance of genera
summarizeDominance(tse, rank = "Genus")

# Get the most prevalent taxa
getPrevalent(tse, rank = "Genus", prevalence = 0.2, detection = 1)

# Get the most abundant taxa based on their median abundance
getTop(tse, method = "median")

# Visualzie the most prevalent features
plotAbundanceDensity(tse)

C.8 Subsetting

These example solutions are related to exercises in Chapter 9.

Show the solution
# Loading one of the available example datasets
library(mia)
data("GlobalPatterns", package = "mia")
tse <- GlobalPatterns

# Adds total size of all libraries to colData
tse <- addQC(tse)

# Visualizes colData and plots distribution of library sizes
colData(tse) |> head()
library(miaViz)
plotHistogram(x = tse, col.var = "total")

# Subsets based on library size and then subsets again based on feature prevalence
tse_library <- tse[, tse$total > 500000]
tse_subset <- subsetByPrevalent(tse_library, detection = 1, prevalence = 2 / 10)

C.9 Agglomeration

These example solutions are related to exercises in Chapter 10.

Show the solution
# Load packages and dataset
library(mia)
data("GlobalPatterns")
tse <- GlobalPatterns

# Show taxonomic ranks
taxonomyRanks(tse)

# Show the unique values for a rank
getUnique(tse, rank = "Phylum")

# Agglomerate by rank and shows # of rows
tse_agglomerated <- agglomerateByRank(tse, rank = "Phylum")
nrow(tse_agglomerated)

# Show rowData
rowData(tse_agglomerated)

# Agglomerate by all ranks and shows one
tse_all_ranks <- agglomerateByRanks(tse)
altExpNames(tse_all_ranks)
altExp(tse_all_ranks, "Phylum")

# Agglomerate by prevalence
tse_prevalence <- agglomerateByPrevalence(tse)
altExp(tse, "prevalent") <- agglomerateByPrevalence(tse)

# Show column variables and merges the data based on one
colData(tse) |> colnames()
tse_variable <- agglomerateByVariable(tse, group = "SampleType", by = "cols")

C.10 Transformation

These example solutions are related to exercises in Chapter 11.

Show the solution
# Load the example dataset
library(mia)
library(miaViz)
data("GlobalPatterns")
tse <- GlobalPatterns

# Visualize counts
plotHistogram(tse, assay.type = "counts")

# Transformations on the counts assay
tse <- transformAssay(tse, assay.type = "counts", method = "relabundance")
tse <- transformAssay(tse, assay.type = "counts", method = "clr", pseudocount = 1)

assayNames(tse)

# Plots the two different assays
library(patchwork)
p1 <- plotHistogram(tse, assay.type = "counts")
p2 <- plotHistogram(tse, assay.type = "clr")

p1 + p2

# Subset the abundance table
clr_matrix <- assay(tse, "clr")
clr_matrix[1:100, 1:10]

# Agglomerate data by ranks
tse <- agglomerateByRanks(tse)

# Apply transformations across altExp
tse <- transformAssay(
    tse,
    altexp = altExpNames(tse), assay.type = "counts", method = "relabundance"
)
tse <- transformAssay(
    tse,
    altexp = altExpNames(tse), assay.type = "counts", method = "clr", pseudocount = 1
)

# phILR transformation. phILR requires a phylogenetic tree. Agglomerating
# GlobalPatterns to family level would remove the tree, because the families
# are not monophyletic. We therefore use prevalent taxa without agglomeration,
# and prune the tree to match the remaining features.
prevalent <- getPrevalent(tse, prevalence = 0.2)
tse <- tse[prevalent, ]
tse <- subsetByLeaf(tse, rowLeaf = rownames(tse))
tse <- transformAssay(
    tse,
    assay.type = "counts", method = "philr", MARGIN = 1L, pseudocount = TRUE
)

assay(altExp(tse, "philr"))

C.11 Community composition

These example solutions are related to exercises in Chapter 12.

C.12 Alpha Diversity

These example solutions are related to exercises in Chapter 13.

C.13 Community similarity

These exercises are related to exercises in Chapter 14.

C.14 Community typing

These example solutions are related to exercises in Chapter 15.

C.15 Differential abundance

These example solutions are related to exercises in Chapter 16.

C.16 Correlation

These example solutions are related to exercises in Chapter 17.

C.17 Mediation

These example solutions are related to exercises in Chapter 18.

C.18 Cross-association

These example solutions are related to exercises in Chapter 20.

Show the solution
# Load the example dataset
library(mia)
data(HintikkaXOData)
mae <- HintikkaXOData

# Agglomerate microbiome data
mae[[1]] <- agglomerateByPrevalence(mae[[1]], rank = "Phylum")

# Apply CLR
mae[[1]] <- transformAssay(mae[[1]], assay.type = "counts", method = "rclr")

# Apply relative and log10
mae[[2]] <- transformAssay(mae[[2]], assay.type = "nmr", method = "relabundance")
mae[[2]] <- transformAssay(mae[[2]], assay.type = "relabundance", method = "log10", pseudocount = TRUE)

# Cross correlates data sets
res <- getCrossAssociation(
    mae,
    experiment1 = 1,
    experiment2 = 2,
    assay.type1 = "rclr",
    assay.type2 = "log10",
    method = "spearman",
    mode = "matrix"
)

# Create a heatmap
library(ComplexHeatmap)
p <- Heatmap(res)
p

C.19 Ordination-based multiassay analysis

These example solutions are related to exercises in Chapter 21.

Show the solution
# Load the example dataset
library(mia)
library(miaViz)
data(HintikkaXOData)
mae <- HintikkaXOData

# Check the experiments, their assays, and whether samples are matched
experiments(mae)
lapply(experiments(mae), assayNames)
sampleMap(mae)
complete.cases(mae) |> all()

# Agglomerate microbiome data to genus level
mae[["microbiota"]] <- agglomerateByRank(mae[["microbiota"]], rank = "Genus")

# Filter rare genera from raw counts. Filtering is based on counts and
# prevalence, which are not meaningful after the rclr transformation.
features <- getPrevalent(mae[["microbiota"]], prevalence = 0.1)
mae[["microbiota"]] <- mae[["microbiota"]][features, ]

# Apply rclr without imputing zeros
mae[["microbiota"]] <- transformAssay(
    mae[["microbiota"]],
    method = "rclr",
    impute = FALSE
)

# Number and proportion of missing values
mat <- assay(mae[["microbiota"]], "rclr")
sum(is.na(mat))
mean(is.na(mat))

# Transform the other omics
mae[["metabolites"]] <- transformAssay(
    mae[["metabolites"]],
    assay.type = "nmr",
    method = "log10"
)
mae[["biomarkers"]] <- transformAssay(
    mae[["biomarkers"]],
    assay.type = "signals",
    method = "standardize",
    MARGIN = "rows"
)

# Run Joint-RPCA with three components
set.seed(123)
mae <- addJointRPCA(
    mae,
    experiments = c("microbiota", "metabolites", "biomarkers"),
    assay.types = c("rclr", "log10", "standardize"),
    ncomponents = 3
)

# Visualize explained variance
plotJointRPCAExplainedVariance(mae, "JointRPCA")

# Visualize samples in the space of the first two components
plotJointRPCA(mae, "JointRPCA", colour.by = "Diet")

# Visualize features with the largest loadings
plotJointRPCALoadings(mae, "JointRPCA", ncomponents = 2, n = 10)

# Visualize correlations between the top features as a heatmap and a network
plotJointRPCACovariance(mae, "JointRPCA", ntop = 10, correlation = TRUE)
plotJointRPCANetwork(mae, "JointRPCA", show.label = TRUE)
Show the solution
# Use the same dataset as in the Joint-RPCA exercise
library(mia)
data(HintikkaXOData)
mae_mofa <- HintikkaXOData

# Agglomerate microbiome data to prevalent genera
mae_mofa[["microbiota"]] <- agglomerateByPrevalence(
    mae_mofa[["microbiota"]],
    rank = "Genus"
)

# Apply CLR
mae_mofa[["microbiota"]] <- transformAssay(
    mae_mofa[["microbiota"]],
    method = "clr",
    pseudocount = TRUE
)

# Apply relative and log10 transformations to metabolites. Biomarkers
# contain missing values and zeros, so they are only standardized below.
mae_mofa[["metabolites"]] <- transformAssay(
    mae_mofa[["metabolites"]],
    assay.type = "nmr",
    method = "relabundance"
)
mae_mofa[["metabolites"]] <- transformAssay(
    mae_mofa[["metabolites"]],
    assay.type = "relabundance",
    method = "log10"
)

# Standardize each feature
mae_mofa[["microbiota"]] <- transformAssay(
    mae_mofa[["microbiota"]],
    assay.type = "clr",
    method = "standardize",
    MARGIN = "rows"
)
mae_mofa[["metabolites"]] <- transformAssay(
    mae_mofa[["metabolites"]],
    assay.type = "log10",
    method = "standardize",
    MARGIN = "rows"
)
mae_mofa[["biomarkers"]] <- transformAssay(
    mae_mofa[["biomarkers"]],
    assay.type = "signals",
    method = "standardize",
    MARGIN = "rows"
)

# Make feature names unique
anyDuplicated(rownames(mae_mofa[["microbiota"]]))
rownames(mae_mofa[["microbiota"]]) <- getTaxonomyLabels(
    mae_mofa[["microbiota"]],
    make.unique = TRUE
)

# Create a MOFA object with five factors
library(MOFA2)
model <- mofa2(
    mae_mofa,
    experiments = c("microbiota", "metabolites", "biomarkers"),
    assays = c("standardize", "standardize", "standardize"),
    num_factors = 5
)

# Train the model
model <- run_mofa(model, use_basilisk = TRUE)

# Visualize variance explained per factor and in total
plot_variance_explained(model, x = "view", y = "factor", plot_total = TRUE)

# Visualize samples in the space of the first two factors
plot_factors(model, factors = c(1, 2), color_by = "Diet")

# Visualize the features with the largest weights for each omic
lapply(
    c("microbiota", "metabolites", "biomarkers"),
    plot_top_weights,
    object = model,
    factors = c(1, 2),
    nfeatures = 10
)
Show the solution
# Sample scores from both methods
jrpca_scores <- metadata(mae)[["JointRPCA"]]
mofa_scores <- get_factors(model)[[1]]
samples <- intersect(rownames(jrpca_scores), rownames(mofa_scores))

# Correlate the components and factors. The sign of a component is
# arbitrary, so absolute correlations are compared.
abs(cor(jrpca_scores[samples, ], mofa_scores[samples, ]))

# Top 20 microbial features of the first Joint-RPCA component
rot <- attr(jrpca_scores, "rotation")
rot <- rot[rownames(rot) %in% rownames(mae[["microbiota"]]), ]
jrpca_top <- rownames(rot)[order(abs(rot[, 1]), decreasing = TRUE)][1:20]

# Top 20 microbial features of the first MOFA factor
w <- get_weights(model, views = "microbiota")[[1]]
mofa_top <- rownames(w)[order(abs(w[, 1]), decreasing = TRUE)][1:20]
# MOFA2 adds the view name as a suffix to the feature names
mofa_top <- sub("_microbiota$", "", mofa_top)

# Features identified by both methods and by only one. Note that duplicated
# genus names were made unique separately in the two analyses, so names such
# as "uncultured_1" do not necessarily refer to the same taxon.
intersect(jrpca_top, mofa_top)
setdiff(jrpca_top, mofa_top)
setdiff(mofa_top, jrpca_top)

# Cross-association between the top microbial features and metabolites
mae_top <- mae_mofa
mae_top[["microbiota"]] <- mae_top[["microbiota"]][
    rownames(mae_top[["microbiota"]]) %in% union(jrpca_top, mofa_top),
]
res <- getCrossAssociation(
    mae_top,
    experiment1 = "microbiota",
    experiment2 = "metabolites",
    assay.type1 = "clr",
    assay.type2 = "log10",
    method = "spearman",
    mode = "matrix"
)

library(ComplexHeatmap)
Heatmap(res)

C.20 Machine learning

These example solutions are related to exercises in Chapter 23.

Back to top