# Track, Analyze, Visualize: Unravel Your Microbiome's Temporal Pattern with MicrobiomeStat.

Dive into MicrobiomeStat's offerings for longitudinal data exploration in microbiome research. Designed for ease, collaboration, and reproducibility, it upholds openness to the scientific community.

## **MicrobiomeStat:** Supporting Longitudinal Microbiome Analysis in R

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fk9gNWckwavrVlNMJplzt%2Fcover.png?alt=media&amp;token=d8dbab3f-4e97-46be-807b-1d155e2e680a" alt=""><figcaption></figcaption></figure>

MicrobiomeStat is a specialized tool for analyzing longitudinal and paired microbiome data. It can also be used for longitudinal analysis of other omics datatypes as long as the data are properly normalized and transformed. As a special case, cross-sectional and case-control microbiome data analysis is also supported.

## Gitbook LLM Integration

Maximize the potential of MicrobiomeStat by utilizing its Gitbook wiki documentation in conjunction with Gitbook LLM (Large Language Model). In the top right corner of the Gitbook, you'll find the "Ask or Search" feature. Feel free to pose any questions you might have, such as "How to filter microbiome data in MicrobiomeStat?"

The Gitbook LLM, fine-tuned specifically for the MicrobiomeStat wiki, will provide you with the answers you need. For example:

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-a5e6721ab0e6d54de29d2d064bb5f24e441bf3a2%2Fgitbook_llm_example.png?alt=media" alt="Example of Gitbook LLM providing an answer"><figcaption><p>Example of Gitbook LLM providing an answer to a question</p></figcaption></figure>

By leveraging this feature, you can quickly find solutions and guidance for using MicrobiomeStat effectively in your research.

## Also Check Out: FlashDeconv

We're excited to introduce `FlashDeconv`, our ultra-fast tool for **spatial transcriptomics cell type deconvolution**. FlashDeconv uses random sketching to achieve O(N) time complexity, making it the fastest deconvolution method available.

Key features of `FlashDeconv`:

* **Ultra-Fast Processing**: Deconvolves 1M spots in \~3 minutes on CPU (no GPU required)
* **O(N) Time Complexity**: Scales linearly with dataset size through random sketching
* **Seamless Integration**: Works directly with scanpy/AnnData workflows
* **Automatic Marker Selection**: Identifies optimal marker genes for each cell type
* **Spatial Regularization**: Produces smooth, biologically meaningful proportion maps

For researchers working with spatial transcriptomics data (Visium, Slide-seq, MERFISH, etc.), `FlashDeconv` offers unprecedented speed without sacrificing accuracy. Learn more on GitHub: [FlashDeconv Repository](https://github.com/cafferychen777/FlashDeconv).

Install with: `pip install flashdeconv`

## Also Check Out: mLLMCelltype

We're excited to introduce `mLLMCelltype`, our innovative framework for **single-cell RNA sequencing data annotation**. This iterative multi-LLM consensus framework leverages the collective intelligence of multiple large language models (including GPT-4o/4.1, Claude-3.7/3.5, Gemini-2.0, Grok-3, and others) to significantly improve cell type annotation accuracy while providing transparent uncertainty quantification.

`mLLMCelltype` addresses critical challenges in scRNA-seq analysis through its unique architecture:

* **Multi-LLM Consensus**: Overcomes single-model limitations by harnessing diverse LLMs' collective intelligence
* **Structured Deliberation**: Enables models to share reasoning, evaluate evidence, and refine annotations through collaborative discussion
* **Transparent Uncertainty Metrics**: Provides quantitative measures to identify ambiguous cell populations requiring expert review
* **Hallucination Reduction**: Suppresses inaccurate predictions through cross-model critical evaluation
* **No Reference Dataset Required**: Performs accurate annotation without pre-training or reference data

For researchers working with single-cell data, `mLLMCelltype` offers a powerful new approach to cell type annotation. Learn more about its capabilities and methodology on GitHub: [mLLMCelltype Repository](https://github.com/cafferychen777/mLLMCelltype).

## Dependencies

It depends on packages such as `rlang`, `tibble`, `ggplot2`, `matrixStats`, `lmerTest`, `foreach`, `modeest`, `vegan`, `dplyr`, `pheatmap`, `tidyr`, `ggh4x`, `ape`, `GUniFrac`, `scales`, `stringr`, `rmarkdown`, `knitr`, `pander`, and `tinytex`. We thank the authors of these packages, whose work has greatly facilitated the development of MicrobiomeStat.

We also acknowledge the work by the developers of `microbiomeutilities`, `phyloseq`, `microbiomemarker`, `MicrobiomeAnalyst`, `microeco`, `EasyAmplicon`, `STAMP`, `qiime2`, `MicrobiotaProcess`, `q2-longitudinal`, `SplinectomeR`, and `coda4microbiome`. Their contributions have significantly advanced the field and inspired us in creating MicrobiomeStat.

## News

### Version 1.5.1 (April 2026)

MicrobiomeStat v1.5.1 brings significant improvements:

* **`linda2()` exported**: Enhanced differential abundance testing with phylogenetic tree-guided smoothing (`tree.smooth = TRUE`), Max-T omnibus p-values (`omnibus = TRUE`), and Detection Depth Weighting (`weights = "detection_depth"`) for handling sample quality heterogeneity
* **Unified analysis interface**: 6 core functions (`plot_taxa`, `plot_alpha`, `plot_beta`, `test_taxa`, `test_alpha`, `test_beta`) that automatically detect study design and route to the appropriate underlying functions. See the [Unified API guide](/introduction/unified-api-simplify-your-analysis) for details.
* **`ref.level` parameter**: Explicitly specify reference groups in taxa differential testing functions (`generate_taxa_test_single`, `generate_taxa_test_pair`, `generate_taxa_change_test_pair`, `generate_taxa_trend_test_long`)
* **Reproducible rarefaction**: `mStat_normalize_data()` now accepts a `seed` parameter (default 123) for reproducible rarefaction
* **New data converters**: `mStat_convert_MRExperiment_to_data_obj()` and `mStat_convert_MultiAssayExperiment_to_data_obj()` for importing data from metagenomeSeq and MultiAssayExperiment objects
* **8 critical statistical bug fixes**: Including PERMANOVA distance/metadata misalignment, LinDA zero-handling dispatch, volatility test covariate adjustment, and more
* **"other" feature data type**: Explicit support for pre-processed non-compositional data

### January 8th, 2024

Exciting news for our users! We have enhanced the color palette functionality in our package. You can now use predefined palette names like "lancet", "nejm", "npg", "aaas", "jama", "jco", and "ucscgb" directly in the `palette` parameter across most functions. This update simplifies the process of customizing color schemes in your data visualizations, making your plots more visually appealing and easier to interpret. For more details, please refer to the function documentation.

### October 20th, 2023

We are pleased to announce that the Shiny interface for `MicrobiomeStat` is now officially available. This interface provides an interactive platform for microbiome data analysis, making it more accessible and user-friendly. The Shiny application can be accessed directly at [this link](https://microbiomestat.shinyapps.io/MicrobiomeStat-Shiny/). For users who prefer a local setup or require more customization, the Shiny application files and instructions are available on its dedicated [GitHub repository](https://github.com/cafferychen777/MicrobiomeStat-Shiny).

Stay tuned for more updates and enhancements as we continue to improve `MicrobiomeStat` for our user community.

## Contribute to MicrobiomeStat and Its Wiki

We welcome contributions to both the MicrobiomeStat project and its Wiki. Here's a guide on how to contribute using GitHub Desktop:

1. Download and install [GitHub Desktop](https://desktop.github.com/).
2. Visit the [MicrobiomeStat repository](https://github.com/cafferychen777/MicrobiomeStat) and [MicrobiomeStat Wiki repository](https://github.com/cafferychen777/MicrobiomeStat-Wiki) on GitHub.
3. Click the "Fork" button in the top-right corner to create a copy of the repository in your account.
4. Open GitHub Desktop and select "File" > "Clone Repository". Choose the repository you just forked and clone it to your local machine.
5. Make your desired changes or additions to the Wiki content locally.
6. In GitHub Desktop, you'll see the modified files. Add a brief commit message and click "Commit to main".
7. Click "Push origin" at the top to push your changes to your GitHub repository.
8. Return to the GitHub website and navigate to your repository. You'll see a "Contribute" button - click it and select "Open pull request".
9. Fill in the pull request description and submit it.

Our team will review your pull request and merge the changes once approved. By contributing to the Wiki, you'll be helping to improve the documentation and resources available to the MicrobiomeStat user community. We appreciate your support in making this project better for everyone!

If you encounter any issues during this process, please feel free to open an issue on GitHub for assistance.

## Resources

* MicrobiomeStat Repository: [GitHub](https://github.com/cafferychen777/MicrobiomeStat)
* MicrobiomeStat Shiny Repository: [GitHub](https://github.com/cafferychen777/MicrobiomeStat-Shiny)
* Shiny Web Application: [Link](https://microbiomestat.shinyapps.io/MicrobiomeStat-Shiny/)
* MicrobiomeStat Github Pages: [Link](https://cafferychen777.github.io/MicrobiomeStat/index.html)
* Function Documentation: [Link](https://cafferychen777.github.io/MicrobiomeStat/reference/index.html)
* Gitbook Wiki: [Link](https://www.microbiomestat.wiki/)

## Contributors

We would like to express our gratitude to the following contributors for their valuable contributions to the MicrobiomeStat project:

| [![cafferychen777's avatar](https://github.com/cafferychen777.png?size=300)](https://github.com/cafferychen777) | [![jchen1981's avatar](https://github.com/jchen1981.png?s=0.001)](https://github.com/jchen1981) | [![zhangxiany-tamu's avatar](https://github.com/zhangxiany-tamu.png?s=0.001)](https://github.com/zhangxiany-tamu) | [![zhouhj1994's avatar](https://github.com/zhouhj1994.png?s=0.001)](https://github.com/zhouhj1994) | [![ZengTaox's avatar](https://github.com/ZengTaox.png?s=0.001)](https://github.com/ZengTaox) |
| --------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |

## Star History

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FGFCvaQbyU6GVryMW6Xo6%2Fstar-history-20241025.png?alt=media&amp;token=74c28ade-d0c4-4119-8cec-65e81178528a" alt=""><figcaption></figcaption></figure>


# Exploring MicrobiomeStat: A Consideration for Your Research Toolkit

MicrobiomeStat provides a user-centric, adaptable, and supportive environment for insightful microbiome data exploration.

MicrobiomeStat provides comprehensive support for a wide array of input formats, accommodating the majority of formats utilized in microbiome research, including but not limited to qiime2, dada2, biom, mothur, phyloseq, DGEList, DESeqDataSet, and SummarizedExperiment. This compatibility facilitates an easy data import process. We encourage users to contact us if you encounter a format used in microbiome research that is not currently supported.

MicrobiomeStat offers a wide array of visualization styles, tailored for microbiome research. It optimizes data analysis for paired and longitudinal studies, and generates high-quality, publication-ready figures. Beyond its comprehensive support for longitudinal data analysis and visualization, MicrobiomeStat offers the flexibility to analyze and visualize individual time points. It can also be applied to cross-sectional/case-control data analysis.

MicrobiomeStat provides customizable parameters, allowing users to adapt analysis outputs to their research needs. Built with a high degree of flexibility, MicrobiomeStat is not confined to the analysis of microbiome data alone. Its versatile design extends its capabilities to accommodate and effectively analyze other omics data, making it a candidate tool for omics research and data interpretation.

Our team with rich experience in collaborative microbiome research and statistical methodological development, is committed to delivering rigorous and reproducible analysis of microbiome data.

MicrobiomeStat's outputs are compatible with the 'plotly' package, enabling users to create interactive graphics for further manipulation and customization post-analysis. The combination of time-series and individual time point analysis, along with paired samples analysis, makes MicrobiomeStat a versatile tool for comprehensive microbiome data analysis.

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fmj4UDzBH56eJGuenbc2m%2FDALL%C2%B7E%202024-10-12%2023.41.05%20-%20An%20illustration%20showcasing%20the%20capabilities%20of%20MicrobiomeStat%20for%20microbiome%20research.%20The%20image%20should%20highlight%20support%20for%20various%20input%20formats%20su.webp?alt=media&amp;token=883e6ba9-808d-4dd9-b6fa-379b3c62322a" alt=""><figcaption></figcaption></figure>


# Unified API: Simplify Your Analysis

Use 6 unified functions to perform all analyses, with automatic study design detection.

Starting from version 1.5.1, MicrobiomeStat provides a **unified API** with 6 core functions that automatically detect your study design (cross-sectional, paired, or longitudinal) and route to the appropriate underlying functions. This significantly simplifies the user experience — instead of memorizing dozens of function-specific names, you can use a consistent interface for all analyses.

## Overview

| Function       | Purpose                             | Replaces                                                                                               |
| -------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------ |
| `plot_taxa()`  | Taxonomic visualization             | `generate_taxa_barplot_single()`, `generate_taxa_boxplot_long()`, `generate_taxa_heatmap_pair()`, etc. |
| `plot_alpha()` | Alpha diversity visualization       | `generate_alpha_boxplot_single()`, `generate_alpha_spaghettiplot_long()`, etc.                         |
| `plot_beta()`  | Beta diversity visualization        | `generate_beta_ordination_single()`, `generate_beta_pc_boxplot_long()`, etc.                           |
| `test_taxa()`  | Feature-level statistical testing   | `generate_taxa_test_single()`, `generate_taxa_trend_test_long()`, etc.                                 |
| `test_alpha()` | Alpha diversity statistical testing | `generate_alpha_test_single()`, `generate_alpha_trend_test_long()`, etc.                               |
| `test_beta()`  | Beta diversity statistical testing  | `generate_beta_test_single()`, `generate_beta_trend_test_long()`, etc.                                 |

## How Study Design Detection Works

The unified functions automatically determine your study design based on the parameters you provide:

* **Cross-sectional (single time point)**: When `time.var = NULL` or a single time point is specified
* **Paired samples**: When `time.points` contains exactly 2 values (baseline + follow-up)
* **Longitudinal**: When `time.points` contains more than 2 values, or multiple time points are present in the data

## Visualization Functions

### plot\_taxa()

One function for all taxonomic visualizations.

```r
data(peerj32.obj)

# Cross-sectional barplot
plot_taxa(peerj32.obj, "barplot",
          group.var = "group",
          feature.level = "Phylum",
          feature.dat.type = "count")

# Paired heatmap
plot_taxa(peerj32.obj, "heatmap",
          subject.var = "subject",
          time.var = "time",
          time.points = c("1", "2"),
          group.var = "group",
          feature.level = "Genus",
          feature.dat.type = "count")

# Longitudinal boxplot with relative change
plot_taxa(peerj32.obj, "boxplot",
          subject.var = "subject",
          time.var = "time",
          group.var = "group",
          feature.level = "Family",
          feature.dat.type = "count",
          change.type = "relative")
```

**Supported plot types**: `"barplot"`, `"boxplot"`, `"heatmap"`, `"dotplot"`, `"areaplot"` (longitudinal only), `"spaghettiplot"` (longitudinal only), `"cladogram"` (single time point only).

### plot\_alpha()

One function for all alpha diversity visualizations.

```r
# Cross-sectional alpha boxplot
plot_alpha(peerj32.obj, "boxplot",
           alpha.name = c("shannon", "observed_species"),
           group.var = "group")

# Longitudinal spaghettiplot
plot_alpha(peerj32.obj, "spaghettiplot",
           subject.var = "subject",
           time.var = "time",
           alpha.name = "shannon",
           group.var = "group")
```

**Supported plot types**: `"boxplot"`, `"spaghettiplot"` (longitudinal), `"dotplot"` (longitudinal).

### plot\_beta()

One function for all beta diversity visualizations.

```r
# Cross-sectional ordination
plot_beta(peerj32.obj, "ordination",
          dist.name = c("BC", "Jaccard"),
          group.var = "group")

# Longitudinal ordination
plot_beta(peerj32.obj, "ordination",
          subject.var = "subject",
          time.var = "time",
          dist.name = "BC",
          group.var = "group")
```

**Supported plot types**: `"ordination"`, `"boxplot"`, `"spaghettiplot"`, `"dotplot"`.

## Statistical Testing Functions

### test\_taxa()

One function for all feature-level statistical tests.

```r
# Cross-sectional group comparison
test_taxa(peerj32.obj, "difference",
          group.var = "group",
          feature.level = "Genus",
          feature.dat.type = "count")

# Longitudinal trend test
test_taxa(peerj32.obj, "trend",
          subject.var = "subject",
          time.var = "time",
          group.var = "group",
          feature.level = "Genus",
          feature.dat.type = "count")
```

**Supported test types**: `"difference"` (group comparisons), `"trend"` (temporal trends, longitudinal), `"volatility"` (temporal instability, longitudinal), `"association"` (continuous variable associations), `"per_time"` (test at each time point separately).

### test\_alpha()

One function for all alpha diversity statistical tests.

```r
# Cross-sectional test
test_alpha(peerj32.obj, "difference",
           alpha.name = c("shannon", "simpson"),
           group.var = "group")

# Longitudinal trend test
test_alpha(peerj32.obj, "trend",
           alpha.name = "shannon",
           subject.var = "subject",
           time.var = "time",
           group.var = "group")
```

**Supported test types**: `"difference"`, `"trend"`, `"volatility"`, `"per_time"`.

### test\_beta()

One function for all beta diversity statistical tests (PERMANOVA, etc.).

```r
# Cross-sectional PERMANOVA
test_beta(peerj32.obj, "difference",
          dist.name = c("BC", "Jaccard"),
          group.var = "group")
```

**Supported test types**: `"difference"`, `"trend"`, `"volatility"`.

## Key Parameters

Common parameters shared across the unified functions:

* `data.obj`: MicrobiomeStat data object
* `subject.var`: Subject/sample ID variable (required for paired/longitudinal)
* `time.var`: Time variable (NULL for cross-sectional)
* `group.var`: Grouping variable (e.g., treatment, condition)
* `strata.var`: Stratification variable for faceting
* `time.points`: Time point specification — controls design detection:
  * `NULL`: use all available time points (auto-detect)
  * Single value: cross-sectional at that time point
  * Vector of 2: paired design (baseline, follow-up)
  * Vector of >2: longitudinal with specific time points
* `change.type`: For paired/longitudinal comparisons — `"none"` (raw values), `"relative"`, `"log_fold"`, or `"absolute"`
* `feature.dat.type`: Data type — `"count"`, `"proportion"`, or `"other"`
* `theme`: Plot theme — `"bw"`, `"classic"`, `"gray"`, `"minimal"`, or `"prism"` (also supports `"light"`, `"dark"`, `"void"`)

## When to Use Unified vs. Specific Functions

The unified API is recommended for:

* **Quick exploratory analysis** — fewer function names to remember
* **Switching between study designs** — same function, just change parameters
* **Teaching and tutorials** — simpler mental model

The specific functions (e.g., `generate_taxa_barplot_single()`) are still available and recommended when:

* You need fine-grained control over function-specific parameters
* You are building automated pipelines that call specific functions
* You want to be explicit about which function is invoked

Both approaches produce identical results — the unified functions simply route to the specific functions internally.


# Installation Guide

This document will guide you through the installation process of the MicrobiomeStat package.

## Installation Options

### Option 1: Installation via CRAN

MicrobiomeStat is available on the CRAN repository. To install it, run the following command in your R console:

```r
install.packages("MicrobiomeStat")
```

{% hint style="info" %}
**Note:** The CRAN version of MicrobiomeStat may lag behind the latest development version. For the most up-to-date features, including `linda2()` with tree-guided smoothing, the unified analysis interface, and the latest bug fixes, consider installing the development version from GitHub.
{% endhint %}

### Option 2: Installation via GitHub (Development Version)

The development version of MicrobiomeStat is hosted on GitHub. To install it, you will first need the 'devtools' package. If you haven't installed it yet, you can do so using the command:

```r
install.packages("devtools")
```

After installing 'devtools', you can proceed to install MicrobiomeStat:

```r
devtools::install_github("cafferychen777/MicrobiomeStat")
```

### Checking the Installed Version

After installation, you can check the installed version of MicrobiomeStat to ensure that you have the latest version:

```r
packageVersion("MicrobiomeStat")
```

This should display the version number of MicrobiomeStat. For the development version installed from GitHub, the current version is 1.5.1. Ensure that the displayed version number matches the expected version for the source you installed from (GitHub or CRAN).

## Dependencies

To ensure the proper functioning of MicrobiomeStat, ensure that you have the following packages installed:

### Required CRAN Packages

```r
# List of packages to install
packages_to_install <- c(
  "rlang",
  "tibble",
  "ggplot2",
  "matrixStats",
  "lmerTest",
  "foreach",
  "modeest",
  "dplyr",
  "pheatmap",
  "tidyr",
  "ggh4x",
  "GUniFrac",
  "stringr",
  "rmarkdown",
  "knitr",
  "pander",
  "tinytex",
  "vegan",
  "scales",
   "ape",          # Used only in mStat_convert_phyloseq_to_data_obj and mStat_import_mothur_as_data_obj
  "ggrepel",       # Used only in the linda.plot function
  "parallel",      # Utilized only when setting parallel in linda
  "ggprism",       # Active only when theme.choice is set to “prism”
  "aplot",         # Operates exclusively in generate_beta_ordination_single
  "yaml",          # Employed solely in mStat_import_qiime2_as_data_obj
  "biomformat",    # Used in mStat_import_biom_as_data_obj
  "Biostrings"     # Required for mStat_import_qiime2_as_data_obj and mStat_import_dada2_as_data_obj
)

# Installing packages
install.packages(packages_to_install)

```

{% hint style="info" %}
**Note:** Due to CRAN's restrictions, we couldn't list all the packages that `MicrobiomeStat` depends on as dependencies in our package documentation. However, for a smooth analysis process, it's imperative to have all these packages installed. Please ensure that you've installed all the packages listed above to prevent any disruptions during your analysis using `MicrobiomeStat`.
{% endhint %}

## Troubleshooting

Ensure that you are using the latest versions of R and Bioconductor. If you encounter any issues, it might be because a package requires a specific version of R or Bioconductor.

If you experience problems during installation or usage, follow these steps:

1. Check our Frequently Asked Questions (FAQ) page at <https://app.gitbook.com/o/JyntywoYcDNroaHdd5wZ/s/hFAmY4z7d1R15Cv49vXQ/frequently-asked-questions-faq/general-faqs>. Many common issues and their solutions are addressed there.
2. If your issue isn't covered in the FAQ, visit <https://github.com/cafferychen777/MicrobiomeStat/issues>.
3. Search this page to see if a similar issue has already been reported and resolved.
4. If you don't find a similar issue, feel free to create a new issue to report your specific problem. When describing the issue, please provide as much detail as possible, including your operating system, R version, and any error messages you encountered.
5. If the problem persists, consult the documentation of the problematic package for further guidance.

Thank you for choosing MicrobiomeStat. We will do our best to assist you with any issues you encounter.


# Creating the MicrobiomeStat Data Object

This section outlines the core components of the basic MicrobiomeStat data object. We use the basic list type to encapsulate the key components of a typical microbiome/omics dataset. The use of the basic data structure in R improves the flexibility and interoperability with other tools. In MicrobiomeStat functions, the parameter `data.obj` is designed to receive the basic MicrobiomeStat data object.

## Core Components

### Component 1: feature.tab (matrix)

The primary matrix of the data object is the **feature.tab**. It records the measurements (e.g. counts) of detected features (**OTU/ASV/KEGG/Gene**, etc.) in the samples. In this matrix, features are designated as rows, while samples are designated as columns. It's essential to ensure the row names (feature names) and column names (sample names ) be named properly and uniquely.

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FOXxvadCyW7qEgWZkCdLX%2FScreenshot%202023-10-11%20at%2010.35.59.png?alt=media&amp;token=b54d942e-d1c2-4787-a2aa-81ee4cce58f1" alt=""><figcaption><p>peerj32.obj$feature.tab</p></figcaption></figure>

### Component 2: meta.dat (data.frame)

The **meta.dat** is a structured data.frame that holds metadata describing the sample characteristics. The rows represent the samples and they must align precisely with the columns of the feature.tab. The row names of meta.dat should be the unique sample IDs. Each column in the meta.dat acts as an **annotation** for the samples. The column names should be informative and concise. To facilitate analysis, for continuous/numeric variables, make sure they are of "numeric" type ("as.numeric" to convert), and for categorical variables, make sure they are of "factor" type with informative factor levels ("as.factor" to convert). It is a good practice to order the levels properly when creating a factor and always put the reference level in the first. Level ordering is especially important for ordinal variables. For the meta data of a longitudinal dataset, we expect to see the following variables or similar:

* **subject**: a factor that indicates individual subjects or experimental units in the study. This can be alphanumeric and unique for each participant. For example, "subj001", "subj002", etc. In a longitudinal study, each subject could have multiple samples collected over time. Therefore, the number of unique subjects should be less than the total number of samples. Ideally, each subject should have the same time points. In reality, however, not all subjects may have samples at every time point. Some subjects might miss certain sampling time points due to various reasons such as dropout, missed visits, or sample quality issues. MicrobiomeStat can handle such unbalanced longitudinal data, where not all subjects have samples at every time point. Make sure that each sample (row) in your meta.dat has a valid subject identifier and a corresponding time point.
* **timepoint**: a factor indicating the specific time points at which measurements were taken. The order of the levels should reflect the order of the time points. For example, if measurements were taken at baseline, 6 months, and 12 months, then the levels might be ordered as "baseline", "6mo", "12mo". MicrobiomeStat also supports continuous time point. For example, if the exact days or hours of measurement are known, they can be represented as numerical values such as 0, 180, 365 for days since the study starts.
* **group**: a factor indicating the grouping of subjects, typically for comparison purposes. For example, the group variable contains the "case" and "control" status. We may put "control" in the first/reference level. By doing so, in visualization, "control" will appear before "case", and in regression analysis, the coefficient will be interpreted as the effect when the status changes from "control" to "case".
* Other variables: the variables could be time-varying (sample-level characteristics) or non-time-varying (subject-level characteristics).

{% hint style="info" %}
**Note**: Tibbles are not allowed for this component. Ensure you are working with a standard R data.frame.
{% endhint %}

### Component 3: feature.ann (matrix)

The **feature.ann** is an annotation matrix where features such as **OTU/ASV/KEGG/Gene**, etc., are designated as rows. These row names must exactly match those in the feature.tab to maintain consistency in the data object. The columns of the feature.ann matrix hold **annotations** for the respective research entities/features.

For example:

* In **microbiome data**, typical annotations might include taxonomic classifications, ranging from **Kingdom** to **Species**.
* For **single-cell sequencing data**, this matrix could contain cell type classifications at different granularities.
* In the context of **KEGG data**, the columns might represent various pathway classifications at different hierarchical levels like L1, L2, and L3.

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FQUJH3P5JknXa6vAP8IZC%2FScreenshot%202023-10-11%20at%2010.38.05.png?alt=media&amp;token=e4241580-4e6d-4e11-8cf0-d42ca08a904f" alt=""><figcaption><p>peerj32.obj$feature.ann</p></figcaption></figure>

### Component 4: tree (phylo, optional)

The **phylogenetic tree** represents the evolutionary relationships among the features. In most situations when using MicrobiomeStat, the phylogenetic tree is not required. However, for certain beta-diversity calculations, the phylogenetic tree becomes essential as it provides additional evolutionary context. Unless your analysis specifically requires this evolutionary perspective, you can typically proceed without this component.

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FD3UldaCfnBBquuF9xlq7%2FScreenshot%202023-10-11%20at%2010.42.09.png?alt=media&amp;token=dc763560-1350-489a-9f58-dd0bdd3188d3" alt=""><figcaption><p>MicrobiomeData$tree</p></figcaption></figure>

### Component 5: feature.agg.list (Optional)

The **feature.agg.list** is an optional component derived from the aggregation of data in the **feature.tab** based on annotations in **feature.ann**. This aggregated data is generated using the `mStat_aggregate_by_taxonomy()` function.

The `feature.agg.list` is a list containing matrices for each level of aggregation. For example, if you aggregated the data by taxonomy, you might have entries like `$Phylum`. To access a specific level of aggregation within the `feature.agg.list`, you would use syntax such as `data.obj$feature.agg.list$Phylum`.

For each matrix within the `feature.agg.list`:

* The columns represent the sample names.
* The rows represent the aggregated level, such as `Phylum`.

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FhaCZSAuaW0XycMACBFwU%2FScreenshot%202023-10-11%20at%2010.44.02.png?alt=media&amp;token=05395719-60ed-4b41-be3c-fb9f40fac170" alt=""><figcaption><p>peerj32.obj$feature.agg.list$Phylum</p></figcaption></figure>

It's worth noting that if you call a MicrobiomeStat function and set a `feature.level` parameter other than "original", the function will automatically call `mStat_aggregate_by_taxonomy()` to ensure the data is properly aggregated.

Together, these components comprise the MicrobiomeStat data object, which facilitates a structured representation of microbiome data. After constructing the MicrobiomeStat data object, it is imperative to validate the integrity of the data object using the `mStat_validate_data` function.

## Specialized Data Objects

In addition to the basic data object, the MicrobiomeStat toolkit accepts specialized data objects for specific analyses, such as alpha and beta diversity analysis. These specialized data objects can be passed to the specific parameters (arguments) in relevant MicrobiomeStat functions as detailed below.

### alpha.obj

`alpha.obj`: For functions performing alpha diversity analysis, the `alpha.obj` parameter accepts a data object that encapsulates various alpha diversity measures of the samples (matrix type, rows: samples, columns: alpha diversity measures). The `mStat_calculate_alpha_diversity` function calculates the common alpha diversity measures ("shannon", "simpson", "observed\_species", "chao1", "ace", "pielou"). If no data object is provided to `alpha.obj` where needed, the function will be called automatically. However, to expedite the analysis process, it is advisable to pre-calculate the alpha diversity indices and store them in a properly named data object for future repeated use.

It is important to note that `mStat_calculate_alpha_diversity` does not perform data rarefaction, a process that equalizes the sequencing depth across samples so that the alpha diversity measures (esp. species richness) are not influenced by sequencing depth variation. It is always recommended that the users perform rarefaction using `mStat_rarefy_data` before calculating the alpha diversity.

### dist.obj

`dist.obj`: For functions performing beta diversity (distance) analysis, the `dist.obj` parameter accepts a data object containing various beta diversity measures in the form of pairwise distances (list type, each element a distance matrix). The `mStat_calculate_beta_diversity` function calculates the common beta diversity measures ("BC" (Bray-Curtis), "Jaccard", "UniFrac" (unweighted), "GUniFrac" (generalized), "WUniFrac" (weighted), and "JS" (Jensen-Shannon divergence)). If we need to remove the effects of some covariates on beta diversity measures, the `mStat_calculate_adjusted_distance` function can be utilized. This adjustment, based on linear models and multidimensional scaling, removes sources of unwanted variation, ensuring that the identified microbial patterns are not confounded by these covariates. Similar to creating the alpha diversity object, rarefaction is highly recommended before calculating the beta diversity since these unweighted beta diversity measures are highly influenced by sequencing depth variation.

### pc.obj

`pc.obj`: For functions performing beta diversity analysis based on the principal coordinates (PC) of distance matrices, the `pc.obj` parameter accepts a data object containing the PCs of various distance matrices (list type, each element is a matrix with rows representing samples, columns representing PCs). The `mStat_calculate_PC` function can be used to generate the PC object. This function allows for the choice between "mds" (multidimensional scaling) and "nmds" (non-metric multidimensional scaling) for ordination methods. If no PC object is passed to `pc.obj`, `mStat_calculate_PC` function will be automatically invoked using the default "mds". For users who prefer more advanced ordination methods, such as t-SNE or UMAP, these can be computed using external tools and then formatted to fit the MicrobiomeStat data structure for compatibility with the MicrobiomeStat toolkit.

With these essential data objects, the MicrobiomeStat toolkit is equipped to handle a wide range of analyses, from diversity assessments to complex ordination techniques, providing users with comprehensive tools for microbiome data analysis.


# Building MicrobiomeStat from Matrix and Data.frame

Discover how to craft the MicrobiomeStat data object using matrices and data frames from your R environment or by importing data from external CSV files.

The basic MicrobiomeStat data object consists of the following components:

* **feature.tab (matrix)**: A matrix recording the measurements of detected features (like OTUs, ASVs, genes) with features as rows and samples as columns. Ensure row names are the names of the features, and column names match the samples.
* **meta.dat (data.frame)**: A data frame of the sample meta data, where rows correspond to samples, and columns denote annotations. Ensure the row names match the feature.tab columns. Tibbles are not permitted; use a standard R data frame.
* **feature.ann (matrix)**: An annotation matrix with features as rows and annotations as columns. Annotations are usually hierarchical such as the taxonomic annotations. Ensure row names match those in feature.tab.
* **tree (phylo, optional)**: Captures the evolutionary relationships among feautres. It's essential for specific beta-diversity calculations but isn't required for the majority of MicrobiomeStat analyses.
* **feature.agg.list (list, optional)**: Generated using the `mStat_aggregate_by_taxonomy` function, this list contains matrices of aggregated data based on the annotations specified in ”feature.ann", with each matrix's columns representing samples and rows representing the annotation level (e.g., Phylum, Genus).

Here is how to construct the MicrobiomeStat data object directly from matrix and data.frame:

### 1. Using Existing Data in R Environment

#### Starting from matrix and data.frame

Assuming we already have the count matrix and sample metadata:

```r
# Step 1: Create the sample names.
# We want 20 sample names, each prefixed with "S". We use the `paste0` function to concatenate "S" with the numbers 1 through 20.
samplenames <- paste0("S",1:20)

# Step 2: Create the feature names.
# We want 100 feature names, each prefixed with "OTU". We use the `paste0` function to concatenate "OTU" with the numbers 1 through 100.
featurenames <- paste0("OTU",1:100)

# Step 3: Create the Feature.tab matrix.
# We want a matrix with 100 rows and 20 columns, filled with random counts.
# We then set the row and column names of this matrix to the feature and sample names we created earlier.
Feature.tab <- matrix(sample(1:1000, 100*20, repl = TRUE),nrow=100,ncol=20)
rownames(Feature.tab) <- featurenames
colnames(Feature.tab) <- samplenames

# Step 4: Create the Meta.dat data frame.
# We want a data frame with two columns: "group" and "weight".
# The "group" column should have 10 "case"s followed by 10 "control"s.
# The "weight" column should have 20 random numbers from a normal distribution with mean 70 and standard deviation 5.
# We then set the row names of this data frame to the sample names we created earlier.
# Create the Meta.dat dataframe
Meta.dat <- data.frame(
  group = rep(c("control","case"), each=10),
  weight = rnorm(20,70,5)
)

# Convert the "group" column to a factor and set "control" as the reference level
Meta.dat$group <- relevel(as.factor(Meta.dat$group), ref="control")

rownames(Meta.dat) <- samplenames
```

#### Add Feature Annotation

To enrich the analysis, it's beneficial to add feature annotations. For this example, we add both taxonomic and functional classifications:

```r
# Step 1: Define the values for the "Kingdom" column. 
# We want 80 "Bacteria" and 20 "Archaea", so we use the `rep` function to repeat these values the desired number of times.
bacteria <- rep("Bacteria", 80)
archaea <- rep("Archaea", 20)
kingdom_values <- c(bacteria, archaea)

# Step 2: Define the values for the "Function" column. 
# We want a random selection from "Metabolism", "Signaling", and "Regulation", and we want 100 values in total.
# We use the `sample` function to randomly select these values, allowing for repeats (replace=TRUE).
function_values <- sample(c("Metabolism","Signaling","Regulation"), 100, replace=TRUE)

# Step 3: Combine the "Kingdom" and "Function" values into a single vector.
# We use the `c` function to concatenate these two vectors into one.
combined_values <- c(kingdom_values, function_values)

# Step 4: Get the number of rows from the `Feature.tab` data frame.
# We use the `nrow` function to get this number.
num_rows <- nrow(Feature.tab)

# Step 5: Get the row names from the `Feature.tab` data frame.
# We use the `rownames` function to get these names.
row_names <- rownames(Feature.tab)

# Step 6: Create the matrix.
# We use the `matrix` function to create the matrix, specifying the combined values, the number of rows, and the column and row names.
Feature.ann <- matrix(combined_values, nrow=num_rows, dimnames=list(row_names, c("Kingdom", "Function")))
```

#### Add Phylogenetic Tree (Optional)

If a phylogenetic tree is available, directly assign:

```r
tree <- ape::rtree(100) # generate random tree
```

#### Combine into MicrobiomeStat Object

Now, combine the components into a MicrobiomeStat object:

```r
MicrobiomeData <- list(
  feature.tab = Feature.tab,
  meta.dat = Meta.dat,
  feature.ann = Feature.ann,
  tree = tree
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F1cR8qVfRQNRyRFfZlPBb%2FScreenshot%202023-10-10%20at%2010.18.21.png?alt=media&amp;token=762478ed-608b-45f6-936e-5c78d7b60731" alt=""><figcaption><p>The image displays the structured breakdown of the <code>MicrobiomeStat</code> data object using R's <code>str</code> function. Additionally, the successful validation of the object with <code>mStat_validate_data(MicrobiomeData)</code> confirms its readiness for subsequent analyses.</p></figcaption></figure>

### 2. Using External CSV Data

To facilitate your understanding and to ease the process of setting up your data, we have provided sample CSV files that can be used as templates. By analyzing these sample files, you can structure your data similarly and ensure it's compatible with our tool.

For this demonstration, we'll import data from three external CSV files: `feature_tab.csv`, `meta_dat.csv`, and `feature_ann.csv`.

#### Download Sample Data Files

You can download these files to understand the expected format:

{% file src="/files/jDIKaqd1wg1x8e5QJ6dZ" %}

{% file src="/files/zuQ87AoKlVY5048hJjXv" %}

{% file src="/files/evxemydGIhA9B85rSYIT" %}

If you want to use your own data, download these example files, examine their structure, and modify your data accordingly to match this format.

#### Import Data from CSV

Once you have the desired CSV files, you can proceed to import the data:

```r
Feature.tab <- read.csv("feature_tab.csv", row.names = 1)
Meta.dat <- read.csv("meta_dat.csv", row.names = 1)
Feature.ann <- read.csv("feature_ann.csv", row.names = 1)
```

#### Combine into MicrobiomeStat Object

With the imported data, combine the components:

```r
MicrobiomeData <- list(
  feature.tab = as.matrix(Feature.tab),
  meta.dat = Meta.dat,
  feature.ann = as.matrix(Feature.ann)
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F6j68hYzCbG3agwsi7AXz%2FScreenshot%202023-10-10%20at%2010.28.16.png?alt=media&amp;token=d5d4c74c-8d84-4fff-b22b-f68c3dde5893" alt=""><figcaption><p>This visualization presents the structure of the imported <code>MicrobiomeStat</code> data object using R's <code>str</code> function, illustrating the organization of the components sourced from external CSV files.</p></figcaption></figure>

#### Add Phylogenetic Tree

If you have a phylogenetic tree that you would like to use, you can upload it:

```r
# Load the ape package
library(ape)

# Read the tree file
# Replace 'path_to_your_tree_file' with the actual path to your tree file.
# The tree file should be in Newick format.
tree <- read.tree('path_to_your_tree_file')

MicrobiomeData <- list(
  feature.tab = as.matrix(Feature.tab),
  meta.dat = Meta.dat,
  feature.ann = as.matrix(Feature.ann),
  tree = tree
)
```

With either the provided sample data or your own structured data, you now have a complete MicrobiomeStat data object ready for subsequent analysis and visualization.


# Converting Data from Phyloseq into MicrobiomeStat

Learn the process for converting Phyloseq data format into MicrobiomeStat data format.

The guide illustrates the procedure to convert a Phyloseq data object into a MicrobiomeStat data object.

### Requirement: Taxa as Rows in Phyloseq

Before converting your Phyloseq object to a MicrobiomeStat data object, it is crucial to ensure that the taxa are represented as rows in your Phyloseq object. This is a requirement for the conversion process to work correctly.

To check if your Phyloseq object has taxa as rows, you can use the `phyloseq::taxa_are_rows()` function:

```r
library(phyloseq)

data(GlobalPatterns)

# Check if taxa are rows in the Phyloseq object
phyloseq::taxa_are_rows(GlobalPatterns)
```

If the function returns `TRUE`, your Phyloseq object is ready for conversion. If it returns `FALSE`, you need to transpose your Phyloseq object to have taxa as rows before proceeding with the conversion.

If your Phyloseq object contains a phylogenetic tree, you also need to load the `phangorn` package for midpoint rooting:

```r
library(phangorn)
```

First, let's take a look at the original structure of our Phyloseq data:

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FjCY1h3HwrMrLN224JI5e%2FScreenshot%202023-10-10%20at%2010.51.53.png?alt=media&amp;token=c6ae1a78-c514-498a-95d2-38090bf8c6e5" alt=""><figcaption><p><strong>Figure 1</strong>: Structure of the original Phyloseq data object.</p></figcaption></figure>

Now, initiate the conversion:

```r
# Required package
library(microbiome)

# Load the dataset
data(peerj32)
peerj32.phy <- peerj32$phyloseq

# Convert the Phyloseq object to a MicrobiomeStat data object
data.obj <- mStat_convert_phyloseq_to_data_obj(peerj32.phy)
```

After the conversion, the Phyloseq object is transformed into a MicrobiomeStat data object. Let's examine the structure post-conversion:

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F8WglzwdwO9NW01YT7RUt%2FScreenshot%202023-10-10%20at%2010.52.44.png?alt=media&amp;token=15fae760-24f3-4542-9018-2095d0a0b500" alt=""><figcaption><p><strong>Figure 2</strong>: Structure of the MicrobiomeStat data object after converting from Phyloseq.</p></figcaption></figure>

### Caution Regarding Factor Levels

During the conversion, there might be changes in the levels of factors in the metadata. This can potentially alter the order or even result in missing levels.

**Recommendation:** It's important to verify the factors after conversion to ensure data consistency. If there are any changes, the factor levels should be reset:

```r
# Example: Adjusting the 'sex' factor levels
data.obj$meta.dat$sex <- factor(as.factor(data.obj$meta.dat$sex), levels = c("male", "female"))
```

Reorder the factor levels of the `sex` column。

The function `mStat_convert_phyloseq_to_data_obj` returns a MicrobiomeStat data object, which includes:

* **feature.tab**: A matrix representing the feature table (OTU table). Rows with a sum of zero are excluded, retaining only the features present in the samples.
* **meta.dat**: A data frame containing the sample data.
* **feature.ann**: A matrix of the feature annotation table (taxonomy table). Only the rows corresponding to the feature table are included.
* **tree**: A rooted phylogenetic tree. If the tree is not rooted, it will be rooted using the midpoint method. Tips not present in the OTU table are pruned.

After converting the Phyloseq object to the MicrobiomeStat format, the data is now compatible with MicrobiomeStat's analysis tools.


# Importing Data from QIIME2 into MicrobiomeStat

This guide provides a step-by-step method for importing QIIME2 data  into the MicrobiomeStat data object.

This guide details the process to import QIIME2 data into MicrobiomeStat's required data object.

The provided files represent essential QIIME2 artifacts and metadata required for microbiome data analysis:

{% file src="/files/kWruDwjYcJHHVq3kUHtC" %}
This artifact contains the feature table, which is a summary of the observed microbial features (e.g., OTUs, ASVs) across different samples. QIIME2 users typically recognize it as their primary count or abundance matrix.
{% endfile %}

{% file src="/files/WWk7dsImPbSK5XToIFv6" %}
This artifact holds taxonomic assignments for each microbial feature, allowing users to determine the classification of observed features at various taxonomic ranks (e.g., kingdom, phylum, class).
{% endfile %}

{% file src="/files/adgOjtz3TebDDzvSWgjX" %}
A tab-separated values (TSV) file detailing the metadata associated with each sample. Metadata might include sample conditions, treatments, or any other annotations pertinent to the study.
{% endfile %}

{% file src="/files/zPDnEziOpS5Xog9hKdiD" %}
A phylogenetic tree artifact representing the evolutionary relationships between microbial features. This tree is crucial for various phylogenetic diversity metrics and analyses within QIIME2.
{% endfile %}

```r
# Define paths to your QIIME2 files
# NOTE: Update these paths to point to the location of the files on your computer.
otuqza_file <- "path_to_your_directory/table.qza"
taxaqza_file <- "path_to_your_directory/taxonomy.qza"
sample_file <- "path_to_your_directory/sample-metadata.tsv"
treeqza_file <- "path_to_your_directory/tree.qza"

# Import QIIME2 data into a MicrobiomeStat data object
data.obj <- mStat_import_qiime2_as_data_obj(
    otu_qza = otuqza_file, 
    taxa_qza = taxaqza_file,
    sam_tab = sample_file, 
    tree_qza = treeqza_file
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FfVSBbILUHt5jaffMdgiD%2FScreenshot%202023-10-10%20at%2011.35.49.png?alt=media&amp;token=06eea4c9-90a0-493c-89f1-122ac1030d00" alt=""><figcaption><p>This output showcases the data paths and structure of the converted <code>data_obj</code> from QIIME2 to MicrobiomeStat format. Displayed paths indicate the location of QIIME2 files on a local machine. The <code>str(data_obj)</code> function in R reveals the organized structure of the <code>data_obj</code> list, detailing its various components such as <code>feature.tab</code>, <code>meta.dat</code>, <code>feature.ann</code>, and the phylogenetic <code>tree</code>. Each component houses relevant microbiome data ready for analysis using MicrobiomeStat.</p></figcaption></figure>

The function `mStat_import_qiime2_as_data_obj` efficiently transforms QIIME2 datasets into the data format required by MicrobiomeStat. Here's a breakdown of the input parameters:

* **otu\_qza**: This file represents your feature table, containing the abundance data of microbial features across samples.
* **taxa\_qza** (Optional): This is the taxonomy assignment table which provides taxonomic classifications for the microbial features.
* **sam\_tab** (Optional): The sample metadata table offers details about the samples.
* **tree\_qza** (Optional): A phylogenetic tree depicting the evolutionary relationships of the microbial features.

Ensure that you have the correct file paths and all required dependencies installed before initiating the conversion process.


# Importing Data from BIOM into MicrobiomeStat

Guide to importing BIOM data into MicrobiomeStat data object.

Follow the instructions below to convert your BIOM data into a format suitable for MicrobiomeStat.

{% file src="/files/NPcN1gJ5lkm1STQUF9Gk" %}
BIOM file containing biological observation matrix and associated metadata.
{% endfile %}

{% file src="/files/7l4CyPkzQtmyHzbdXoRa" %}
Phylogenetic tree file representing evolutionary relationships among observed species.
{% endfile %}

{% code fullWidth="true" %}

```r
# Example code

# Specify the path to your BIOM data. Replace the placeholder with the correct path on your system.
rich_dense_biom <- "rich_dense_otu_table.biom"
# Reminder: Ensure that you replace the above path with the actual location of your BIOM file.

# Specify the path to your phylogenetic tree. Again, replace the placeholder with the correct path on your system.
treefilename <- "biom-tree.phy"
# Reminder: Ensure that you replace the above path with the actual location of your phylogenetic tree file.

# Convert the BIOM data and associated phylogenetic tree (if provided) 
# into a format suitable for MicrobiomeStat using the mStat_import_biom_as_data_obj function.
data.obj <- mStat_import_biom_as_data_obj(BIOMfilename = rich_dense_biom, treefilename = treefilename)

# The resulting 'data.obj' is now a MicrobiomeStat data object that you can use for further analyses.
```

{% endcode %}

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FmzkP3pv2yLJRx47JhrmE%2FScreenshot%202023-10-10%20at%2015.18.52.png?alt=media&amp;token=6fa9363f-18dd-4e2a-9004-ad93a063ce9e" alt=""><figcaption><p>Structure of the MicrobiomeStat data object created from BIOM data.</p></figcaption></figure>

By employing the `mStat_import_biom_as_data_obj` function, the BIOM data, along with optional phylogenetic tree data, can be integrated into the MicrobiomeStat framework. Here's a brief overview of the function's parameters:

* **BIOMfilename**: The file path to your BIOM data.
* **treefilename** (Optional): The file path to your phylogenetic tree.
* **parseFunction** (Optional): A user-defined function to interpret the taxonomy from the BIOM file metadata.


# Converting SummarizedExperiment into MicrobiomeStat

A step-by-step guide on converting SummarizedExperiment data format for compatibility with MicrobiomeStat.

The Bioconductor package `SummarizedExperiment` provides a convenient representation of experimental data. MicrobiomeStat provides a straightforward method for converting SummarizedExperiment objects.

```r
# Check if the 'airway' package is installed
if (!requireNamespace("airway", quietly = TRUE)) {
  # If not installed, install 'airway'
  BiocManager::install("airway")
}

# Load necessary libraries
library(airway)

# Use the provided 'airway' dataset as an example
data(airway)

# Convert the SummarizedExperiment object 'airway' into a MicrobiomeStat data object
airway_obj <- mStat_convert_SummarizedExperiment_to_data_obj(airway)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FUHduLvJbXp19l6sdUsmO%2FScreenshot%202023-10-10%20at%2011.50.07.png?alt=media&amp;token=cdca8ff8-dcf2-4209-b004-472775f1b31d" alt=""><figcaption><p>Structure of the <code>airway_obj</code> data object, converted from the <code>airway</code> SummarizedExperiment dataset. The visualization showcases the primary components of the MicrobiomeStat data object, detailing its matrices and data frames derived from the original dataset.</p></figcaption></figure>

The function `mStat_convert_SummarizedExperiment_to_data_obj` requires:

* **se.obj**: A SummarizedExperiment object for conversion.

Post conversion, the data is organized into a **MicrobiomeStat data object** with the following components:

* **feature.tab**: A matrix derived from assay data.
* **feature.ann**: A matrix consisting of rowData or feature annotations. Only the features present in the assay data are retained.
* **meta.dat**: A data frame containing colData or sample metadata.

For efficient analysis, features with an aggregate count of zero in the assay data are excluded during the conversion process.


# Converting DGEList Data into MicrobiomeStat

Learn the steps to  convert DGEList data format into MicrobiomeStat data format.

This guide will assist you in converting DGEList data format into MicrobiomeStat format.

Before we proceed with the conversion, let's examine the original structure of our DGEList data:

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fhqopy7ieuODsbtrbr05n%2FScreenshot%202023-10-10%20at%2014.45.38.png?alt=media&amp;token=e71dc761-bf02-4f22-aa94-ed94d5f6fb06" alt=""><figcaption><p>Original structure of the DGEList data.</p></figcaption></figure>

Now, follow the steps below to convert the DGEList data:

```r
# Load necessary packages
library(airway)
library(DESeq2)
library(edgeR)

# Load dataset
data("airway")
dds <- DESeqDataSet(airway, design = ~ cell + dex)
dge <- DGEList(counts = counts(dds), group = dds$dex)

# Convert DGEList to MicrobiomeStat data object
data.obj <- mStat_convert_DGEList_to_data_obj(dge)
```

After conversion, let's take a look at the transformed data structure:

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FeBeXOXf7TdFPVsZ57F58%2FScreenshot%202023-10-10%20at%2014.46.16.png?alt=media&amp;token=42839408-5b08-41d9-a4ad-728f39d21678" alt=""><figcaption><p>Structure of the MicrobiomeStat data object after importing DGEList data.</p></figcaption></figure>

By using the `mStat_convert_DGEList_to_data_obj` function, you can effectively convert:

* **dge.obj**: Your existing DGEList object.

The resultant **MicrobiomeStat data object** includes:

* **feature.tab**: A matrix populated with counts data.
* **meta.dat**: A data frame detailing the sample information.

As part of the conversion process, features with a sum of zero from the counts data are filtered out to maintain data relevance.


# Converting DESeqDataSet into MicrobiomeStat

A guide on converting DESeqDataSet data format into the MicrobiomeStat format.

This guide provides the recipe for converting the DESeqDataSet format to MicrobiomeStat format.

To begin, let's inspect the initial structure of our DESeqDataSet data:

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FISXMNrOXaaaU8HklmL61%2FScreenshot%202023-10-10%20at%2014.56.23.png?alt=media&amp;token=05a258ec-e84e-4b90-8787-961a5eae6300" alt=""><figcaption><p>Initial structure of the DESeqDataSet data.</p></figcaption></figure>

Proceed with the steps below to conduct the conversion:

```r
# Example Code (replace with your real dataset!)
# Load necessary packages
 library(airway)
 library(DESeq2)

# Load dataset
 data("airway")
 dds <- DESeqDataSet(airway, design = ~ cell + dex)

# Convert DESeqDataSet to MicrobiomeStat data object
 data.obj <- mStat_convert_DESeqDataSet_to_data_obj(dds)
```

Upon conversion, the data structure will be transformed as follows:

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F03CpHx1bvsgnoYBzxWMB%2FScreenshot%202023-10-10%20at%2014.57.15.png?alt=media&amp;token=3b931785-6097-4592-9338-988aa5be5958" alt=""><figcaption><p>Structure of the MicrobiomeStat data object after importing DESeqDataSet data.</p></figcaption></figure>

The `mStat_convert_DESeqDataSet_to_data_obj` function facilitates the transition:

* **dds.obj**: The DESeqDataSet object slated for conversion.

After the conversion, the **MicrobiomeStat data object** consists of:

* **feature.tab**: A matrix containing count data.
* **meta.dat**: A data frame detailing the sample information.
* **feature.ann**: A matrix presenting feature annotations.

For data integrity and relevance, the function ensures only features with a sum > 0 from the counts data are retained.


# Importing Data from DADA2 into MicrobiomeStat

Learn the steps to import data from DADA2 into MicrobiomeStat's data structure.

This guide will walk you through the steps required to import data from DADA2 into MicrobiomeStat.

### Download Necessary Files

{% file src="/files/oN0J7Ai73oTGK7XtlpS9" %}
Sequence table (`seq_tab`) - This table from DADA2 contains sample-specific sequence abundance data. Rows represent samples, and columns correspond to sequences.
{% endfile %}

{% file src="/files/bu9u6RmhiYzceAryDteE" %}
Taxonomy assignment table (`tax_tab`) - This table provides taxonomic classifications for sequences, helping users understand the biological context of the identified sequences.
{% endfile %}

{% file src="/files/an8U8diBkN7qSSUqNKK4" %}
Sample metadata table (\`sam\_tab\`) - This table offers detailed metadata for each sample, enriching the context and facilitating more in-depth analyses.
{% endfile %}

### Code to Import Data

```r
# This function requires the `Biostrings` and `yaml` packages.
 
# If you encounter issues when running the example code, please ensure that you have installed and loaded these packages.
library(Biostrings)
library(yaml)
# Read the sequence table from the downloaded RDS file
seq_tab <- readRDS("path_to_your_downloaded_folder/dada2_seqtab.rds")

# Read the taxonomy table from the downloaded RDS file
tax_tab <- readRDS("path_to_your_downloaded_folder/dada2_taxtab.rds")

# Read the sample metadata from the downloaded txt file
sam_tab <- read.table(
  "path_to_your_downloaded_folder/dada2_samdata.txt",
  sep = "\t",
  header = TRUE,
  row.names = 1
)

# Convert DADA2 data into a MicrobiomeStat data object
# phy_tree is optional: provide a phylogenetic tree (phylo object) if available
data_obj <- mStat_import_dada2_as_data_obj(
  seq_tab = seq_tab,
  tax_tab = tax_tab,
  sam_tab = sam_tab,
  phy_tree = NULL  # Set to a phylo object if you have a tree from DADA2
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F0ts1LGxVUUELACqr1cKU%2FScreenshot%202023-10-10%20at%2014.34.05.png?alt=media&amp;token=ae8b1b36-f7d1-4041-ae7b-dfeb0041480e" alt=""><figcaption><p>Structure of the MicrobiomeStat data object after importing DADA2 data. This visualization highlights the different components of the data object, including the feature table, taxonomy table, and sample metadata, facilitating a comprehensive understanding of the imported dataset.</p></figcaption></figure>

{% hint style="info" %}
Note: Ensure to replace `"path_to_your_downloaded_folder"` with the actual path where you've saved the downloaded files.
{% endhint %}


# Importing Data from Mothur into MicrobiomeStat

Steps for importing Mothur-generated data into the MicrobiomeStat framework.

This guide details the procedure to seamlessly import data generated by Mothur into the MicrobiomeStat environment.

{% file src="/files/9YQn8MwxPCISZVLhrk9q" %}
This compressed file contains the list file from Mothur, which typically encompasses OTU clustering information for various thresholds.
{% endfile %}

{% file src="/files/o0s4QSmxYOiQxGed8qZv" %}
The shared file provides a breakdown of the abundance of OTUs in each sample.
{% endfile %}

{% file src="/files/NoYO3XLiySJjcvqghlvL" %}
Group file indicating the sample assignment for each sequence.
{% endfile %}

{% file src="/files/yzitMiRNqCcroBr4dCWY" %}
Phylogenetic tree file representing the evolutionary relationships among OTUs.
{% endfile %}

```r
# Make sure the plyr package is installed
if (!require(plyr)) {
    install.packages("plyr")
    library(plyr)
} else {
    library(plyr)
}

# Specify the paths to your Mothur files
path_to_list_file <- "/path_to_your_files/esophagus.fn.list.gz"
path_to_group_file <- "/path_to_your_files/esophagus.good.groups.gz"
path_to_tree_file <- "/path_to_your_files/esophagus.tree.gz"
path_to_shared_file <- "/path_to_your_files/esophagus.fn.shared.gz"

# Import Mothur data into a MicrobiomeStat data object
data_obj <- mStat_import_mothur_as_data_obj(
    mothur_list_file = path_to_list_file,
    mothur_group_file = path_to_group_file,
    mothur_tree_file = path_to_tree_file,
    mothur_shared_file = path_to_shared_file
)

# After constructing data_obj, detach the plyr package to avoid conflicts with dplyr
if ("package:plyr" %in% search()) {
    detach("package:plyr", unload = TRUE)
    message("Detached plyr package to avoid potential conflicts with dplyr.")
}
```

The `mStat_import_mothur_as_data_obj` function facilitates the conversion of the Mothur dataset to the basic MicrobiomeStat data objects. Here are the key components:

* **mothur\_list\_file** (Optional): Mothur-generated list file.
* **mothur\_group\_file** (Optional): Group designation file from Mothur.
* **mothur\_tree\_file** (Optional): Phylogenetic tree representation.
* **mothur\_shared\_file** (Optional): OTU Abundance data across samples.
* **mothur\_constaxonomy\_file** (Optional): Classification of OTUs at various taxonomic levels.
* **parseFunction** (Optional): Custom function for taxonomy parsing, with 'parse\_taxonomy\_default' as an available option.

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FdBFPDxfjAnxcNaRMD45J%2FScreenshot%202023-10-10%20at%2016.27.19.png?alt=media&amp;token=f214d24b-d667-41a3-b5ba-ac3c4f536d44" alt=""><figcaption><p>Structural overview of the `data_obj` generated after importing Mothur datasets into MicrobiomeStat.</p></figcaption></figure>


# Converting MRExperiment into MicrobiomeStat

If your data is stored in a `MRExperiment` object from the **metagenomeSeq** package, the `mStat_convert_MRExperiment_to_data_obj()` function provides a direct conversion to the MicrobiomeStat data format.

## Function Overview

```r
mStat_convert_MRExperiment_to_data_obj(mr.obj)
```

**Parameters:**

* `mr.obj`: A `MRExperiment` object to be converted.

**Returns:** A MicrobiomeStat data object (a list) containing:

* `feature.tab`: A matrix of expression data (features as rows, samples as columns)
* `meta.dat`: A data frame of sample metadata
* `feature.ann`: A matrix of feature annotations (if available)

## Example Usage

```r
library(metagenomeSeq)

# Load example data from metagenomeSeq
data(mouseData)

# Convert to MicrobiomeStat format
data.obj <- mStat_convert_MRExperiment_to_data_obj(mouseData)

# Verify the conversion
print(dim(data.obj$feature.tab))
print(head(data.obj$meta.dat))
```

## Notes

* Only features with a sum > 0 across all samples are retained during conversion.
* The function requires the `metagenomeSeq` package to be installed.
* After conversion, validate the data object with `mStat_validate_data(data.obj)`.


# Converting MultiAssayExperiment into MicrobiomeStat

If your data is stored in a `MultiAssayExperiment` object (commonly used in multi-omics studies), the `mStat_convert_MultiAssayExperiment_to_data_obj()` function converts a specified experiment to the MicrobiomeStat data format.

## Function Overview

```r
mStat_convert_MultiAssayExperiment_to_data_obj(mae.obj, experiment_name = NULL)
```

**Parameters:**

* `mae.obj`: A `MultiAssayExperiment` object to be converted.
* `experiment_name`: A string specifying which experiment in the `MultiAssayExperiment` to convert. Default is the first experiment.

**Returns:** A MicrobiomeStat data object (a list) containing:

* `feature.tab`: A matrix of assay data (features as rows, samples as columns)
* `meta.dat`: A data frame of sample metadata (from colData)

## Example Usage

```r
library(MultiAssayExperiment)

# Assuming 'mae' is your MultiAssayExperiment object
# Convert the "16S" experiment to MicrobiomeStat format
data.obj <- mStat_convert_MultiAssayExperiment_to_data_obj(mae, "16S")

# Or convert the first experiment (default)
data.obj <- mStat_convert_MultiAssayExperiment_to_data_obj(mae)

# Verify the conversion
print(dim(data.obj$feature.tab))
print(head(data.obj$meta.dat))
```

## Notes

* Only features with a sum > 0 across all samples are retained during conversion.
* The function requires the `MultiAssayExperiment` package to be installed.
* After conversion, validate the data object with `mStat_validate_data(data.obj)`.


# Introduction

Cross-sectional microbiome studies, which randomly sample the microbiome from a study population at a single time point, have been widely used in microbiome research due to its simplicity and easy sample collection. Besides cross-sectional design, case-control study designs are also prevalent in microbiome research. Both designs will generate microbiome data with independence among samples and can be analyzed in a similar way by treating the microbiome measurement as the outcome. MicrobiomeStat provides full support of analyzing data from cross-sectional and case-control studies. We illustrate the use of MicrobiomeStat in analyzing these types of data using the `peerj32` dataset, which was originated from a study that probed the relationship between human intestinal bacteria and lipid metabolism in response to a probiotic intervention.

> Lahti L, Salonen A, Kekkonen RA, Salojärvi J, Jalanka-Tuovinen J, Palva A, Orešič M, de Vos WM. Associations between the human intestinal microbiota, Lactobacillus rhamnosus GG and serum lipids indicated by integrated analysis of high-throughput profiling data. PeerJ. 2013 Feb 26;1:e32. doi: 10.7717/peerj.32. PMID: 23638368; PMCID: PMC3628737.

**Exploring the PeerJ32 Dataset**

The `peerj32` was originally in the `phyloseq` format. We have converted it to our MicrobiomeStat format using the `mStat_convert_phyloseq_to_data_obj` function. For an in-depth look at the conversion process, please refer to this section in our Gitbook.

{% content-ref url="/pages/ncvk6iQalI4IDdmAzizj" %}
[Converting Data from Phyloseq into MicrobiomeStat](/setting-up-microbiomestat-installation-and-data-preparation/laying-the-foundation-creating-the-microbiomestat-data-object/navigating-data-from-phyloseq-into-microbiomestat)
{% endcontent-ref %}

The major variable of interest in this study is the treatment group: LGG Probiotic or Placebo. Additionally, the dataset includes other variables such as the sex of participants, which can serve both as a stratifying factor in visualization and as a covariate in statistical testing.

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FEX0JmFgi93PqcJhnFC6b%2FScreenshot%202023-10-10%20at%2018.31.52.png?alt=media&amp;token=da662a47-7cfc-4075-b6c2-54ab43a48460" alt=""><figcaption><p>Sample metadata overview from the <code>peerj32</code> dataset. This table provides details about each sample, including the subject ID, cons, time point, sex of the participant, and the treatment group assignment (Placebo or LGG).</p></figcaption></figure>

The dataset provides taxonomic classifications at three ranks: Phylum, Family, and Genus. The phylogenetic tree is not provided in this dataset.

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F9lb7zl5I5Pu4068fRiYb%2FScreenshot%202023-10-10%20at%2018.32.30.png?alt=media&amp;token=78cd9791-10c9-49b7-8f1f-31fee944ea9b" alt=""><figcaption><p>Taxonomic annotations for the microbial features in the <code>peerj32</code> dataset. Each row represents a microbial feature, classified at the Phylum, Family, and Genus levels.</p></figcaption></figure>

We will use `peerj32` dataset to showcase the utility of MicrobiomeStat in analyzing cross-sectional/case-control data. For users wishing to apply our tutorial to their own datasets, please see the following guide:

{% content-ref url="/pages/WK9NC4ukGZbAvQGuCKUR" %}
[Creating the MicrobiomeStat Data Object](/setting-up-microbiomestat-installation-and-data-preparation/laying-the-foundation-creating-the-microbiomestat-data-object)
{% endcontent-ref %}

This section explains how to convert your data into the MicrobiomeStat format, enabling you to use the MicrobiomeStat toolkit for your research.


# Alpha Diversity Analysis

Alpha diversity indices offer insights into the species richness and evenness within individual microbiome samples. MicrobiomeStat supports a variety of indices including "shannon", "simpson", "observed\_species", "chao1", "ace", and "pielou". These diversity measures vary by assigning different weights to the abundant species. The alpha diversity measures can be conveniently calculated using `mStat_calculate_alpha_diversity` function. Note that rarefaction is highly recommended before calculating the diversity measures. `mStat_rarefy_data` can be used for this purpose.

For those functions performing alpha diversity analysis, they all include an `alpha.obj` parameter, which accepts a matrix of alpha diversity measures (rows - samples, columns - alpha diversity measures), either created by the user or by calling `mStat_calculate_alpha_diversity`. If `alpha.obj` parameter is NULL, `mStat_calculate_alpha_diversity` will be called autonomously. To speed up computation, we recommend calling `mStat_calculate_alpha_diversity` once and store the alpha diversity measures in a data object, which can be used later repeatedly.

Next, we will illustrate how to perform alpha diversity analysis for cross-sectional data (or case-control data) using peerj32.obj. The first task is to test the association between alpha diversity and a variable of interest while adjusting for other variables (such as confounders and independent predictors). We achieve this using `generate_alpha_test_single`, which is based on multiple linear models.

```r
generate_alpha_test_single(
  data.obj = peerj32.obj,
  alpha.obj = NULL, 
  alpha.name = c("shannon", "observed_species"),
  depth = NULL,
  time.var = "time",
  t.level = "2",
  group.var = "group",
  adj.vars = "sex")
```

If one wishes to focus on a specific time point, `time.var` (name of the time variable) and `t.level`(name of the specific time point) can be specified here. If not specified, the function uses all samples. Here, we use the time point "2". In this example, we did not provide a pre-caluclated alpha object (`alpha.obj = NULL`). Thus, `mStat_calculate_alpha_diversity` is automatically called after the data are rarefied to the minimum depth (`depth=NULL`). For each alpha diversity measure in `alpha.name`, a linear model is fit, with `group.var` as the primary variable of interest, with covariates to be adjusted specified via `adj.vars`. The function's output consists of linear model output that contains coefficients, standard errors, test statistics, and p-values. In scenarios where `group.var` has multiple categories, ANOVA will be employed to test the global null hypothesis of no difference in means between all the groups.

#### Shannon Index Results

<table><thead><tr><th>Term</th><th width="111">Estimate</th><th width="118">Std.Error</th><th width="102">Statistic</th><th>P.Value</th></tr></thead><tbody><tr><td>(Intercept)</td><td>3.60</td><td>0.0386</td><td>93.2</td><td>9.47e-27</td></tr><tr><td>sexmale</td><td>-0.0633</td><td>0.0451</td><td>-1.40</td><td>1.77e-1</td></tr><tr><td>groupPlacebo</td><td>0.0415</td><td>0.0437</td><td>0.950</td><td>3.54e-1</td></tr></tbody></table>

#### Observed Species Results

<table><thead><tr><th>Term</th><th width="81">Estimate</th><th width="122">Std.Error</th><th width="110">Statistic</th><th>P.Value</th></tr></thead><tbody><tr><td>(Intercept)</td><td>100.</td><td>3.72</td><td>26.9</td><td>1.36e-16</td></tr><tr><td>sexmale</td><td>2.29</td><td>4.35</td><td>0.528</td><td>6.04e-1</td></tr><tr><td>groupPlacebo</td><td>1.99</td><td>4.21</td><td>0.473</td><td>6.42e-1</td></tr></tbody></table>

The visualization of alpha diversity can be performed using `generate_alpha_boxplot_single` function. First, plot all observations and ignore the `time.var` and `strata.var`.

```r
generate_alpha_boxplot_single(
  data.obj = peerj32.obj,
  alpha.obj = NULL,
  alpha.name = c("shannon"),
  depth = NULL,
  time.var = NULL,
  t.level = NULL,
  group.var = "group",
  strata.var = NULL,
  base.size = 16,
  theme.choice = "bw",
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FHQMddbm23xtizMJkwDcz%2FScreenshot%202023-10-10%20at%2019.16.07.png?alt=media&amp;token=b56ec406-5a67-40ff-bd9a-dbb36954d40f" alt=""><figcaption></figcaption></figure>

Next, we will plot the particular time point (time point 2 in this example) by setting `t.level = '2'`.

```r
generate_alpha_boxplot_single(
  data.obj = peerj32.obj,
  alpha.obj = NULL,
  alpha.name = c("shannon"),
  depth = NULL,
  time.var = "time",
  t.level = "2",
  group.var = "group",
  strata.var = NULL,
  base.size = 16,
  theme.choice = "bw",
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FHKrdzJIj8UncdQkm86Es%2FScreenshot%202023-10-10%20at%2019.17.06.png?alt=media&amp;token=b5b49f07-3f59-4831-9118-29a09defe094" alt=""><figcaption></figcaption></figure>

For a detailed inspection, we can further stratify the analysis based on sex by specifying `strata.var = 'sex'`.

```r
generate_alpha_boxplot_single(
  data.obj = peerj32.obj,
  alpha.obj = NULL,
  alpha.name = c("shannon"),
  depth = NULL,
  time.var = "time",
  t.level = "2",
  group.var = "group",
  strata.var = "sex",
  base.size = 16,
  theme.choice = "bw",
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FHDOL3P3gsUPWuG8mb6Lb%2FScreenshot%202023-10-10%20at%2019.18.43.png?alt=media&amp;token=9adee92d-bc22-4c60-bb3e-7d57c7f90be5" alt=""><figcaption></figcaption></figure>


# Beta Diversity Analysis

Beta diversity analysis is instrumental in revealing the difference in microbial community composition between samples, and attributing the differences to a specific covariate/covariates. For those beta diversity-based functions, they all have a `dist.obj` parameter, which accepts a list of distance matrices (beta diversity is expressed in the form of pairwise distances). If the parameter is not specified, `mStat_calculate_beta_diversity` after rarefaction (`mStat_rarefy_data`) will be automatically called to calculate various distance matrices. MicrobiomeStat supports a variety of beta diversity measures, including "BC" (Bray-Curtis), "Jaccard", "UniFrac" (unweighted), "GUniFrac" (generalized), "WUniFrac" (weighted), and "JS" (Jensen-Shannon divergence). The users can also create a list of their own distance matrices of choice and pass it to `dist.obj`. We recommend the user to pre-calculate distance matrices once in the analysis, store it in a data object and then use it repeatedly.

In some applications (e.g. ordination), the users may want to remove the covariate effects from the distance matrices. This can be achieved by using `mStat_calculate_adjusted_distance` function based on the reference below.

> Shi, Y., Zhang, L., Do, K. A., Peterson, C. B., & Jenq, R. R. (2020). aPCoA: covariate adjusted principal coordinates analysis. Bioinformatics, 36(13), 4099-4101. PMID: 32339223 PMCID: PMC7332564.

This process ensures the extracted microbial patterns are not confounded by the specified covariates, thus presenting a more accurate representation of the microbial community structures.

Based on the distance matrices, we can also extract their first several principal coordinates (PCs), which capture the main variation in the data. PCs can be calculated by calling `mStat_calculate_PC` function. Users can select between "mds" and "nmds" as their ordination method (default is "mds" method). Users favoring advanced ordination techniques like t-SNE or UMAP can employ external tools to compute the PCs. For those PC-based functions, they all have a `pc.obj` parameter, which accepts a list of PC matrices based on a variety of beta diversity measures. If the parameter is not specified, `mStat_calculate_PC` will be called automatically. We recommend the user to create the list once in the analysis and use it repeatedly.

We will first use beta diversity-based visualizations to explore the relationship between the microbial community and variables of interest. The `generate_beta_ordination_single` function performs this task.

```r
library(aplot)
generate_beta_ordination_single(
  data.obj = peerj32.obj,
  dist.obj = NULL,
  pc.obj = NULL,
  time.var = NULL, # Variable representing time points
  t.level = NULL, # Specific time level for subset (if subset desired)
  group.var = "group",
  strata.var = NULL,
  dist.name = c("BC","Jaccard"),
  base.size = 20,
  theme.choice = "bw",
  custom.theme = NULL,
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FH9s1c3n533k2yi6F2B0F%2FScreenshot%202023-10-10%20at%2019.54.22.png?alt=media&amp;token=948d3795-7e7d-442f-a7fd-f398895f967a" alt=""><figcaption></figcaption></figure>

In the example above, we did not specifiy the specific time point, though the function has the flexibility to visualize a specific time point by using `time.var` and `t.level`. After the visualization, we can conduct more rigorous statistical testing and calculate p-values. To rigorously test the association between the microbial community and a covariate of interest while adjusting for other covariates, we can use `generate_beta_test_single`, which is based on PERMANOVA using distance matrices.

```r
generate_beta_test_single(
  data.obj = peerj32.obj,
  dist.obj = NULL,
  time.var = "time",
  t.level = "2",
  group.var = "group", 
  adj.vars = "sex",
  dist.name = c('BC', 'Jaccard') 
)
```

In this example, we test the microbiome association with the "group" variable, adjusting for the "sex" variable, at the time point "2". We use both the "BC" and "Jaccard" distance measures. The function will output the R2 (percent variation explained) and association p-values for each beta diversity measure. To be noted, the association statistics for "sex" in the table is not adjusted for the "group" effect.

#### PERMANOVA results

<table><thead><tr><th width="121">Distance</th><th>Variable</th><th width="60">DF</th><th>Sum.Sq</th><th width="82">Mean.Sq</th><th>F.Statistic</th><th>R.Squared</th><th>P.Value</th></tr></thead><tbody><tr><td>BC</td><td>sex</td><td>1</td><td>0.043</td><td>0.043</td><td>0.644</td><td>0.032</td><td>0.786</td></tr><tr><td>BC</td><td>group</td><td>1</td><td>0.042</td><td>0.042</td><td>0.621</td><td>0.031</td><td>0.782</td></tr><tr><td>BC</td><td>Residuals</td><td>19</td><td>1.28</td><td>0.067</td><td>NA</td><td>0.938</td><td>NA</td></tr><tr><td>BC</td><td>Total</td><td>21</td><td>1.36</td><td>NA</td><td>NA</td><td>1</td><td>NA</td></tr><tr><td>Jaccard</td><td>sex</td><td>1</td><td>0.099</td><td>0.099</td><td>0.707</td><td>0.035</td><td>0.827</td></tr><tr><td>Jaccard</td><td>group</td><td>1</td><td>0.094</td><td>0.094</td><td>0.668</td><td>0.033</td><td>0.827</td></tr><tr><td>Jaccard</td><td>Residuals</td><td>19</td><td>2.67</td><td>0.14</td><td>NA</td><td>0.933</td><td>NA</td></tr><tr><td>Jaccard</td><td>Total</td><td>21</td><td>2.86</td><td>NA</td><td>NA</td><td>1</td><td>NA</td></tr></tbody></table>

The table above provides the detailed outcome of the PERMANOVA analysis, including metrics such as sum of squares, mean squares, and p-values.

#### Omnibus test results

| Term  | BC    | Jaccard | Omnibus |
| ----- | ----- | ------- | ------- |
| sex   | 0.791 | 0.819   | 0.808   |
| group | 0.794 | 0.859   | 0.817   |

It is also noteworthy that in practical scenarios, the nature of microbiome change is usually unknown before the analysis. As each distance measure excels at detecting a specific type of change, combining several representative distance measures may improve statistical power. Howver, conducting separate tests for each distance measure requires multiple testing correction and the simple Bonferroni correction may be too stringent due to the correlations among the distance measures. An omnibus test (reference below), which takes the minimum of the p-values as a new test statistic and uses permutation to assess significance, is usually more powerful than Bonferroni correction. In the result, we thus also provide the omnibus test p-value by combining the association evidence provided by different distance measures.

> Chen J, Bittinger K, Charlson ES, Hoffmann C, Lewis J, Wu GD, Collman RG, Bushman FD, Li H. Associating microbiome composition with environmental covariates using generalized UniFrac distances. Bioinformatics. 2012 Aug 15;28(16):2106-13. doi: 10.1093/bioinformatics/bts342. Epub 2012 Jun 17. PMID: 22711789; PMCID: PMC3413390.

In the PCoA plot, we can also stratify on a specific variable, such as "sex", and add the PERMANOVA p-value to highlight the statistical significance:

```r
library(MicrobiomeStat)
data(peerj32.obj)
p <- generate_beta_ordination_single(
  data.obj = peerj32.obj,
  dist.obj = NULL,
  pc.obj = NULL,
  time.var = "time",
  t.level = "2",
  group.var = "group",
  strata.var = "sex",
  adj.vars = "sex",
  dist.name = c("BC"),
  base.size = 20,
  theme.choice = "bw",
  custom.theme = NULL,
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5
)

# Add a p-value annotation to the plot. The p-value is calculated from a PERMANOVA test.
p <- p + annotate("text", x = 0.3, y = 0.8, 
  label = paste("italic(p) == ", 
  format(pvalue, digits = 2)), 
  parse = TRUE, 
  size = 5)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F3A5pirdQAjidkaD5EQgq%2FScreenshot%202023-10-16%20at%2018.48.19.png?alt=media&amp;token=ffef1eb9-9c18-4445-aca3-d5a7e9b3d31d" alt=""><figcaption></figcaption></figure>


# Feature-level Analysis

A central task in feature-level analysis is to identify taxa with differential abundance between groups. The `generate_taxa_test_single` function performs differential abundance analysis (DAA) based on compositional data using the LinDA method, which is a DAA method based on log linear model with bias correction due to compositional effects. If the data are not compositional, regular linear regression analysis will be used.

> Zhou H, He K, Chen J, Zhang X. LinDA: linear models for differential abundance analysis of microbiome compositional data. Genome Biol. 2022 Apr 14;23(1):95. doi: 10.1186/s13059-022-02655-5. PMID: 35421994; PMCID: PMC9012043.

In the `generate_taxa_test_single` function, `feature.dat.type` parameter specifies the data type in the feature matrix. Depending on the data type, different preprocessing steps and methods are used.

* `count` and `proportion`: For count and proportion data, which are both compositional, `linda` will be called. To address zeros, a pseudo-count of 0.5 is added to the count data, and zeros are substituted with half of the nonzero minimum for proportion data (feature-wise). Winorization at 97% quantile is performed to reduce the influence of outliers.
* `other`: When `feature.dat.type` is set to "other", the data are considered to be non-compositional and ordinary linear regression analysis will be performed. Users need to determine the appropriate normalization and transformation of the data before running the function. This option increases the applicability of MicrobiomeStat to other data types.

The `prev.filter` and `abund.filter` parameters filter taxa based on their prevalence and average relative abundance, so those rare and less abundant taxa will be excluded from testing. As the statistical power for these rare/less abundant taxa tends to be low, excluding them can reduce multiple testing burden.

The `feature.level` determines what aggregation level(s) the tests will be performed. If `feature.level` is set to "original", the original features in `feature.tab` will be tested. The `feature.level` can also be set to the aggregated levels specified in the `feature.ann` matrix.

### Categorical vs Continuous Predictors

The `generate_taxa_test_single` function automatically distinguishes between categorical and continuous predictor variables:

* **Categorical variables** (factor/character): Creates pairwise comparisons vs. the reference level (first level of the factor). Output format: "Level vs Reference (Reference)" (e.g., "Treatment vs Control (Reference)")
* **Continuous variables** (numeric/integer): Tests linear association with a single slope coefficient. Output format: Variable name only (e.g., "age")

This distinction is important for interpreting results:

* For categorical variables, the coefficient represents the log2 fold change between groups
* For continuous variables, the coefficient represents the change in log2 abundance per unit increase in the predictor

The `ref.level` parameter (added in v1.4.4) allows you to explicitly specify the reference level for categorical `group.var`. By default, R uses the first level of the factor as the reference. Setting `ref.level` overrides this behavior, which is useful when you want to compare against a specific control group.

The `generate_taxa_test_single` outputs a table of LinDA association statistics for all tested taxa/features. The table contains the following components:

* `Variable`: It identifies the taxon/feature being analyzed.
* `Coefficient`: Expressed as log2FoldChange for categorical variables, or slope for continuous variables, bias-corrected. It indicates the degree and direction of change in the abundance of a specific taxon/feature.
* `SE`: Standard errors of the coefficients. It measures the variability of the coefficient estimates.
* `Mean Abundance`: The average abundance of a particular taxon/feature across all samples.
* `Prevalence`: The proportion of samples where a specific taxon/feature is present.

`generate_taxa_volcano_single` will produce a volcano plot based on the `generate_taxa_test_single` output. It visualizes the relationship between the effect size (log foldchange) and its statistical significance. The function has the `feature.sig.level` and `feature.mt.method` parameters:

* `feature.sig.level`: This parameter determines the significance level, influencing the position of the dashed lines in the volcano plot. It sets the threshold for distinguishing between significant and non-significant differences.
* `feature.mt.method`: This parameter determines whether the adjusted p-values or raw p-values will be plotted. Available options: "fdr" (false discovery rate), "bonferroni", and "none" (raw p-value).

Following shows an example:

```r
# Load data
data(peerj32.obj)

# Generate taxa test
test.list <- generate_taxa_test_single(
    data.obj = peerj32.obj,
    time.var = "time",
    t.level = "2",
    group.var = "group",
    adj.vars = "sex",
    feature.dat.type = "count",
    feature.level = c("Phylum","Genus","Family"),
    prev.filter = 0.1,
    abund.filter = 0.0001,
    ref.level = "Placebo"  # Explicitly set reference level for group comparisons
)
```

#### First 10 Rows of Differential Abundance Results at Genus Level

<table><thead><tr><th>Variable</th><th width="135">Coefficient</th><th width="54">SE</th><th>P.Value</th><th>Adjusted.P.Value</th><th>Mean.Abundance</th><th>Prevalence</th></tr></thead><tbody><tr><td>Actinomycetaceae</td><td>0.43088737</td><td>0.8125191</td><td>0.60204023</td><td>0.9892442</td><td>0.0001950405</td><td>0.7272727</td></tr><tr><td>Aerococcus</td><td>-0.09734179</td><td>0.7893169</td><td>0.90314569</td><td>0.9892442</td><td>0.0002352668</td><td>0.5909091</td></tr><tr><td>Aeromonas</td><td>0.02022775</td><td>1.0311377</td><td>0.98455351</td><td>0.9892442</td><td>0.0002829477</td><td>0.6363636</td></tr><tr><td>Akkermansia</td><td>-0.70914707</td><td>0.5667601</td><td>0.22603834</td><td>0.9892442</td><td>0.0202212889</td><td>1.0000000</td></tr><tr><td>Allistipes et rel.</td><td>-0.54628088</td><td>0.4985462</td><td>0.28688461</td><td>0.9892442</td><td>0.0083365762</td><td>1.0000000</td></tr><tr><td>Anaerofustis</td><td>0.37736758</td><td>0.3988262</td><td>0.35592789</td><td>0.9892442</td><td>0.0013725489</td><td>1.0000000</td></tr><tr><td>Anaerostipes caccae et rel.</td><td>-0.45297144</td><td>0.1723513</td><td>0.01655715</td><td>0.7004574</td><td>0.0185944926</td><td>1.0000000</td></tr><tr><td>Anaerotruncus colihominis et rel.</td><td>0.05420558</td><td>0.4605402</td><td>0.90754073</td><td>0.9892442</td><td>0.0028354658</td><td>1.0000000</td></tr><tr><td>Anaerovorax odorimutans et rel.</td><td>-0.55577241</td><td>0.3180729</td><td>0.09672749</td><td>0.9892442</td><td>0.0044828621</td><td>1.0000000</td></tr><tr><td>Aneurinibacillus</td><td>-0.20493605</td><td>0.5227462</td><td>0.69939327</td><td>0.9892442</td><td>0.0007296989</td><td>0.9545455</td></tr></tbody></table>

```r
# Generate volcano plots
volcano_plots <- generate_taxa_volcano_single(
    data.obj = peerj32.obj,
    group.var = "group",
    test.list = test.list,
    feature.sig.level = 0.1,
    feature.mt.method = "none"
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FqW8GuN7ckEumWQ253kx6%2FScreenshot%202023-10-07%20at%2015.18.08.png?alt=media&amp;token=0c20868c-01d6-4272-a708-3a31b969a1da" alt=""><figcaption></figcaption></figure>

Next, we will introduce functions to plot the taxa/features data. They can be used to visualize specific taxa/features, for example, those selected from differential abundance anlysis. Or they can be used to visualize all taxa with some basic filtering. The first function is `generate_taxa_boxplot_single`, which generate boxplots of abundance data. It has the following relevant parameters:

* `feature.dat.type`: One of "count", "proportion" or "other". For "count", the data will be converted to proportion data before the visualization.
* `transform`: This parameter indicates the transformation to apply to the abundance data when plotting. Transformations are only applied when the `feature.dat.type` is set to either "count" or "proportion". When `feature.dat.type` is "other", no transformation will be performed. User should determine the appropriate transformation to better visualize the data. The available options for `transform` include:
  * `"sqrt"`: Square root transformation (default)
  * `"identity"`: No transformation
  * `"log"`: Logarithmic transformation. Zeros are replaced with half of the non-zero minimum for each taxon before log transformation.
* `feature.level`: Specifiy which level of the data to be plotted. Same meaning as in `generate_taxa_test_single`.
* `features.plot`: This parameter can be used in all feature-level visualization functions to specify which taxa or features should be visualized. This is particularly useful for focusing on the results of differential abundance analyses. When you provide a vector of taxa or feature names to `features.plot`, this will directly select these features for visualization, overriding any settings in `prev.filter` and `abund.filter`. By using this parameter, you can directly highlight and examine the taxa or features that are significantly different in abundance across your comparisons.
* `top.k.plot` and `top.k.func`: In many scenarios, especially when navigating through expansive datasets, you may want to focus on a select subset of taxa that stand out either due to their high abundance or large variability. `top.k.plot` lets you visualize the top k taxa/features based on the criterion you selected in `top.k.func`, which have four choices:

  * `"mean"`: Highlights taxa with the highest average abundances across samples.
  * `"sd"`: Selects taxa with the greatest variability (standard deviation) across samples, useful for identifying taxa with notable differences under varying conditions.
  * `"prevalence"`: Chooses taxa with the highest occurrence across samples, targeting those most consistently present.
  * `top.k.func` can also accept a user-defined function so that the users can rank taxa based on their own criterion. The user-defined function should take the abundance matrix (those in `feature.tab` and `feature.agg.list`) as the input and returns a numeric vector of the feature importance values. This allows for criteria beyond "mean", "sd", or "prevalence".

  Certainly. Here's the revised content in English, maintaining consistency with the context and using more professional and concise language:

After performing differential abundance analysis with `generate_taxa_test_single` and visualizing results with `generate_taxa_volcano_single`, we can further explore phylogenetic relationships and abundance patterns using the `generate_taxa_cladogram_single` function. This function creates a circular cladogram with an integrated heatmap.

Key features of `generate_taxa_cladogram_single`:

1. Visualization of phylogenetic relationships
2. Integrated heatmap of abundance or coefficient data
3. Simultaneous visualization of multiple taxonomic levels
4. Filtering based on statistical significance
5. Customizable color-coding of cladogram branches by taxonomic level

Example usage:

```r
plot.list <- generate_taxa_cladogram_single(
  data.obj = peerj32.obj,
  test.list = test.list,
  group.var = "group",
  feature.level = c("Phylum","Genus","Family"),
  feature.mt.method = "none",
  cutoff = 0.9,
  color.group.level = "Family"
)
```

Key parameters:

* `color.group.level`: Taxonomic level for branch color-coding

The function returns a list of ggplot objects, one for each comparison in the data. These plots provide a holistic view of the microbiome data, combining phylogenetic information, abundance patterns, and statistical significance.

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-dc1a7d382ac1c829ee6ebff8a5bad40d4730eaf2%2Fcladogram.png?alt=media" alt=""><figcaption></figcaption></figure>

The following shows the usage and output of the function `generate_taxa_boxplot_single`. All the taxa are plotted together.

```r
generate_taxa_boxplot_single(
  data.obj = peerj32.obj,
  time.var = "time",
  t.level = "1",
  group.var = "group",
  strata.var = NULL,
  feature.level = c("Family"),
  feature.dat.type = "count",
  features.plot = NULL,
  top.k.plot = 8,
  top.k.func = "mean",
  transform = "log",
  prev.filter = 0,
  abund.filter = 0,
  base.size = 16,
  theme.choice = "bw",
  custom.theme = NULL,
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FzUopkKAL53c4LlH30jbr%2FScreenshot%202023-10-10%20at%2021.03.21.png?alt=media&amp;token=ec34e5a7-07e4-4a58-8b58-7747c7a6c670" alt=""><figcaption></figcaption></figure>

For more clarity, `generate_taxa_indiv_boxplot_single` provides separate plots for each taxon. When the `pdf` parameter is set to `TRUE`, you can find the file in your default directory. Each page of this file represents a boxplot for a specific taxon or feature.

```r
generate_taxa_indiv_boxplot_single(
  data.obj = peerj32.obj,
  time.var = "time",
  t.level = "1",
  group.var = "group",
  strata.var = "sex",
  feature.level = c("Family"),
  features.plot = NULL,
  feature.dat.type = "count",
  top.k.plot = NULL,
  top.k.func = NULL,
  transform = "log",
  prev.filter = 0,
  abund.filter = 0,
  base.size = 20,
  theme.choice = "bw",
  custom.theme = NULL,
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FZ6TI9B7cYMjvPDhFGO6b%2FScreenshot%202023-08-05%20at%2020.04.16.png?alt=media&amp;token=bc09aae2-44c2-43cf-9293-97177c436184" alt=""><figcaption></figcaption></figure>

Besides boxplots, MicrobiomeStat can also generate heatmaps using the `generate_taxa_heatmap_single` function. Heatmaps are particularly insightful for discerning clusters of taxa/features that exhibit similar abundance profiles across amples. By default, the function will only cluster rows (taxa/features) based on their abundance patterns. The columns are ordered by `group.var` and `strata.var`. If users wish to see the taxa in their original order without clustering, they can achieve this by setting `cluster.rows = FALSE`. The function also allows for column clustering by setting `cluster.cols = TRUE`, which can be instrumental in revealing groups of samples with similar abundance profiles. Note that when `feature.dat.type` is "count” or "proportion", the data will be visualized using proportions. For "other" type, the original scale will be used. Following is an example:

```r
generate_taxa_heatmap_single(
  data.obj = peerj32.obj,
  time.var = NULL,
  t.level = NULL,
  group.var = "group",
  strata.var = "sex",
  feature.level = c("Family"),
  feature.dat.type = "count",
  features.plot = NULL,
  top.k.plot = NULL,
  top.k.func = NULL,
  prev.filter = 0.1,
  abund.filter = 0.1,
  base.size = 10,
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FNIUcsps3bigv8Gb4JyRF%2FScreenshot%202023-10-10%20at%2021.16.15.png?alt=media&amp;token=23b7b476-3079-4384-9c63-a069a81a9fad" alt=""><figcaption></figcaption></figure>

We can use `generate_taxa_dotplot_single` function as an alternative to the heatmap. Here is the example:

```r
generate_taxa_dotplot_single(
  data.obj = peerj32.obj,
  time.var = NULL,
  t.level = NULL,
  group.var = "group",
  strata.var = "sex",
  feature.level = c("Family"),
  feature.dat.type = "count",
  features.plot = NULL,
  top.k.plot = NULL,
  top.k.func = NULL,
  prev.filter = 0.1,
  abund.filter = 0.001,
  base.size = 16,
  theme.choice = "bw",
  custom.theme = NULL,
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 15,
  pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FrPjJyFgakqOo1nTWlNJ3%2FScreenshot%202023-10-10%20at%2021.34.06.png?alt=media&amp;token=09142e46-1d6a-4e93-9791-b89bd15f0ac6" alt=""><figcaption></figcaption></figure>

We can use `generate_taxa_barplot_single` function to generate stacked bar plots of taxa. The function has an important parameter `feature.number`.

* `feature.number`: This parameter determines the maximum number of taxa/features that will be visualized directly in the barplot. For datasets with numerous features, it's practical to limit to the most abundant or significant taxa, ensuring that the visualization remains informative and isn't cluttered. When the number of taxa surpasses the value defined in `feature.number`, the function aggregates low-abundance taxa into a collective category labeled "other". This means, for instance, if there are over 20 features in the dataset but `feature.number` is set to 20, the least abundant features that exceed this count will be collectively presented as "other" in the visualization. This approach ensures that the chart remains legible, highlighting the most dominant features, while still accounting for the contributions of less abundant taxa.

With this insight, let's now examine the function and the resultant visuals:

```r
generate_taxa_barplot_single(
  data.obj = peerj32.obj,
  time.var = NULL,
  t.level = NULL,
  group.var = "group",
  strata.var = "sex",
  feature.level = "Family",
  feature.dat.type = "count",
  feature.number = 30,
  base.size = 10,
  theme.choice = "bw",
  custom.theme = NULL,
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FXe9hdNxqJSNSPACyMuXi%2FScreenshot%202023-10-10%20at%2021.37.34.png?alt=media&amp;token=f7f74722-16f2-49b5-bb5a-67689056fd50" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F7mjZNraXOrO9RHtYw7ji%2FScreenshot%202023-10-10%20at%2021.38.40.png?alt=media&amp;token=e49d1543-d872-47bf-bacb-a869e69aa18e" alt=""><figcaption></figcaption></figure>

### Visualizing Differential Abundance with MA Plots

The MA plot is a powerful visualization tool for differential abundance analysis, commonly used in genomics and now available for microbiome data through MicrobiomeStat. The `generate_taxa_ma_plot_single` function creates MA plots that visualize the relationship between average abundance (A) and log2 fold change (M) for each taxon, helping researchers identify features with significant abundance differences between groups.

In an MA plot:

* The x-axis (A) represents the average abundance of each taxon across all samples
* The y-axis (M) represents the log2 fold change between comparison groups
* Points are colored based on statistical significance
* Point size can represent prevalence or other metrics
* Significant taxa are typically labeled for easy identification

MA plots are particularly useful because they:

1. Show both effect size (fold change) and abundance information in one plot
2. Help identify abundance-dependent biases in differential testing
3. Allow visualization of overall patterns in the data (e.g., whether most changes are increases or decreases)
4. Complement volcano plots by emphasizing the abundance dimension

#### Using the `generate_taxa_ma_plot_single` function

The `generate_taxa_ma_plot_single` function takes the output from `generate_taxa_test_single` and creates MA plots for the differential abundance results:

```r
# First perform differential abundance testing
test.list <- generate_taxa_test_single(
  data.obj = peerj32.obj,
  group.var = "group",
  adj.vars = NULL,
  feature.level = c("Genus", "Family"),
  feature.dat.type = "count"
)

# Then create MA plots
plot.list <- generate_taxa_ma_plot_single(
  data.obj = peerj32.obj,
  group.var = "group",
  test.list = test.list,
  feature.sig.level = 0.05,
  feature.mt.method = "fdr"
)

# View the plot for Genus level
plot.list$Genus[[1]]
```

#### Key parameters for `generate_taxa_ma_plot_single`

* `data.obj`: The MicrobiomeStat data object
* `group.var`: The grouping variable used in the differential testing
* `test.list`: The output from `generate_taxa_test_single`, containing test results
* `feature.sig.level`: Significance level cutoff for highlighting taxa (default is 0.05)
* `feature.mt.method`: Multiple testing correction method: "fdr" (default), "bonferroni", or "none"
* `features.plot`: Optional. Specific taxa to include in the plots
* `palette`: Optional. Color palette for the plot
* `pdf`: Whether to save the plot as a PDF file
* `pdf.wid` and `pdf.hei`: Width and height of the PDF file if saved

#### Example MA plot interpretation

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-f8b4df7c4fa766888ee412e08877f0f370c51191%2Fma_plot_example.png?alt=media" alt=""><figcaption><p>Example MA plot showing differential abundance of genera between groups</p></figcaption></figure>

In the MA plot above:

* Each point represents a taxon (genus in this example)
* Taxa above the horizontal line (y=0) are more abundant in the comparison group
* Taxa below the line are less abundant in the comparison group
* Points in red are statistically significant at the specified threshold
* Larger points indicate taxa with higher prevalence across samples
* Text labels identify significant taxa to focus on for biological interpretation

MA plots complement volcano plots by emphasizing the relationship between abundance and fold change, which can reveal important patterns that might be missed when looking at just statistical significance. For example, you might observe that most significant changes occur in low-abundance or high-abundance taxa, which could inform further biological interpretation or methodological considerations.

***

## Advanced: Tree-Guided Differential Abundance with `linda2()`

MicrobiomeStat v1.4.2+ includes `linda2()`, an enhanced version of LinDA that supports **phylogenetic tree-guided smoothing** for improved statistical power. This method borrows strength from evolutionarily related taxa to boost detection of differentially abundant features.

### When to Use `linda2()`

* When you have a **phylogenetic tree** available (e.g., from 16S rRNA or shotgun metagenomic data)
* When you want to **increase statistical power** for detecting differentially abundant taxa
* When you expect **phylogenetically clustered effects** (related taxa responding similarly to treatment)

### Key Parameters

```r
linda2(
  feature.dat,           # Feature abundance matrix
  meta.dat,              # Sample metadata
  formula,               # Model formula (e.g., "~ group + age")
  feature.dat.type,      # "count", "proportion", or "other"
  weights = NULL,        # Sample weights (NULL, "detection_depth", column name, or numeric vector)
  tree = NULL,           # Phylogenetic tree (phylo object)
  tree.smooth = FALSE,   # Enable tree-guided smoothing
  tree.lambda = 0.1,     # Smoothing strength (0.05-0.2 recommended)
  tree.k = 5,            # Number of nearest neighbors for local smoothing
  omnibus = TRUE         # Max-T omnibus combining baseline and smoothed results
)
```

### Parameter Details

* `weights`: Sample weights for regression models. Options:
  * `NULL` (default): No weighting, standard LinDA analysis
  * `"detection_depth"`: Automatic Detection Depth Weighting (DDW) using `sqrt(colSums(feature.dat > 0))`. Recommended for handling sample quality heterogeneity
  * Character string: Name of a column in `meta.dat` containing custom weights
  * Numeric vector: Direct sample weights (length must equal number of samples)
* `tree.lambda`: Controls smoothing strength. Higher values = more borrowing from neighbors.
  * Default: 0.1 (mild smoothing)
  * Range: 0.05-0.2 recommended
  * Use lower values (0.05) for exploratory analysis
  * Use higher values (0.2) when strong phylogenetic clustering is expected
* `tree.k`: Number of nearest phylogenetic neighbors for local smoothing.
  * Default: 5
  * Lower values prevent signal leakage to distant taxa
* `omnibus`: When `TRUE` (default) and tree smoothing is enabled, computes Max-T omnibus p-values that combine baseline and smoothed results. This achieves the "envelope" effect: it captures the advantage of smoothing for phylogenetically clustered signals while not losing power for isolated signals.

### Example: Tree-Guided Analysis with phyloseq Data

```r
library(phyloseq)
library(MicrobiomeStat)

# If you have a phyloseq object with a tree
data("GlobalPatterns")
GP <- GlobalPatterns

# Subset to two groups for comparison
sample_data(GP)$Environment <- ifelse(
  sample_data(GP)$SampleType %in% c("Feces", "Skin", "Tongue"),
  "Human", "Environmental"
)

# Run linda2 with tree-guided smoothing and omnibus
result <- linda2(
  phyloseq.obj = GP,
  formula = "~ Environment",
  tree.smooth = TRUE,      # Enable tree smoothing
  tree.lambda = 0.1,       # Mild smoothing
  omnibus = TRUE,          # Max-T omnibus (default)
  verbose = TRUE
)

# The tree is automatically extracted from the phyloseq object
```

### Detection Depth Weighting (DDW)

`linda2()` supports automatic Detection Depth Weighting, which adjusts for differences in sample detection quality. Samples with more detected features (higher detection depth) receive higher weight, improving power when sample quality is heterogeneous.

```r
# Run linda2 with DDW
result <- linda2(
  feature.dat = otu_table,
  meta.dat = metadata,
  formula = "~ group",
  feature.dat.type = "count",
  weights = "detection_depth"   # Automatic DDW
)
```

Technical details:

* DDW uses `sqrt(detection_depth)` rather than raw detection depth
* Raw detection depth weights cause standard error underestimation (\~7.5%) and inflated Type I error
* The square root transformation preserves power gains while maintaining proper FDR control
* DDW is most beneficial when samples have heterogeneous detection depths (CV > 0.2)

### Precision-Weighted Bias Correction

`linda2()` also includes an improved bias correction method that weights taxa by their precision (1/SE²). This reduces bias estimation error when taxa have heterogeneous standard errors (common in microbiome data where high-abundance taxa have lower variance).

This feature is automatically enabled when:

* SE ratio (max/min) is less than 100
* All SE values are finite and positive

### Output Interpretation

The output from `linda2()` is similar to `linda()`, with additional columns when tree smoothing is enabled:

```r
# Access results for a specific variable
result$output$EnvironmentHuman

# Standard columns:
# - baseMean: Normalized mean abundance
# - log2FoldChange: Bias-corrected effect size
# - lfcSE: Standard error
# - stat: Test statistic
# - pvalue: Final p-value (omnibus if enabled, smoothed otherwise)
# - padj: FDR-adjusted p-value
# - reject: Whether the taxon is significant at the specified alpha
# - df: Degrees of freedom

# Additional columns with tree smoothing:
# - pvalue.baseline: P-value from standard (unsmoothed) analysis
# - pvalue.smoothed: P-value after tree-guided smoothing (with M_eff correction)
# - pvalue.omnibus: Max-T omnibus p-value (if omnibus = TRUE)
```

### When Tree Smoothing Helps Most

Tree-guided smoothing provides the greatest power improvement when:

1. **True effects are phylogenetically clustered**: Related taxa respond similarly
2. **Sample size is limited**: Borrowing strength helps overcome noise
3. **Effect sizes are moderate**: Very large effects are detected anyway

For hypothesis-generating analyses, tree smoothing can reveal patterns that would be missed by taxon-by-taxon testing.


# One-Click Reports Generation

MicrobiomeStat equips researchers with automated workflows to quickly analyze the data and report the major findings by providing a one-click report-generation function. The standardized report integrates multidimensional perspectives, including alpha diversity, beta diversity, and differential abundance analysis, for comprehensive insights. The report contains both visualizations and statistical summaries to aid in biological interpretation and facilitate result dissemination. By automating time-consuming manual analytical tasks, MicrobiomeStat enables rapid, reproducible, and robust reporting to advance microbiome research.

The `mStat_generate_report_single()` function generates an integrated report for cross-sectional (single time point) analysis. It performs:

* **Alpha diversity analysis**: This calls functions `mStat_calculate_alpha_diversity()`, `generate_alpha_boxplot_single()`, and `generate_alpha_test_single()`.
* **Beta diversity analysis**: This calls functions `mStat_calculate_beta_diversity()`, `generate_beta_ordination_single()`, and `generate_beta_test_single()`.
* **Feature-level analysis**: This calls functions `generate_taxa_barplot_single()`, `generate_taxa_dotplot_single()`, `generate_taxa_heatmap_single()`, `generate_taxa_test_single()` and `generate_taxa_volcano_single()`.

The function then compiles these analyses into a comprehensive PDF report. The report includes:

* A data summary from `mStat_summarize_data_obj()`
* Visual representations including alpha diversity boxplots, beta diversity ordination plots, and taxa composition visualizations
* Tables detailing statistical test results
* Commentary on key findings

Before using the function, it is important to understand the parameters:

* `data.obj`: A list object in MicrobiomeStat data format, which includes components feature.tab (matrix), feature.ann (matrix), meta.dat (data.frame), tree, and feature.agg.list (list). This object can be converted from other formats using several functions from the MicrobiomeStat package, or constructed manually. For more detailed information on how to convert data from other formats or how to construct the `data.obj` manually, please refer to the following page.

{% content-ref url="/pages/WK9NC4ukGZbAvQGuCKUR" %}
[Creating the MicrobiomeStat Data Object](/setting-up-microbiomestat-installation-and-data-preparation/laying-the-foundation-creating-the-microbiomestat-data-object)
{% endcontent-ref %}

* Once the data object has been successfully constructed, users may wish to perform some preprocessing of the data, including sample-level and feature-level filtering, renaming and recoding of the variables, changing the data types of the variables (e.g., character to numeric, character to factor, etc.) and rearranging the levels for a factor variable (so the reference category appears as the first level). These preprocessing will make sure the analyses proceed smoothly. We refer users to the following document for data manupilation.

{% content-ref url="/pages/LLh6oXlfW0M2j5bSG5jU" %}
[Data Filtering](/data-manipulation-and-transformation/data-filtering)
{% endcontent-ref %}

* `group.var`: The name of the variable of primary interest. We currently support categorical type but plan to support numeric type in future versions. For a continuous variable, the user could dichotomize their variable for the exploratory purpose.
* `test.adj.vars`: Names of columns in the metadata containing covariates to be adjusted for in statistical tests and models. Default is NULL, which indicates no covariates are adjusted for in statistical testing.
* `vis.adj.vars`: For alpha and beta diversity visualization functions, the `vis.adj.vars` parameter specifies the covariates whose effects will be removed before visualization. This is achieved by taking reisuals after regressing the alpha diversity and beta diversity PCs on the variables specified by `vis.adj.vars`. This step is important to reveal the signal of interest when the unwanted variation in `vis.adj.vars` dominates/obscures the signals. Although it is equally important to do similar adjustment to feature-level data, due to the complexity of the data characteristics (zero inflation, etc.), such linear model-based adjustment may not be sufficient.
* `strata.var`: Variable to stratify the data in visualization.
* `time.var`: Variable name used for time points.
* `t.level`: Character string specifying the time level/value to subset the data to, only if both `time.var` and `t.level` are specified. If NULL, all data will be used.
* `alpha.obj`: A matrix containing pre-calculated alpha diversity measures (row - samples, column - measures). If NULL (default), alpha diversity measures will be calculated using `mStat_calculate_alpha_diversity` function after data rarefaction by `mStat_rarefy_data`. The rarefaction depth can be specified with `depth` parameter or minimum depth will be used if `depth = NULL`.
* `alpha.name`: The alpha diversity measures to be used. Supported measures include "shannon", "simpson", "observed\_species", "chao1", "ace", and "pielou". If this parameter is set to NULL, the report will not include any alpha diversity results.
* `depth`: An integer. Rarefaction depth when rarefaction is needed. If NULL, the minimum sequencing depth will be used.
* `dist.name`: A character vector specifying which beta diversity measures to calculate. Supported measures are "BC" (Bray-Curtis), "Jaccard", "UniFrac" (unweighted UniFrac), "GUniFrac" (generalized UniFrac), "WUniFrac" (weighted UniFrac), and "JS" (Jensen-Shannon divergence). If this parameter is set to NULL, the report will not include any beta diversity results.
* `dist.obj`: A list of distance matrices between samples. If NULL, beta diversity distance matrices will be automatically computed from `data.obj` using `mStat_calculate_beta_diversity` after data rarefaction.
* `pc.obj`: A list containing the principal coordinates calculated on the beta diversity distance matrices. If NULL (default), dimension reduction will be automatically performed using metric multidimensional scaling (MDS) via `mStat_calculate_PC`. The `pc.obj` list structure should contain:
  * `$points`: A matrix with samples as rows and PCs as columns containing the coordinates.
  * `$eig`: Eigenvalues for each PC dimension.
  * `$vectors`: Feature loadings vectors for each PC.
  * Other metadata like `$method`, `$dist.name`, etc. See `mStat_calculate_PC` function for details.
* `feature.dat.type`: The type of the feature data, which determines how the data is handled in downstream analyses. Should be one of: "count": Raw count data from a sequencing experiment (e.g. ASV/OTU count); "proportion": Data that has already been normalized to proportions/percentages (e.g., functional data); "other": Other non-compositional data types, where the data will be analyzed directly without normalization and transformation. The user needs to determine the data-specific QC, normalization, and transformation. If the user wants to normalize/transform the abundance data on his own way, he can also use this option.
* `feature.analysis.rarafy`: Logical, indicating whether to rarefy the data for feature-level analysis. If TRUE, the feature data will be rarefied before visualization and analysis. Default is TRUE. Note: When the majority of the features are of low-abundance, their presence/absence strongly depends on the sequencing depth. Rarefaction can be used to remove the unwanted variation due to sequencing depth and could increase the power for the analysis of rare features.
* `vis.feature.level`: The feature levels to be visualized for an overview of the data (stacked barplot, heatmap, etc.). Feature levels should correspond to the column names in the feature annotation matrix (`feature.ann`) of data.obj. It could also contain the "original" level, which is the raw feature level without aggregation.
* `bar.area.feature.no`: A numeric value indicating the number of top abundant features to retain in both barplot and areaplot. Features with average relative abundance ranked below this number will be grouped into 'Other'. Default 40. Only applicable to count and proportion data.
* `heatmap.feature.no`: A numeric value indicating the number of top abundant features to retain in the heatmap. Features with average relative abundance ranked below this number will be grouped into 'Other'. Default 40.
* `dotplot.feature.no`: A numeric value indicating the number of top abundant features to retain in the dotplot. Features with average relative abundance ranked below this number will be grouped into 'Other'. Default 40. Only applicable to count and proportion data.
* `test.feature.level`: The feature levels to be tested. Similar to `vis.feature.level`. The signficant features will be visualized collectively and individually.
* `feature.mt.method`: Character, multiple testing method to identify differential features, "fdr", "bonferroni", or "none". Default is "fdr".
* `feature.sig.level`: Numeric, significance cutoff for declaring differntial features, default is 0.1.
* `feature.box.axis.transform`: A string indicating the transformation to be applied to abundance data before plotting. This parameter is only used in `generate_taxa_boxplot_single` and `generate_taxa_indiv_boxplot_single`. Options are:
  * "sqrt": Square root transformation (default),
  * "identity": No transformation,
  * "log": Logarithmic transformation.
* `base.size`: Base font size for the generated plots.
* `theme.choice`: Plot theme choice. Can be one of: "prism": ggprism::theme\_prism(), "classic": theme\_classic(), "gray": theme\_gray(), "bw": theme\_bw().
* `output.file`: A character string specifying the output file name for the report. Full path can be specified, e.g., "path\_to\_your\_location/report". The file extension (.pdf or .html) will be automatically added based on the `output.format` if not already present. This parameter also determines the title of the generated report. For example, if set to "path\_to\_your\_location/my\_report", the report title will be "my\_report".
* `output.format`: A character string specifying the desired output format of the report. Must be either "pdf" or "html". Default is c("pdf", "html"), which will use the first value ("pdf") if not explicitly specified. This parameter determines whether the report will be generated as a PDF or HTML document.

Note: Before running the function, please be aware of potential compatibility issues between RStudio and LaTeX. These issues can lead to problems such as images from the RStudio Viewer appearing in unexpected locations in the PDF report. To avoid this, it is recommended to clear the current images in the RStudio Viewer before running the function. You can do this by clicking on the broom icon in the RStudio Viewer.

Now, let's see how we can implement the function:

```r
# Load the dataset
data(peerj32.obj)
data.obj = peerj32.obj

# Specify variable names
group.var = "group" # Variable used for grouping samples, primary variable of interest
vis.adj.vars = c("sex") # Covariates whose effects need to be removed before visualization
test.adj.vars = c("sex") # Covariates whose effects need to be adjusted in statistical tests
time.var = "time" # Variable used for time points

# Specify diversity indices
alpha.name = c("shannon", "observed_species") # Alpha diversity indices to calculate
dist.name = c("BC",'Jaccard') # Beta diversity indices to calculate

# Specify feature levels for visualization and testing
vis.feature.level = c("Phylum", "Family", "Genus") # Feature levels for visualization to have an overview of the data
test.feature.level = "Family" # Feature level to use for testing

# Specify other parameters
feature.dat.type = "count" # Type of the feature data
theme.choice = "bw" # Theme choice for the plots
base.size = 20 # Base size for the plots

# Parameters for multiple testing. Following setting is just for illustration. In real data analysis, multiple testing correction should always be applied.  
feature.mt.method = "none" # Multiple testing method for differential feature analysis
feature.sig.level = 0.2 # Significance level cutoff for highlighting differential features 

# Specify output file
output.file = "path/to/mStat_generate_report_single_example.pdf" # Replace with your own file path for the output report

# Specify optional parameters
dist.obj = NULL # Replace with a pre-computed distance matrix if available
alpha.obj = NULL # Replace with a pre-computed alpha diversity matrix if available
depth = NULL # Replace with a desired rarefaction depth, if NULL, minimum depth will be used
t.level = "1" # Replace with a desired time level if time points have multiple levels
feature.box.axis.transform = "sqrt" # Axis transformation for feature boxplots
strata.var = "sex" # Variable to stratify on in visualization

# Specify parameters for feature retention
bar.area.feature.no = 40 # Number of top abundant features to retain in barplot and areaplot
heatmap.feature.no = 40 # Number of top abundant features to retain in heatmap
dotplot.feature.no = 40 # Number of top abundant features to retain in dotplot

# Run the function
mStat_generate_report_single(
   data.obj = data.obj,
   dist.obj = dist.obj,
   alpha.obj = alpha.obj,
   group.var = group.var,
   vis.adj.vars = vis.adj.vars,
   test.adj.vars = test.adj.vars,
   time.var = time.var,
   alpha.name = alpha.name,
   depth = depth,
   dist.name = dist.name,
   t.level = t.level,
   feature.box.axis.transform = feature.box.axis.transform,
   strata.var = strata.var,
   vis.feature.level = vis.feature.level,
   test.feature.level = test.feature.level,
   feature.dat.type = feature.dat.type,
   bar.area.feature.no = bar.area.feature.no,
   heatmap.feature.no = heatmap.feature.no,
   dotplot.feature.no = dotplot.feature.no,
   feature.mt.method = feature.mt.method,
   feature.sig.level = feature.sig.level,
   theme.choice = theme.choice,
   base.size = base.size,
   output.file = output.file
 )
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-acce1a8568240e3e05a518a529a657c46cab09d8%2FmStat_generate_report_single_example_page-0001.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-f1ab16694ee24587008743f8e66157b6975ca169%2FmStat_generate_report_single_example_page-0002.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-6f878c0be478e1a27f890ecfcf81ef8fbce886e2%2FmStat_generate_report_pair_example_page-0003.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-cd5f825c848e9ef65d5699c6f883c5d234be064b%2FmStat_generate_report_single_example_page-0004.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-432a5e9e207264d9097dcfdaa1524554a5783052%2FmStat_generate_report_single_example_page-0005.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-f33f33e8b828b6fc6e07de6b43e3df1a1a69ebcf%2FmStat_generate_report_single_example_page-0006.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-eca22ce8074d706005d3a5b4418d2e49af72b23a%2FmStat_generate_report_single_example_page-0007.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-407765743d8f90822598a64642e7ef7b316a6f10%2FmStat_generate_report_single_example_page-0008.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-a89a82427bab11f01747350391dd3203ddbc2b8d%2FmStat_generate_report_single_example_page-0009.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-fbebf13555d785c7de728329d870a830cdf05598%2FmStat_generate_report_single_example_page-0010.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-39b26966a4d48be11add7def4bd50ba4bc93eeea%2FmStat_generate_report_single_example_page-0011.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-1f3e8db9ba8c1174a8807d0b131aa93641935628%2FmStat_generate_report_single_example_page-0012.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-9d2021e791d3d2f5935668b595be86c289039b86%2FmStat_generate_report_single_example_page-0013.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-cf58f93c0905346f775b01ebee9ea7617c82c3c1%2FmStat_generate_report_single_example_page-0014.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-9f57206902f30b7df86b8a10038da5877500d0e5%2FmStat_generate_report_single_example_page-0015.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-29f2c53a0e649ba637a1b5c921bf706c4fd0c999%2FmStat_generate_report_single_example_page-0016.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-21fc58705cb4015bb926488404b968e6f6642513%2FmStat_generate_report_single_example_page-0017.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-8de1266bb655bb743952ac6384601523c94c5e2a%2FmStat_generate_report_single_example_page-0018.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-c2356eae6efac4248ae26eedf35d58399bc15955%2FmStat_generate_report_single_example_page-0019.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-fc25eb55feb94a39e71bc20afe98a08bf3a8e11d%2FmStat_generate_report_single_example_page-0020.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-857fc8ab5d22d2fd35e9ae0e5eee6dbf8229f61c%2FmStat_generate_report_single_example_page-0021.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-a309fa96a24d10bee28458e9af638b177e6bf445%2FmStat_generate_report_single_example_page-0022.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-f1457db2302860420b70cbb767b4496ed8d8e760%2FmStat_generate_report_single_example_page-0023.jpg?alt=media" alt=""><figcaption></figcaption></figure>

{% file src="/files/Bm7C8SmCnR1MIU0y6zaE" %}

The automated report reduces the need for manual interaction and ensures consistency.


# Introduction

In clinical microbiome research, the paired samples design is a common study design that are frequently used to study the treatment effects. By using self as a control, the effects of many variables can be efficiently controlled, increasing the analysis power as well as reducing potential confounding. By sampling the microbiome longitudinally, it is also possible to study the microbiome dynamics/evolution and its association with some treatment outcome. Depending on how the paired samples are collected, there are mainly two setting involving paired samples. In the first setting, the two samples from the same subject are under two different conditions. For example, one sample could be before treatment and the other sample could be after treatment. The main interest is to study the difference between the microbiomes before and after treatment, and to correlate the microbiome change with some treatment outcome. In the second setting, the two samples are collected under the same condition. For example, the two samples are both obtained in the treatment course, so both samples are under the same treatment condition. The main purpose is to understand how the microbiome evolves in the treatment course, and how the evolution is related to the treatment outcome. In both settings, we will label the two samples as "t1" and "t2", respectively. Although the questions to be asked may be different from the two settings, the analysis tasks share much commonality:

* **Task 1** (paired comparison): Compare the t1 vs. t2 to see if there are community-level and feature-level microbiome differences.
* **Task 2** (per time point analysis): Given a subject-level outcome, investigate the association of the t1 and t2 microbiome with the outcome, separately, to see how the association changes.
* **Task 3** (analysis of changes): If there are changes between t1 and t2, investigate whether and how the changes are associated with an outcome.
* **Task 4** (joint analysis)：Jointly analyze t1 and t2 and test the global hypothesis that none of the two time points is associated with an outcome. This analysis will allow the identification of taxa whose abundance differs in some ways with respect to the outcome. The p-values for individual terms as well as the results from Task 2 and 3 will help understand the nature of the associations.

Task 2 can be achieved using the functions for single time point analysis described in last section, and other Tasks are specific for paired samples design. Although Task 1-3 in principle can be simultaneously achieved by the joint modeling approach of Task 4, tools for analysis of independent data (Task 1-3) are usually more abundant, robust and flexible and require less assumptions than the joint approach. Task 3 is particularly useful if the difference at the t1 (baseline) is assumed not to exist, for example, due to randomization，or the baseline difference is a nuisance and should be controlled. Analysis of changes standardizes the large inter-subject variability at the baseline and is usually more powerful than analysis of t2 only. This guide will navigate you through a comprehensive analysis of microbiome data from a paired samples design. The visualizations produced by MicrobiomeStat can reveal patterns and trends in your data, facilitating a more straightforward interpretation and understanding of your results.

The dataset utilized in this guide is the peerj32 dataset, derived from a real-world study that investigates the interaction between human intestinal bacteria and host lipid metabolism under the influence of a probiotic intervention. The primary variable in this study is the 'LGG Probiotic/Placebo' treatment, with 'sex' serving as a stratifying variable in visualization and a covariate to be adjusted in the tests. The dataset includes taxonomic abundance data at the Phylum, Family, and Genus levels.

For an in-depth introduction and generation process of the peerj32 dataset, please refer to our previous cross-sectional study design tutorial.

{% content-ref url="/pages/N7CUcHG5GyAAIGTdnXD9" %}
[Introduction](/single-point-analysis/unraveling-cross-sectional-studies-with-microbiomestat)
{% endcontent-ref %}

For users wishing to apply our tutorial to their own datasets, please see the following guide.

{% content-ref url="/pages/WK9NC4ukGZbAvQGuCKUR" %}
[Creating the MicrobiomeStat Data Object](/setting-up-microbiomestat-installation-and-data-preparation/laying-the-foundation-creating-the-microbiomestat-data-object)
{% endcontent-ref %}

This section explains how to convert your data into the `mStat` format, enabling you to use MicrobiomeStat for your research.

Note that, in our current implementation, the `group.var` and `strata.var` should be non-time-varying, i.e., they should stay constant across time points. `adj.vars` on the other hand could be time-varying in most cases. If only non-time-varying variables are allowed, we will state it explicitly.


# Alpha Diversity Analysis

Welcome to this tutorial on Alpha Diversity Analysis for Paired Samples. This analysis will involve studying variations in alpha diversity across different time points and groups. Our primary tools will be illustrative boxplots coupled with formal statistical tests, which will assist in identifying potential informative patterns in alpha diversity. One of our main objectives is to explore changes in alpha diversity within the same group and compare the changes between groups.

MicrobiomeStat supports "shannon", "simpson", "observed\_species", "chao1", "ace", and "pielou". Each of these metrics furnishes distinct insights into the species richness and evenness characteristics in the microbiome samples.

For those functions performing alpha diversity analysis, they all include an `alpha.obj` parameter, which accepts a matrix of alpha diversity measures (row - samples, column - measures). `mStat_calculate_alpha_diversity` could be used to generate the common alpha diversity measures. If `alpha.obj` is NULL, `mStat_calculate_alpha_diversity` will be called autonomously. To speed up computation, we recommend calling `mStat_calculate_alpha_diversity` once and store the alpha diversity measures in an object, which can be used later repeatedly.

To note, `mStat_calculate_alpha_diversity` does not perform rarefaction. Rarefaction is important in diversity analysis since this process ensures the datasets are rendered more comparable by equalizing the sequencing depth across samples. Such standardization is vital for comparative analyses. You can use `mStat_rarefy_data` to rarefy our data.

The first step in this process involves understanding how to test for differences in alpha diversity across timepoints and/or groups. To this end, MicrobiomeStat provides the `generate_alpha_test_pair()` function. This function fits a linear mixed model to detect changes in alpha diversity between time points and the difference of the changes between groups. The model takes the time variable, group variable, and any additional adjustment variables as fixed effects, and the subject variable as a random effect. The function generates a list of coefficient tables, one for each alpha diversity index. These tables present the term, estimate, standard error, t-value, and p-value for each fixed effect in the model.

Here is an example of its application:

```r
data(peerj32.obj)

generate_alpha_test_pair(
   data.obj = peerj32.obj,
   alpha.obj = NULL,
   time.var = "time",
   alpha.name = c("shannon","observed_species"),
   subject.var = "subject",
   group.var = "group",
   adj.vars = "sex"
)
```

The output of this function is a list of summary tables for each alpha diversity measure tested. Each table contains columns for Term (variable name), Estimate (coefficient), Std.Error, Statistic (t or F), and P.Value.

Here is an example of what the output might look like:

<table><thead><tr><th>Term</th><th width="121">Estimate</th><th width="133">Std.Error</th><th width="144">Statistic</th><th>P.Value</th></tr></thead><tbody><tr><td>(Intercept)</td><td>3.53</td><td>0.0372</td><td>95.0</td><td>1.25e-43</td></tr><tr><td>groupPlacebo</td><td>0.0994</td><td>0.0436</td><td>2.28</td><td>2.87e-2</td></tr><tr><td>time2</td><td>0.0589</td><td>0.0433</td><td>1.36</td><td>1.88e-1</td></tr><tr><td>sexmale</td><td>-0.0548</td><td>0.0353</td><td>-1.55</td><td>1.37e-1</td></tr><tr><td>groupPlacebo:time2</td><td>-0.0548</td><td>0.0542</td><td>-1.01</td><td>3.25e-1</td></tr></tbody></table>

In this example, we are particularly interested in testing whether there are time effects ("time2" term), i.e., whether the alpha diversity index changes over the two time points, and wether the changes differ by groups ("groupPlacebo:time2" interaction term). An omnibus p-value is also provided to test the null hypothesis of no group effect at both time points (i.e., the coefficients for "groupPlacebo" and "groupPlacebo:time2" are both zeros).

If the major interest is to test whether the time changes differ by groups, MicrobiomeStat provides the `generate_alpha_change_test_pair()` function to directly test the changes in relation to the group variable. One advantage of this function is the permission of flexible defintion of alpha diversity change while the linear mixed model implicitly uses the absolute change. The function `generate_alpha_change_test_pair` includes a parameter `alpha.change.func` that allows you to specify how the change in alpha diversity is calculated. By default, the function calculates the 'absolute change', which represents the difference between 't2' and 't1'. You can also use 'log fold change'. Or you can define your own change via `alpha.change.func`. For instance, you might want to define the ratio of alpha diversity at the 't2' to 't1' as the change. Here's an example of how you can do this:

```r
# Define custom function
change_ratio <- function(time_2, time_1) {
  return(time_2 / time_1)
}
```

In this case, the function 'change\_ratio' is defined to calculate the ratio of alpha diversity at `time_2` to `time_1`. Once defined, you can pass 'change\_ratio' to the `alpha.change.func` parameter in the `generate_alpha_change_test_pair` function. To note, currently the function does not account for time-varying covariates. If you need to control the effects of time-varying covariates, you may need to use the mixed model approach.

Let's see an example of its application:

```r
library(vegan)
data(peerj32.obj)

generate_alpha_change_test_pair(
  data.obj = peerj32.obj,
  alpha.obj = NULL,
  alpha.name = c("shannon","observed_species"), 
  depth = NULL,
  time.var = "time",
  subject.var = "subject",
  group.var = "group",
  adj.vars = "sex",
  alpha.change.func = "absolute change",
  change.base = "1"  
)
```

The output of this function is a list of summary tables for each alpha diversity measure tested. Each table contains columns for Term (variable name), Estimate (coefficient), Std.Error, Statistic (t or F), and P.Value.

Here is an example of what the output might look like:

<table><thead><tr><th>Term</th><th width="128">Estimate</th><th width="141">Std.Error</th><th>Statistic</th><th>P.Value</th></tr></thead><tbody><tr><td>(Intercept)</td><td>0.0174</td><td>0.0140</td><td>1.24</td><td>0.230</td></tr><tr><td>sexmale</td><td>-0.000390</td><td>0.0164</td><td>-0.0238</td><td>0.981</td></tr><tr><td>groupPlacebo</td><td>-0.0154</td><td>0.0158</td><td>-0.975</td><td>0.342</td></tr></tbody></table>

To visually explore alpha diversity changes, MicrobiomeStat facilites visualizing both time points via `generate_alpha_boxplot_long` function or visualizing the changes via `generate_alpha_change_boxplot_pair`. The `generate_alpha_boxplot_long` function is developed for general longitudinal data with multiple time points. As a special case, it can be applied to the paired samples case by specifying the start time point (`t0.level`) and the end time point (`ts.level`). The function generates an alpha diversity boxplot, with lines connecting the dots representing the same subject. These lines provide a visual of how individual subjects' alpha diversity changes over time.

Here's how you can use this function:

```r
generate_alpha_boxplot_long(
  data.obj = peerj32.obj,
  alpha.obj = NULL,
  alpha.name = c("shannon","observed_species"),
  depth = NULL,
  subject.var = "subject",
  time.var = "time",
  t0.level = "1",
  ts.levels = "2",
  group.var = "group",
  strata.var = "sex",
  base.size = 20,
  theme.choice = "bw",
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FoqUKYfwmAlrGZ8OuYBJF%2FScreenshot%202023-10-11%20at%2014.37.51.png?alt=media&amp;token=348dc92b-4a2b-4f50-8684-0b6d22c47b6d" alt=""><figcaption></figcaption></figure>

In addition, MicrobiomeStat provides the `generate_alpha_change_boxplot_pair` function, which allows the exploration of the changes in relation to the group variable with or without stratification. The function is specifically designed for paired samples designs. Here's an example of its usage:

```r
generate_alpha_change_boxplot_pair(
   data.obj = peerj32.obj,
   alpha.obj = NULL,
   alpha.name = c("shannon","observed_species"),
   depth = NULL,
   subject.var = "subject",
   time.var = "time",
   group.var = "group",
   strata.var = "sex",
   change.base = "1",
   alpha.change.func = "log fold change",
   base.size = 20,
   theme.choice = "bw",
   palette = NULL,
   pdf = TRUE,
   file.ann = "test",
   pdf.wid = 11,
   pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FsQtg0HyFro16Ui2ozDnz%2FScreenshot%202023-10-11%20at%2014.39.14.png?alt=media&amp;token=a02eb613-3c73-4baa-a379-ffd9c368b3c3" alt=""><figcaption></figcaption></figure>


# Beta Diversity Analysis

Welcome to this tutorial on Beta Diversity Analysis within Paired Samples. Our focus here is to understand the variations in microbial community structure and composition across different groups and within individual subjects over time. We aim to identify patterns and extract meaningful insights from microbiome data using various functions provided by MicrobiomeStat.

For those beta diversity-based functions, they all have a `dist.obj` parameter, which accepts a list of distance matrices. If the parameter is not specified, `mStat_calculate_beta_diversity` will be automatically called. MicrobiomeStat supports "BC" (Bray-Curtis), "Jaccard", "UniFrac" (unweighted), "GUniFrac" (generalized), "WUniFrac" (weighted), and "JS" (Jensen-Shannon divergence). The user can create his own list of distance matrices and pass it to `dist.obj`. We recommend the user to create a list of distance matrices once in the analysis and then use it repeatedly.

In beta diversity-based visualization functions as well as those testing functions based on changes, when covariates (`adj.vars`) are presented, the covariate effects will be removed using `mStat_calculate_adjusted_distance` function. The method used is referenced below. However, we recommend the user to perform covariate adjustment explicitly and store the adjusted beta diversity object for future repeated use.

> Shi, Y., Zhang, L., Do, K. A., Peterson, C. B., & Jenq, R. R. (2020). aPCoA: covariate adjusted principal coordinates analysis. Bioinformatics, 36(13), 4099-4101. PMID: 32339223 PMCID: PMC7332564.

This process ensures the extracted microbial patterns are not confounded by the specified covariates, thus presenting a cleaner representation of the microbial community structure.

Based on the distance matrices, we can also extract the first several principal coordinates (PCs), which capture the main variation in the data. PCs can be calculated by calling `mStat_calculate_PC` function. While users are free to select between "mds" and "nmds" as their ordination method, in scenarios where `pc.obj` is not provided beforehand, the toolkit defaults to the "mds" method. Researchers favoring advanced ordination techniques like t-SNE or UMAP can employ external tools to compute results. For those PC-based functions, they all have a `pc.obj` parameter, which accepts a list of PC matrices based on a variety of beta diversity measures. If the parameter is not specified, `mStat_calculate_PC` will be called automatically. Or the users can create their own list of PC matrices and pass it to `pc.obj`. We recommend the user to create the list once in the analysis and use it repeatedly.

We begin our analysis by statistically testing beta diversity differences using the `generate_beta_change_test_pair()` function. This function fits linear models where the dependent variable is the distance between two time points from the same subject in a paired samples design, relating these beta diversity measures to the grouping variable and covariates.

```r
generate_beta_change_test_pair(
  data.obj = peerj32.obj,
  dist.obj = NULL,
  time.var = "time",
  subject.var = "subject",
  group.var = "group",
  adj.vars = c("sex"),
  change.base = "1",
  dist.name = c('BC', 'Jaccard') 
)
```

The function returns coefficient tables with p-values for assessing associations with each beta diversity measure. These tables enable rigorous hypothesis testing complementing visualization for paired samples designs.

<table><thead><tr><th width="134">Distance</th><th>Term</th><th>Estimate</th><th>Std.Error</th><th>Statistic</th><th>P.Value</th></tr></thead><tbody><tr><td>BC</td><td>(Intercept)</td><td>0.175</td><td>0.0186</td><td>9.42</td><td>8.24e-12</td></tr><tr><td>BC</td><td>sexmale</td><td>0.0671</td><td>0.0217</td><td>3.09</td><td>3.58e-3</td></tr><tr><td>BC</td><td>groupPlacebo</td><td>-0.0157</td><td>0.0210</td><td>-0.746</td><td>4.60e-1</td></tr></tbody></table>

<table><thead><tr><th width="123">Distance</th><th>Term</th><th>Estimate</th><th>Std.Error</th><th>Statistic</th><th>P.Value</th></tr></thead><tbody><tr><td>Jaccard</td><td>(Intercept)</td><td>0.294</td><td>0.0246</td><td>12.0</td><td>6.04e-15</td></tr><tr><td>Jaccard</td><td>sexmale</td><td>0.0853</td><td>0.0288</td><td>2.96</td><td>5.06e-3</td></tr><tr><td>Jaccard</td><td>groupPlacebo</td><td>-0.0207</td><td>0.0279</td><td>-0.744</td><td>4.61e-1</td></tr></tbody></table>

Next, we explore the `generate_beta_ordination_pair()` function. This function generates ordination plots based on the microbial community structures of samples.

```r
generate_beta_ordination_pair(
  data.obj = peerj32.obj,
  dist.obj = NULL,
  pc.obj = NULL,
  subject.var = "subject",
  time.var = "time",
  group.var = "group",
  strata.var = "sex",
  dist.name = c("BC"),
  base.size = 16,
  theme.choice = "bw",
  custom.theme = NULL,
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FKC924UlrmQ5kz8EjWDcq%2FScreenshot%202023-10-11%20at%2015.07.10.png?alt=media&amp;token=aee36a01-5ee3-4f38-a452-ba7291ed9c6c" alt=""><figcaption></figcaption></figure>

The `generate_beta_change_boxplot_pair()` function is another tool that aids in beta diversity-based visualization. This function quantifies the beta diversity changes within individual subjects over time.

```r
generate_beta_change_boxplot_pair(
  data.obj = peerj32.obj,
  dist.obj = NULL,
  subject.var = "subject",
  time.var = "time",
  group.var = "group",
  strata.var = "sex",
  change.base = "1",
  dist.name = c('BC'),
  base.size = 16,
  theme.choice = "bw",
  custom.theme = NULL,
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FYW2dsUlDBH37W3HSz2g1%2FScreenshot%202023-10-11%20at%2015.08.07.png?alt=media&amp;token=b3d82364-df0e-48d3-ad62-e023cee95646" alt=""><figcaption></figcaption></figure>

The `generate_beta_pc_change_boxplot_pair()` function provides the functionality to explore the differences in specific ordination Axes between different groups. The `pc.ind` parameter is used to specify which Principal Coordinates (PCs) or axes to analyze after conducting a Multidimensional Scaling (MDS) or Nonmetric Multidimensional Scaling (NMDS).

```r
generate_beta_pc_change_boxplot_pair(
  data.obj = peerj32.obj,
  dist.obj = NULL,
  pc.obj = NULL,
  pc.ind = c(1, 2),
  subject.var = "subject",
  time.var = "time",
  group.var = "group",
  strata.var = "sex",
  change.base = "1",
  change.func = "absolute change",
  dist.name = c('BC'),
  base.size = 20,
  theme.choice = "bw",
  custom.theme = NULL,
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FGGCM4P1idDhDiCIwWAnT%2FScreenshot%202023-10-11%20at%2015.09.03.png?alt=media&amp;token=3ee11ce8-c5ba-4908-ab7b-ee316700e5cc" alt=""><figcaption></figcaption></figure>

Lastly, the `generate_beta_pc_boxplot_long()` function traces the trajectory of each subject's beta diversity across two time points on specific ordination axes. However, when the number of subjects is large, the individual connection lines can become too cluttered, making the plot difficult to interpret. To address this, we have set a threshold: when the number of subjects (`n_subjects`) exceeds 25, the individual connection lines are replaced with overall connection lines, improving the clarity and readability of the plot.

```r
generate_beta_pc_boxplot_long(
  data.obj = peerj32.obj,
  dist.obj = NULL,
  pc.obj = NULL,
  subject.var = "subject",
  time.var = "time",
  t0.level = "1",
  ts.levels = "2",
  group.var = "group",
  strata.var = "sex",
  dist.name = c('BC'),
  base.size = 20,
  theme.choice = "bw",
  custom.theme = NULL,
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FrcMcut3U0mhU9G2LJNSL%2FScreenshot%202023-10-11%20at%2015.10.07.png?alt=media&amp;token=aa1dbf57-3d9e-4460-b404-ce02ca155692" alt=""><figcaption></figcaption></figure>


# Feature-level Analysis

In feature-level data analysis for paired samples design, the major tasks include identifying (1) features that change over time, (2) features that are differenital between groups over time, and (3) features whose changes over time differ between groups. Features in (3) are a subset of features in (2). These tasks can be achieved by `generate_taxa_test_single` and `generate_taxa_change_test_pair`. The `generate_taxa_test_pair` function performs differential abundance analysis (DAA) based on compositional data using the mixed effects mode of LinDA, which is a DAA method based on log linear model with bias correction due to compositional effects. If the data are not compositional, standard linear mixed effects model (lme4) will be used.

> Zhou H, He K, Chen J, Zhang X. LinDA: linear models for differential abundance analysis of microbiome compositional data. Genome Biol. 2022 Apr 14;23(1):95. doi: 10.1186/s13059-022-02655-5. PMID: 35421994; PMCID: PMC9012043.

### Categorical vs Continuous Predictors

The `generate_taxa_test_pair` function automatically distinguishes between categorical and continuous predictor variables for the `group.var` parameter:

* **Categorical variables** (factor/character): Creates pairwise comparisons vs. the reference level (e.g., "Treatment vs Placebo (Reference) \[Main Effect]" and "\[Interaction]" effects)
* **Continuous variables** (numeric/integer): Tests linear association with the variable

This automatic detection allows the same function to handle both types of predictors appropriately.

The `ref.level` parameter allows you to explicitly specify the reference level for categorical `group.var`. By default, R uses the first level of the factor as the reference. Setting `ref.level` overrides this behavior, which is useful when you want to compare against a specific control group.

### Data Type Handling

In the `generate_taxa_test_pair` function, the `feature.dat.type` parameter specifies the data type in the feature matrix. Depending on the data type, different preprocessing steps and methods are used.

* `count` and `proportion`: For count and proportion data, which are both compositional, `linda` will be called. To address zeros, a pseudo-count of 0.5 is added to the count data, and zeros are substituted with half of the nonzero minimum for proportion data (feature-wise). Winorization at 97% quantile is performed to reduce the influence of outliers.
* `other`: When `feature.dat.type` is set to "other", the data are considered to be non-compositional and standard linear mixed effects model will be used. Users need to determine the appropriate normalization and transformation of the data before running the function. This option increases the applicability of MicrobiomeStat to other data types.

The `prev.filter` and `abund.filter` parameters filter taxa based on their prevalence and average relative abundance, so those rare and less abundant taxa will be excluded from testing. As the statistical power for these rare/less abundant taxa tends to be low, excluding them can reduce multiple testing burden.

The `feature.level` determines what aggregation level(s) the tests will be performed. If `feature.level` is set to "original", the original features in `feature.tab` will be tested. The `feature.level` can also be set to the aggregated levels specified in the `feature.ann` matrix.

The `generate_taxa_test_pair` outputs a table of LinDA association statistics for all tested taxa/features. The table contains the following components:

* `Variable`: It identifies the taxon/feature being analyzed.
* `Coefficient`: Expressed as log2FoldChange, bias-corrected. It indicates the degree and direction of change in the abundance of a specific taxon/feature.
* `SE`: Standard errors of the coefficients. It measures the variability of the coefficient estimates.
* `Mean Abundance`: The average abundance of a particular taxon/feature across all samples.
* `Prevalence`: The proportion of samples where a specific taxon/feature is present.

The `generate_taxa_change_test_pair` function contains an additional parameter `feature.change.func`, which specifies the method or function used to compute the change between the two time points. The options include:

* `"relative change"` (default): Computes the relative change as `(value_time_2 - value_time_1) / (value_time_2 + value_time_1)`. If both time points have 0 values, the change is defined as 0.
* `"absolute change"`: Computes the absolute difference between the values at the two time points (`value_time_2 - value_time_1`).
* `"log fold change"`: Computes the log2 fold change between the two time points.
* A custom function: If a user-defined function is provided to calculate the change, it should take two numeric vectors as input corresponding to the values at the two time points (`value_time_1` and `value_time_2`) and return a numeric vector of the computed changes.

Results from both functions can be visualized using `generate_taxa_volcano_single`, will produce a volcano plot. It visualizes the relationship between the effect size (log foldchange) and its statistical significance. The function has the `feature.sig.level` and `feature.mt.method` parameters:

* `feature.sig.level`: This parameter determines the significance level, influencing the position of the dashed lines in the volcano plot. It sets the threshold for distinguishing between significant and non-significant differences.
* `feature.mt.method`: This parameter determines whether the adjusted p-values or raw p-values will be plotted. Available options: "fdr" (false discovery rate), "bonferroni", and "none" (raw p-value).

By understanding and appropriately setting these parameters, users can ensure a more accurate and contextually relevant interpretation of the plotted results.

```r
#' Load the dataset
data(peerj32.obj)

#' Perform the differential abundance test
test.list <- generate_taxa_test_pair(
  data.obj = peerj32.obj,
  subject.var = "subject",
  time.var = "time",
  change.base = "1",
  group.var = "group",
  adj.vars = c("sex"),
  feature.level = c("Genus"),
  prev.filter = 0.1,
  abund.filter = 0.0001,
  feature.dat.type = "count"
)

#' Generate the volcano plot
plot.list <- generate_taxa_volcano_single(
  data.obj = peerj32.obj,
  group.var = "group",
  test.list = test.list,
  feature.sig.level = 0.1,
  feature.mt.method = "none"
)

plot.list
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FvDScCOi9DITEKqWqp7ro%2FScreenshot%202023-10-11%20at%2016.07.17.png?alt=media&amp;token=d8e42bf1-fca3-41ce-883a-0d8aaa931e4e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FnrORQ3eGD7FQqkgcteie%2FScreenshot%202023-10-11%20at%2016.07.38.png?alt=media&amp;token=797f461e-dd1f-491c-9ca8-71400633af41" alt=""><figcaption></figcaption></figure>

For specific comparisons, labels like `$Genus$Placebo vs LGG (Reference) [Main Effect]` and `$Genus$Placebo vs LGG (Reference) [Interaction]` may appear.

* The `[Main Effect]` label indicates the primary difference in taxa abundance between the compared groups at the baseline.
* The `[Interaction]` label reveals the interaction between group differences and time variable, i.e., whether the group difference changes with the time.

If the aim is to specifically investigate the shifts in taxa abundance between the two time points, the `generate_taxa_change_test_pair()` function can be used. This function employs a linear model (lm) to evaluate the changes in taxa abundance in relation to a grouping variable.

```r
# Generate taxa change test pair
test.list <- generate_taxa_change_test_pair(
  data.obj = peerj32.obj,
  subject.var = "subject",
  time.var = "time",
  group.var = "group",
  adj.vars = c("sex"),
  change.base = "1",
  feature.change.func = "log fold change",
  feature.level = "Genus",
  prev.filter = 0.01,
  abund.filter = 0.001,
  feature.dat.type = "count"
)

# Generate the volcano plot
plot.list <- generate_taxa_volcano_single(
  data.obj = peerj32.obj,
  group.var = "group",
  test.list = test.list,
  feature.sig.level = 0.1,
  feature.mt.method = "none"
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FKot69QHP7XB4dg0HmEKc%2FScreenshot%202023-10-11%20at%2016.37.16.png?alt=media&amp;token=6c879584-570e-4db1-9c6e-d7b90a8dcdd4" alt=""><figcaption></figcaption></figure>

The results enable researchers to recognize taxa that exhibit notable changes in abundance across time points, and to determine whether these changes differ by group. In the following sections, we will demonstrate how to visualize taxa of interest such as those from the differential abundance analysis using various visualization tools.

First, let us look at `generate_taxa_indiv_boxplot_long()`:

```r
generate_taxa_indiv_boxplot_long(
   data.obj = peerj32.obj,
   subject.var = "subject",
   time.var = "time",
   t0.level = "1",
   ts.levels = "2",
   group.var = "group",
   strata.var = "sex",
   feature.level = c("Genus"),
   feature.dat.type = "count",
   features.plot = NULL,
   top.k.plot = NULL,
   top.k.func = NULL,
   transform = "log",
   prev.filter = 0.1,
   abund.filter = 0.001,
   base.size = 20,
   theme.choice = "bw",
   custom.theme = NULL,
   palette = NULL,
   pdf = TRUE,
   file.ann = NULL,
   pdf.wid = 11,
   pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FdJMOPDNO5QGC52s1qA0Q%2FScreenshot%202023-10-11%20at%2016.50.17.png?alt=media&amp;token=926fded6-a839-4463-869e-cf50d5d86df1" alt=""><figcaption></figcaption></figure>

This function creates a series of boxplots, one for each taxon, and outputs them into a multi-page PDF. Several parameters in this function and other related functions are noteworthy.

* `feature.dat.type`: One of "count", "proportion" or "other". For "count", the data will be converted to proportion data before the visualization.
* `t0.level`: the name of the baseline level ("t1") or the first time point.
* `ts.levels`: a character vector of the names of other levels to be visualized. In the paired samples setting, `ts.levels` can be the name of the second time point ("t2")
* `transform`: This parameter indicates the transformation to apply to the abundance data when plotting. Transformations are only applied when the `feature.dat.type` is set to either "count" or "proportion". When `feature.dat.type` is "other", no transformation will be performed. User should determine the appropriate transformation to better visualize the data. The available options for `transform` include:
  * `"sqrt"`: Square root transformation (default)
  * `"identity"`: No transformation
  * `"log"`: Logarithmic transformation. Zeros are replaced with half of the non-zero minimum for each taxon before log transformation.
* `feature.level`: Specifiy which level of the data to be plotted.
* `features.plot`: This parameter can be used in all feature-level visualization functions to specify which taxa or features should be visualized. This is particularly useful for focusing on the results of differential abundance analyses. When you provide a vector of taxa or feature names to `features.plot`, this will directly select these features for visualization, overriding any settings in `prev.filter` and `abund.filter`. By using this parameter, you can directly highlight and examine the taxa or features that are significantly different in abundance across your comparisons.
* `top.k.plot` and `top.k.func`: In many scenarios, especially when navigating through expansive datasets, you may want to focus on a select subset of taxa that stand out either due to their high abundance or large variability. `top.k.plot` lets you visualize the top k taxa/features based on the criterion you selected in `top.k.func`, which have four choices:
  * `"mean"`: Highlights taxa with the highest average abundances across samples.
  * `"sd"`: Selects taxa with the greatest variability (standard deviation) across samples, useful for identifying taxa with notable differences under varying conditions.
  * `"prevalence"`: Chooses taxa with the highest occurrence across samples, targeting those most consistently present.
  * `top.k.func` can also accept a user-defined function so that the users can rank taxa based on their own criterion. The user-defined function should take the abundance matrix (those in `feature.tab` and `feature.agg.list`) as the input and returns a numeric vector of the feature importance values. This allows for criteria beyond "mean", "sd", or "prevalence".

The `generate_taxa_boxplot_long()` places all taxa onto a single page, providing an overview of all your taxa at once.

```r
generate_taxa_boxplot_long(
   data.obj = peerj32.obj,
   subject.var = "subject",
   time.var = "time",
   t0.level = "1",
   ts.levels = "2",
   group.var = "group",
   strata.var = "sex",
   feature.level = c("Genus"),
   feature.dat.type = "count",
   features.plot = NULL,
   top.k.plot = 8,
   top.k.func = "mean",
   transform = "log",
   prev.filter = 0.1,
   abund.filter = 0.001,
   base.size = 16,
   theme.choice = "bw",
   custom.theme = NULL,
   palette = NULL,
   pdf = TRUE,
   file.ann = NULL,
   pdf.wid = 11,
   pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FrnMrRkHLNhxY99CQWok0%2FScreenshot%202023-10-11%20at%2016.52.12.png?alt=media&amp;token=085d8181-30fa-4db9-97d2-5230c36daec7" alt=""><figcaption></figcaption></figure>

Next, we present two key functions, `generate_taxa_indiv_change_boxplot_pair()` and `generate_taxa_change_boxplot_pair()`, for visualizing the changes from "t1" to "t2".

```r
generate_taxa_indiv_change_boxplot_pair(
   data.obj = peerj32.obj,
   subject.var = "subject",
   time.var = "time",
   group.var = "group",
   strata.var = "sex",
   change.base = "1",
   feature.change.func = "log fold change",
   feature.level = c("Genus"),
   feature.dat.type = "count",
   features.plot = NULL,
   top.k.plot = NULL,
   top.k.func = NULL,
   prev.filter = 0.1,
   abund.filter = 0.001,
   base.size = 20,
   theme.choice = "bw",
   custom.theme = NULL,
   palette = NULL,
   pdf = TRUE,
   file.ann = NULL,
   pdf.wid = 11,
   pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FvwdMD8ep6wIgZZMiwQEP%2FScreenshot%202023-10-11%20at%2018.18.32.png?alt=media&amp;token=387c494b-0e93-4ede-9600-fc040734208b" alt=""><figcaption></figcaption></figure>

```r
generate_taxa_change_boxplot_pair(
   data.obj = peerj32.obj,
   subject.var = "subject",
   time.var = "time",
   group.var = "group",
   strata.var = "sex",
   change.base = "1",
   feature.change.func = "log fold change",
   feature.level = c("Genus"),
   feature.dat.type = "count",
   features.plot = NULL,
   top.k.plot = 8,
   top.k.func = "sd",
   prev.filter = 0.1,
   abund.filter = 0.001,
   base.size = 20,
   theme.choice = "bw",
   custom.theme = NULL,
   palette = NULL,
   pdf = TRUE,
   file.ann = NULL,
   pdf.wid = 11,
   pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FKJ8VKRqeCWbxoVNVH6Qh%2FScreenshot%202023-10-11%20at%2018.20.52.png?alt=media&amp;token=1760c2bb-d4f8-4251-b5a8-c82ff05aca08" alt=""><figcaption></figcaption></figure>

The `generate_taxa_barplot_pair` function will generate stacked bar plots of taxa. In each sample pair, the same taxa are connected by lines to track their abundance changes. The function outputs both individual and averaged bar plots. The function has an important parameter `feature.number`.

* `feature.number`: This parameter determines the maximum number of taxa/features that will be visualized directly in the barplot. For datasets with numerous features, it's practical to limit to the most abundant or significant taxa, ensuring that the visualization remains informative and isn't cluttered. When the number of taxa surpasses the value defined in `feature.number`, the function aggregates low-abundance taxa into a collective category labeled "other". This means, for instance, if there are over 20 features in the dataset but `feature.number` is set to 20, the least abundant features that exceed this count will be collectively presented as "other" in the visualization. This approach ensures that the chart remains legible, highlighting the most dominant features, while still accounting for the contributions of less abundant taxa.

```r
generate_taxa_barplot_pair(
  data.obj = peerj32.obj,
  subject.var = "subject",
  time.var = "time",
  group.var = "group",
  strata.var = "sex",
  feature.level = "Genus",
  feature.dat.type = c("count"),
  feature.number = 30,
  base.size = 10,
  theme.choice = "bw",
  custom.theme = NULL,
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FIbeDV2xI5bOvtI88lMtv%2FScreenshot%202023-10-11%20at%2018.23.36.png?alt=media&amp;token=b1d8448a-7105-400c-9d88-4c29bde310d8" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FdkfhWQwC1yUolmxEmcLT%2FScreenshot%202023-10-11%20at%2018.24.47.png?alt=media&amp;token=27306533-43a7-40d0-afc2-ca2c536e2de0" alt=""><figcaption></figcaption></figure>

The function `generate_taxa_dotplot_pair()` depicts the mean abundance and prevalence across times and groups. The two time points are visualized together for easy comparison.

```r
generate_taxa_dotplot_pair(
  data.obj = peerj32.obj,
  subject.var = "subject",
  time.var = "time",
  group.var = "group",
  strata.var = "sex",
  feature.level = c("Family"),
  feature.dat.type = "count",
  features.plot = NULL,
  top.k.plot = NULL,
  top.k.func = NULL,
  prev.filter = 0.01,
  abund.filter = 0.01,
  base.size = 16,
  theme.choice = "bw",
  custom.theme = NULL,
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 45,
  pdf.hei = 8.5
)
```

<figure><img src="https://content.gitbook.com/content/hFAmY4z7d1R15Cv49vXQ/blobs/J5hTRkGjLUkcaOHJMjo2/Screenshot%202023-06-12%20at%2020.34.39.png" alt=""><figcaption></figcaption></figure>

The `generate_taxa_change_dotplot_pair()` function visualizes the mean abundance change and prevalence change across groups:

```r
generate_taxa_change_dotplot_pair(
  data.obj = peerj32.obj,
  subject.var = "subject",
  time.var = "time",
  group.var = "group",
  strata.var = NULL,
  change.base = "2",
  feature.change.func = "log fold change",
  feature.level = "Family",
  feature.dat.type = "count",
  features.plot = NULL,
  top.k.plot = NULL,
  top.k.func = NULL,
  prev.filter = 0.001,
  abund.filter = 0.01,
  base.size = 16,
  theme.choice = "bw",
  custom.theme = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FrpfUKl4oKINQB3iUjMIl%2FScreenshot%202023-10-08%20at%2021.12.29.png?alt=media&amp;token=bf0c788b-3f60-4ceb-ae8e-c49f90469940" alt=""><figcaption></figcaption></figure>

The `generate_taxa_heatmap_pair()` function creates a heatmap of paired smaples. Here is an example:

```r
generate_taxa_heatmap_pair(
   data.obj = peerj32.obj,
   subject.var = "subject",
   time.var = "time",
   group.var = "group",
   strata.var = "sex",
   feature.level = c("Family"),
   feature.dat.type = "count",
   features.plot = NULL,
   top.k.plot = NULL,
   top.k.func = NULL,
   prev.filter = 0.1,
   abund.filter = 0.001,
   base.size = 12,
   custom.theme = NULL,
   palette = NULL,
   pdf = TRUE,
   file.ann = NULL,
   pdf.wid = 11,
   pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FGn9Vw3PsIqWIeLU5h0AK%2FScreenshot%202023-10-08%20at%2021.21.36.png?alt=media&amp;token=761e126a-d221-4e9d-9e6e-35754012c92f" alt=""><figcaption></figcaption></figure>

Heatmaps are particularly insightful for discerning clusters of microbial families that exhibit similar abundance profiles across different samples. Heatmaps are particularly insightful for discerning clusters of taxa/features that exhibit similar abundance profiles across amples. By default, the function will only cluster rows (taxa/features) based on their abundance patterns. The columns are ordered by `group.var` and `strata.var`. If users wish to see the taxa in their original order without clustering, they can achieve this by setting `cluster.rows = FALSE`. The function also allows for column clustering by setting `cluster.cols = TRUE`, which can be instrumental in revealing groups of samples with similar abundance profiles. Note that when `feature.dat.type` is "count” or "proportion", the data will be visualized using proportions. For "other" type, the original scale will be used.

The `generate_taxa_change_heatmap_pair()` function helps assist in analyzing patterns of changes:

```
generate_taxa_change_heatmap_pair(
   data.obj = peerj32.obj,
   subject.var = "subject",
   time.var = "time",
   group.var = "group",
   strata.var = "sex",
   change.base = "1",
   feature.change.func = "relative change",
   feature.level = "Family",
   feature.dat.type = "count",
   features.plot = NULL,
   top.k.plot = NULL,
   top.k.func = NULL,
   prev.filter = 0.1,
   abund.filter = 0.001,
   base.size = 12,
   palette = NULL,
   cluster.rows = NULL,
   cluster.cols = FALSE,
   pdf = TRUE,
   file.ann = NULL,
   pdf.wid = 11,
   pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FTQjf1NxOMMvjPPeEtaaM%2FScreenshot%202023-10-08%20at%2021.30.23.png?alt=media&amp;token=1199e863-6130-4dca-a100-f8884ad3a651" alt=""><figcaption></figcaption></figure>

## Scatterplot Visualizations

The `generate_taxa_change_scatterplot_pair()` function creates scatterplots showing the change in taxa abundance between two time points. This visualization is particularly useful for identifying taxa with large changes and understanding the direction of change across groups.

```r
generate_taxa_change_scatterplot_pair(
  data.obj = peerj32.obj,
  subject.var = "subject",
  time.var = "time",
  group.var = "group",
  strata.var = "sex",
  change.base = "1",
  feature.change.func = "log fold change",
  feature.level = c("Family"),
  feature.dat.type = "count",
  features.plot = NULL,
  top.k.plot = 10,
  top.k.func = "mean",
  prev.filter = 0.1,
  abund.filter = 0.001,
  base.size = 16,
  theme.choice = "bw",
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5
)
```

The `feature.change.func` parameter supports several methods for computing change:

* `"absolute change"`: Simple difference between time points
* `"log fold change"`: Log2 fold change (with automatic zero imputation)
* `"relative change"`: Relative change as (ts - t0) / (ts + t0)

For individual-level visualization, the `generate_taxa_indiv_change_scatterplot_pair()` function shows taxa changes for each subject:

```r
generate_taxa_indiv_change_scatterplot_pair(
  data.obj = peerj32.obj,
  subject.var = "subject",
  time.var = "time",
  group.var = "group",
  strata.var = NULL,
  change.base = "1",
  feature.change.func = "log fold change",
  feature.level = c("Genus"),
  features.plot = NULL,
  feature.dat.type = "count",
  top.k.plot = 6,
  top.k.func = "sd",
  prev.filter = 0.1,
  abund.filter = 0.001,
  base.size = 16,
  theme.choice = "bw",
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 20,
  pdf.hei = 8.5
)
```

These scatterplot functions complement the boxplot and heatmap visualizations by providing a different perspective on taxa abundance changes in paired samples.


# One-Click Reports Generation

MicrobiomeStat provides automated solutions for integrated analysis reporting in paired samples microbiome studies.

MicrobiomeStat provides an efficient solution by generating integrated reports for paired samples studies. These reports include:

* Visualizations to illustrate key findings
* Statistical summaries that highlight significant results

The `mStat_generate_report_pair()` function generates an integrated reports. It performs:

* **Alpha diversity**: The functions `generate_alpha_test_pair()`, `generate_alpha_change_test_pair()`, `generate_alpha_boxplot_long()`, and `generate_alpha_change_boxplot_pair()` are used for this purpose.
* **Beta diversity**: This is achieved through functions including `generate_beta_change_test_pair()`, `generate_beta_ordination_pair()`, `generate_beta_change_boxplot_pair()`, `generate_beta_pc_change_boxplot_pair()`, and `generate_beta_pc_boxplot_long()`.
* **Feature-level**: This involves the use of `generate_taxa_test_pair()`, `generate_taxa_change_test_pair()`, `generate_taxa_indiv_boxplot_long()`, `generate_taxa_boxplot_long()`, `generate_taxa_indiv_change_boxplot_pair()`, `generate_taxa_change_boxplot_pair()`, `generate_taxa_barplot_pair()`, `generate_taxa_dotplot_pair()`, `generate_taxa_change_dotplot_pair()`, `generate_taxa_heatmap_pair()`, and `generate_taxa_change_heatmap_pair()`.

The function then compiles these analyses into a comprehensive PDF report. The report includes:

* A data summary from `mStat_summarize_data_obj()`
* Visual representations like alpha diversity boxplots, beta diversity ordination plots, and taxa composition visualizations
* Tables detailing statistical test results
* Commentary on key findings

Before using the function, it's important to understand the parameters:

* `data.obj`: A list object in a specific format to MicrobiomeStat, which can include components such as feature.tab (matrix), feature.ann (matrix), meta.dat (data.frame), tree, and feature.agg.list (list). This object can be converted from other formats using several functions from the MicrobiomeStat package, or constructed manually. For more detailed information on how to convert data from other formats or how to construct the `data.obj` manually, please refer to the following page.

{% content-ref url="/pages/WK9NC4ukGZbAvQGuCKUR" %}
[Creating the MicrobiomeStat Data Object](/setting-up-microbiomestat-installation-and-data-preparation/laying-the-foundation-creating-the-microbiomestat-data-object)
{% endcontent-ref %}

* Once the data has been successfully constructed, users may wish to perform minor adjustments to the data, such as removing levels with few subjects from the group.var. In such cases, you can refer to this document for guidance.

{% content-ref url="/pages/LLh6oXlfW0M2j5bSG5jU" %}
[Data Filtering](/data-manipulation-and-transformation/data-filtering)
{% endcontent-ref %}

* `group.var`: The name of the variable of primary interest.
* `test.adj.vars`: Names of columns in the metadata containing covariates to be adjusted for in statistical tests and models. Default is NULL, which indicates no covariates are adjusted for in statistical testing.
* `vis.adj.vars`: For alpha and beta diversity visualization functions, the `vis.adj.vars` parameter designates the column names in the metadata that correspond to covariates. When covariates are specified, `vis.adj.vars` will adjust the `alpha.obj` and `dist.obj` accordingly, resulting in an alpha diversity index and a distance matrix that have been modified to account for the additional covariates.
* `strata.var`: Variable to stratify the analysis by (optional).
* `subject.var`: Variable name used for subject identification.
* `time.var`: Variable name used for time points.
* `change.base`: This parameter specifies the base level for calculating changes in paired data. It is particularly useful when dealing with longitudinal data where you want to understand how different features change relative to a baseline measurement.
* `alpha.obj`: An optional list containing pre-calculated alpha diversity indices. If NULL (default), alpha diversity indices will be calculated using `mStat_calculate_alpha_diversity` function.
* `alpha.name`: The alpha diversity index to be plotted. Supported indices include "shannon", "simpson", "observed\_species", "chao1", "ace", and "pielou". If you are not interested in alpha diversity for datasets other than microbiome data, you can set this parameter to NULL. In this case, the report will not include any alpha diversity results, only feature-level analysis will be presented.
* `depth`: An integer. The sequencing depth to be used for the "Rarefy" and "Rarefy-TSS" methods. If NULL, the smallest total count across samples is used as the rarefaction depth.
* `dist.obj`: Distance matrix between samples, usually calculated using `mStat_calculate_beta_diversity` function. If NULL, beta diversity will be automatically computed from `data.obj` using `mStat_calculate_beta_diversity`.
* `dist.name`: A character vector specifying which beta diversity indices to calculate. Supported indices are "BC" (Bray-Curtis), "Jaccard", "UniFrac" (unweighted UniFrac), "GUniFrac" (generalized UniFrac), "WUniFrac" (weighted UniFrac), and "JS" (Jensen-Shannon divergence). Similar to `alpha.name`, if you do not care about beta diversity for non-microbiome data, you can set this parameter to NULL. The report will then exclude beta diversity results and only provide feature-level analysis.
* `pc.obj`: A list containing the results of dimension reduction/Principal Component Analysis. This should be the output from functions like `mStat_calculate_PC`, containing the PC coordinates and other metadata. If NULL (default), dimension reduction will be automatically performed using metric multidimensional scaling (MDS) via `mStat_calculate_PC`. The `pc.obj` list structure should contain:
  * `$points`: A matrix with samples as rows and PCs as columns containing the coordinates.
  * `$eig`: Eigenvalues for each PC dimension.
  * `$vectors`: Loadings vectors for features onto each PC.
  * Other metadata like `$method`, `$dist.name`, etc. See `mStat_calculate_PC` function for details on output format.
* `vis.feature.level`: The column name in the feature annotation matrix (feature.ann) of data.obj to use for visualization and plotting. This can be a taxonomic level like "Phylum" or "Genus" for microbiome data. For KEGG data, this could be a pathway level such as "Pathway\_L1", "Pathway\_L2", or "Pathway\_L3". If you want to avoid aggregation, you can set it to "original", and no aggregation will be performed. The selected feature level will be used to aggregate the data at the specified level in the generated visualizations.
* `test.feature.level`: The column name in the feature annotation matrix (feature.ann) of data.obj to use for testing or analytical purposes. This can be a taxonomic level like "Phylum" or "Genus" for microbiome data. For single-cell data, this could be a cell type identifier such as "CellType". For KEGG data, this could be a pathway level such as "Pathway\_L1", "Pathway\_L2", or "Pathway\_L3". If you want to avoid aggregation, you can set it to "original", and no aggregation will be performed. The selected feature level will be used to aggregate the data at the specified level for statistical tests and models.
* `feature.dat.type`: The type of the feature data, which determines how the data is handled in downstream analyses. Should be one of: "count": Raw count data, will be normalized internally. "proportion": Data that has already been normalized to proportions/percentages. "other": Other data types such as transcriptomic and metabolomic data, where the user will decide the QC, normalization, and transformation. If the user wants to normalize/transform the abundance data on his own way, he can also use this option.
* `feature.change.func`: A function or character string specifying how to calculate the change from baseline value. This allows flexible options:
  * If a function is provided, it will be applied to each row to calculate change. The function should take 2 arguments: value at timepoint t and value at baseline t0.
  * If a character string is provided, following options are supported:
    * 'relative change': (value\_t - value\_t0) / (value\_t + value\_t0)
    * 'absolute change': value\_t - value\_t0
    * 'log fold change': log2(value\_t + 1e-5) - log2(value\_t0 + 1e-5)
  * Default is 'relative change'.
  * If none of the above options are matched, an error will be thrown indicating the acceptable options or prompting the user to provide a custom function.
* `feature.box.axis.transform`: A string indicating the transformation to apply to the data before plotting. Options are:
  * "sqrt": Square root transformation (default),
  * "identity": No transformation,
  * "log": Logarithmic transformation.
* `feature.analysis.rarafy`: Logical, indicating whether to rarefy the data at the feature-level for analysis. If TRUE, the feature data will be rarefied before analysis. Default is TRUE.
* `bar.area.feature.no`: A numeric value indicating the number of top abundant features to retain in both barplot and areaplot. Features with average relative abundance ranked below this number will be grouped into 'Other'. Default 30.
* `heatmap.feature.no`: A numeric value indicating the number of top abundant features to retain in the heatmap. Features with average relative abundance ranked below this number will be grouped into 'Other'. Default 30.
* `dotplot.feature.no`: A numeric value indicating the number of top abundant features to retain in the dotplot. Features with average relative abundance ranked below this number will be grouped into 'Other'. Default 30.
* `feature.mt.method`: Character, multiple testing method for features, "fdr", "bonferroni", or "none", default is "fdr".
* `feature.sig.level`: Numeric, significance level cutoff for highlighting features, default is 0.1.
* `base.size`: Base font size for the generated plots.
* `theme.choice`: Plot theme choice. Can be one of: "prism": ggprism::theme\_prism(), "classic": theme\_classic(), "gray": theme\_gray(), "bw": theme\_bw().
* `output.file`: A character string specifying the output file name for the report. Full path can be specified, e.g., "path\_to\_your\_location/report". The file extension (.pdf or .html) will be automatically added based on the `output.format` if not already present. This parameter also determines the title of the generated report. For example, if set to "path\_to\_your\_location/my\_report", the report title will be "my\_report".
* `output.format`: A character string specifying the desired output format of the report. Must be either "pdf" or "html". Default is c("pdf", "html"), which will use the first value ("pdf") if not explicitly specified. This parameter determines whether the report will be generated as a PDF or HTML document.

Note: Before running the function, please be aware of potential compatibility issues between RStudio and LaTeX. These issues can lead to problems such as images from the RStudio Viewer appearing in unexpected locations in the PDF report. To avoid this, it's recommended to clear the current images in the RStudio Viewer before running the function. You can do this by clicking on the broom icon in the RStudio Viewer.

Now, let's see how we can implement the function:

```r
# Load the dataset
data(peerj32.obj)
data.obj = peerj32.obj

# Specify variable names
group.var = "group" # Variable used for grouping samples
subject.var = "subject" # Variable used for subject identification
time.var = "time" # Variable used for time points
strata.var = "sex" # Variable to stratify by in diversity calculations and statistical tests

# Specify diversity indices
alpha.name = c("shannon", "observed_species") # Alpha diversity indices to calculate
dist.name = c("BC",'Jaccard') # Beta diversity indices to calculate

# Specify feature levels for visualization and testing
vis.feature.level = c("Genus") # Feature levels to use for visualization
test.feature.level = c("Genus") # Feature level to use for testing

# Specify other parameters
feature.dat.type = "count" # Type of the feature data
theme.choice = "bw" # Theme choice for the plots
base.size = 18 # Base size for the plots
feature.mt.method = "none" # Multiple testing method for features
feature.sig.level = 0.1 # Significance level cutoff for highlighting features

# Specify output file
output.file = "path/to/report.pdf" # Replace with your own file path for the output report

# Specify parameters for feature retention
bar.area.feature.no = 30 # Number of top abundant features to retain in barplot and areaplot
heatmap.feature.no = 30 # Number of top abundant features to retain in heatmap
dotplot.feature.no = 30 # Number of top abundant features to retain in dotplot

# Specify optional parameters
dist.obj = NULL # Replace with a pre-computed distance matrix if available
alpha.obj = NULL # Replace with a pre-computed alpha diversity matrix if available
change.base = "1" # Base for calculating relative change
feature.change.func = "relative change" # Function for calculating feature change

# Run the function
mStat_generate_report_pair(
   data.obj = data.obj,
   group.var = group.var,
   test.adj.vars = NULL,
   vis.adj.vars = NULL,
   strata.var = strata.var,
   subject.var = subject.var,
   time.var = time.var,
   change.base = change.base,
   alpha.obj = alpha.obj,
   alpha.name = alpha.name,
   dist.obj = dist.obj,
   dist.name = dist.name,
   feature.change.func = feature.change.func,
   vis.feature.level = vis.feature.level,
   test.feature.level = test.feature.level,
   bar.area.feature.no = bar.area.feature.no,
   heatmap.feature.no = heatmap.feature.no,
   dotplot.feature.no = dotplot.feature.no,
   feature.dat.type = feature.dat.type,
   feature.mt.method = feature.mt.method,
   feature.sig.level = feature.sig.level,
   theme.choice = theme.choice,
   base.size = base.size,
   output.file = output.file
 )
```

{% hint style="info" %}
**Note:** Due to certain interactions between R and RStudio, the visualization of significant features in the boxplot section of the report may occasionally not be displayed. If you encounter this issue, a potential solution is to clear the Viewer in RStudio (by clicking on the broom icon), and subsequently reset the environment (by using the `rm(list=ls())` command or clicking on the broom icon in the Environment pane). This procedure often resolves the display issue, allowing the boxplot to render correctly.
{% endhint %}

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-f50c521166095af9ba1d42a584614c5c5f9c8892%2FmStat_generate_report_pair_example_page-0001.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-695224d5a3c3abd09efefcce550e9af2f6ef2d52%2FmStat_generate_report_pair_example_page-0002.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-6f878c0be478e1a27f890ecfcf81ef8fbce886e2%2FmStat_generate_report_pair_example_page-0003.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-cf3247801bbeeffbfa6f7db2f78c74d488953016%2FmStat_generate_report_pair_example_page-0004.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-ceb5646857e06dc17fcdcf68c45816f60e0cc2dd%2FmStat_generate_report_pair_example_page-0005.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-184d8613ab197daaaf7915358f72e572f798aac6%2FmStat_generate_report_pair_example_page-0006.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-62641fa725b47d62dafb016aa4102ff08480f4ff%2FmStat_generate_report_pair_example_page-0007.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-565b690d1baa13cbe42d3770ee62d7e51a13289c%2FmStat_generate_report_pair_example_page-0008.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-7d93d4c34398d2bf532231ab021e332dc57c9b75%2FmStat_generate_report_pair_example_page-0009.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-dd1a0a02216fc94dda4e26391c749a442ac00318%2FmStat_generate_report_pair_example_page-0010.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-5ff24a35cd3588fe3a6c6bcc249e303621959286%2FmStat_generate_report_pair_example_page-0011.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-76e1289627ad097e667b590529e1a5c7b8fb34e4%2FmStat_generate_report_pair_example_page-0012.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-20b39d0fcaf309d6e820c163bf2bb8c2df696ed0%2FmStat_generate_report_pair_example_page-0013.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-2264e07c6ee9656dcce2a8a62de40526031ca07f%2FmStat_generate_report_pair_example_page-0014.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-304069fc62421fbe8611d35555fc78424433e164%2FmStat_generate_report_pair_example_page-0015.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-77a20691a4d635e120cd4e80fe842bdc39c4a818%2FmStat_generate_report_pair_example_page-0016.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-ddc155de8ec38f74583f67d37c1dc34bd084c003%2FmStat_generate_report_pair_example_page-0017.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-2492ec8d9e50f75cf1d21a76d923973e3a7e3351%2FmStat_generate_report_pair_example_page-0018.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-dc5ffa685b7ca6591fb5199ebbb19c284643346c%2FmStat_generate_report_pair_example_page-0019.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-2345d5f8b222e2fbf84abf90450c16a443f45324%2FmStat_generate_report_pair_example_page-0020.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-527aec2b6acf5bedfbc6b5261b051763a88b2b2c%2FmStat_generate_report_pair_example_page-0021.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-93f5a1b557e684ee784a4c6f11c74fa66f82c838%2FmStat_generate_report_pair_example_page-0022.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-6a42d2bf36dac94e971a6758dc557a69a47d355d%2FmStat_generate_report_pair_example_page-0023.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-1d3dc6890f4b764bed553336a6f2a99e767194cd%2FmStat_generate_report_pair_example_page-0024.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-f513cc505508f8950b0027a8186b1faa939ac598%2FmStat_generate_report_pair_example_page-0025.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-cb8c3d7bfef30078c435ebbe283ed47f51bf7209%2FmStat_generate_report_pair_example_page-0026.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-535dd64972df3139f04577ec5d8d0dd668289a97%2FmStat_generate_report_pair_example_page-0027.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-ee94d27250734a89584861d6e84bd36d3c74430a%2FmStat_generate_report_pair_example_page-0028.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-8191d6e4c7f5a4b9a33ff5b04e7b55ba69ec4d8a%2FmStat_generate_report_pair_example_page-0029.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-3df7ddb2b5b66e06968981d4a40f283e67dc8ad0%2FmStat_generate_report_pair_example_page-0030.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-614481ed5e732c691ca951afc2cb92ded5f1cd1f%2FmStat_generate_report_pair_example_page-0031.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-f9bec003c1d934d97e5963126882211c198da5bf%2FmStat_generate_report_pair_example_page-0032.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-2cd604917f666640060e30f248567ee78f097883%2FmStat_generate_report_pair_example_page-0033.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-7327bba9190fca7f6bd246a4b76a8f05f5f8b1dc%2FmStat_generate_report_pair_example_page-0034.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-ddbec546f13f50fc9053a13361d05393f4f48ea9%2FmStat_generate_report_pair_example_page-0035.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-b3890e2bb10715c34b3cc5a9db194cf91d03a7af%2FmStat_generate_report_pair_example_page-0036.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-4d4271acd8e81ea5f013e7aa0b7915b34ac1c7cb%2FmStat_generate_report_pair_example_page-0037.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-6472874e498161d198f0eb5b329ab5433c4b9434%2FmStat_generate_report_pair_example_page-0038.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-014ce797feb041ee0892d41d8f494c531d6f478e%2FmStat_generate_report_pair_example_page-0039.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-9d970dd59dcd1e647aa62240f92ac53b639af3b8%2FmStat_generate_report_pair_example_page-0040.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-508311d8b336d0bff2fd976fbdb579dc78050d18%2FmStat_generate_report_pair_example_page-0041.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-398cb9e99627f9c4fe455b5fea76a34b934ada9f%2FmStat_generate_report_pair_example_page-0042.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-931cac2257e7cdbd3b3da1885d06437b54c3af8c%2FmStat_generate_report_pair_example_page-0043.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-09b5cbb0c7454e0cc8449e5ccc6b83f87aff3562%2FmStat_generate_report_pair_example_page-0044.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-9e73e7d267d1bea8783a56b608b097b07284c59a%2FmStat_generate_report_pair_example_page-0045.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-b0ac31cef2fc9351bb55d6206b4ef5e4cbf5e9cf%2FmStat_generate_report_pair_example_page-0046.jpg?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fgit-blob-3a7a3c1dd958bd7179836f5b007db93d5ecdba45%2FmStat_generate_report_pair_example_page-0047.jpg?alt=media" alt=""><figcaption></figcaption></figure>

{% file src="/files/psMKLzokJLXL7mcjCfGs" %}

The automated report reduces the need for manual analysis and ensures consistency. By integrating results from different analytical dimensions, it provides a comprehensive view of the data.

MicrobiomeStat equips researchers with automated workflows to quickly synthesize and report findings from paired samples studies. The standardized reports integrate multidimensional perspectives, including alpha diversity, beta diversity, and differential abundance analysis, for comprehensive insights.

The reports contain clear visualizations and statistical summaries to aid in biological interpretation and facilitate result dissemination. By automating time-consuming manual analytical tasks, MicrobiomeStat enables rapid, reproducible, and robust reporting to advance microbiome research.


# Introduction

In clinical microbiome research, longitudinal studies have been widely employed to study the microbiome's evolution over time and its relationship to an outcome of interest. By longitudinally sampling the microbiome, we have a more comprehensive and dynamic view of the microbiome, facilitating the identification of the critical temporal window when the microbiome is "in effect". Longitudinal studies also contributes to the establishment of causal effects if the microbiome change precedes the manifestation of a clinical outcome. Furthermore, by using self as a control, the effects of many variables can be efficiently controlled, increasing the power as well as reducing potential confounding for certain association analyses. MicrobiomeStat aims to achieve the following tasks in longitudinal microbiome analysis:

* **Task 1** (time effect analysis): Analyze all time points to see if the microbiome composition shows consistent changes with the time.
* **Task 2** (global null analysis)：Jointly analyze all time points (categorical) and test the global hypothesis that none of the time points is associated with a subject-level outcome. This analysis will allow the identification of taxa whose abundance variation is associated with the outcome in certain ways. The global test pools all time points and could be more powerful than testing individual time points followed by multiple testing correction. Task 3 and 4 will then help understand the details of the association for taxa that reject the global null hypothesis.
* **Task 3** (per time point analysis): Test the association of the microbiome at different time points with the outcome. This will help identify the particular time window where the association occurs or peaks.
* **Task 4** (change analysis): Test the association of the microbiome changes with the outcome. By using changes, it controls the large inter-subject variability in microbiome composition, and amplifies the association strength. It is likely that task 4 finds more associations than Task 3 with larger strength.
* **Task 5** (volatility analysis): It is possible that the average composition of the microbiome remains similar between conditions, but the variability differs by conditions. Volatility analysis will help identify the taxa whose temporal variability ("volatility") is associated with the outcome.
* **Task 6** (trend analysis): In the global null test (Task 2), we do not assume any temporal pattern such as linearly or monotonically increasing. If we have some prior knowledge about the temporal trend or the microbiome is more densely sampled longitudinally, we can model the temporal trend and test the association of the trend with the outcome. This offers more power than Task 2 to identify the taxa associated with the outcome.

This guide will navigate you through a comprehensive analysis of microbiome data from a longitudinal design. We will utilize two datasets to illustrate the analysis.

The first dataset is derived from the "Early Childhood Antibiotics and the Microbiome" (ECAM) study. This project observed the microbiome composition and development of 43 infants in the United States from birth through their second year. The study explored the impact of antibiotic exposure, delivery mode, and diet on early microbiome maturation.

> Bokulich, Nicholas A., et al. "Antibiotics, birth mode, and diet shape microbiome maturation during early life." Science translational medicine 8.343 (2016): 343ra82-343ra82.

The second dataset originates from the "T2D16S" study, which tracked a cohort of approximately 100 individuals at risk of diabetes. This study utilized omics analysis of longitudinal patient samples and snapshots of their microbiomes, with the objective of understanding the microbiome-host interactions during viral infections and throughout the onset and progression of diabetes. Due to the large size of this dataset, we have created a subset for our analysis, focusing only on the 16S rRNA sequencing data from the first six time points.

> Stansfield J, Smirnova E, Zhao N, Fettweis J, Waldron L, Dozmorov M (2023). *HMP2Data: 16s rRNA sequencing data from the Human Microbiome Project 2*. R package version 1.14.0, <https://github.com/jstansfield0/HMP2Data>.

These datasets provide valuable insights into how early-life experiences and health conditions, such as diabetes, can influence the microbiome. Our goal is to leverage our analytical tool to explore the longitudinal dynamics of the microbiome presented in these datasets. This exploration will contribute to a more comprehensive understanding of the temporal intricacies of microbiome development and its susceptibilities.

It is important to note some constraints of our current development. Currently, `group.var` and `strata.var` are assumed to be non-time-varying (they stay the same for each subject), while `adj.vars` could allow or not allow time-varying variables depending on the specific settings. If a function cannot adjust time-varying covariates, we will explicitly state it. We will increase the flexibility in the future work.

For users wishing to apply our tutorial to their own datasets, please see the following guide.

{% content-ref url="/pages/WK9NC4ukGZbAvQGuCKUR" %}
[Creating the MicrobiomeStat Data Object](/setting-up-microbiomestat-installation-and-data-preparation/laying-the-foundation-creating-the-microbiomestat-data-object)
{% endcontent-ref %}

This section explains how to convert your data into the `mStat` format, enabling you to use MicrobiomeStat for your research.


# Alpha Diversity Analysis

This section introduces alpha diversity analysis in longitudinal studies, focusing on how within-sample diversity changes over time. The first step is to filter out samples with low sequencing depth, as alpha diversity analysis is sensitive to this factor.

MicrobiomeStat includes "shannon", "simpson", "observed\_species", "chao1", "ace", and "pielou". Each of these metrics furnishes distinct insights into the species richness and evenness inherent in the microbiome samples.

For those functions performing alpha diversity analysis, they all include an alpha.obj parameter, which is a list output from calling `mStat_calculate_alpha_diversity` If alpha.obj parameter is NULL, `mStat_calculate_alpha_diversity` will be called autonomously. To speed up computation, we recommend calling `mStat_calculate_alpha_diversity` once and store the alpha diversity indices in the alpha.obj, which can be used later repeatedly.

To note, `mStat_calculate_alpha_diversity` by default, undertakes data rarefaction. This process ensures the datasets are rendered more comparable by equalizing the sequencing depth across samples. Such standardization is vital for comparative analyses. You can set the desired rarefaction depth in `mStat_calculate_alpha_diversity` or if not specified, the minimum sequencing depth will be used. If you aim to work with non-rarefied data when determining alpha diversity, You can pre-calculate your own alpha diversity indices and pass them to the alpha.obj parameter in these alpha diversity analysis functions.

To account for potential confounding factors that may influence the relationship between alpha diversity and time, the function allows for the inclusion of additional variables (`adj.vars`) in the model. These variables are adjusted for in the linear mixed-effects model, ensuring that the influence of time on alpha diversity is evaluated more accurately.

After the initial preparation, we can use MicrobiomeStat's functions to test for differences in alpha diversity across timepoints. One such function is `generate_alpha_trend_test_long`, which uses a linear mixed-effects model to analyze longitudinal alpha diversity data. It tests whether alpha diversity changes significantly over time, while taking into account individual variability and other potential confounding factors. The mixed-effects model allows for within-subject and between-subject variability, making it suitable for unbalanced data and repeated measures. The trend test checks if the association between alpha diversity and time is statistically significant, providing insights into temporal dynamics in microbiome diversity.

The `time.var` argument in the function `generate_alpha_trend_test_long` needs to be numeric. If you provide a string, it will automatically be converted to a factor and then to numeric, which might cause issues. Please ensure that the time variable is numeric to avoid any potential problems.

```r
data("subset_T2D.obj") 
alpha_trend_test_results <- generate_alpha_trend_test_long(
  data.obj = subset_T2D.obj,
  alpha.name = c("shannon","observed_species"),
  time.var = "visit_number_num",
  subject.var = "subject_id",
  group.var = "subject_race",
  adj.vars = NULL
)
```

**Shannon Diversity**

<table><thead><tr><th>Term</th><th width="114">Estimate</th><th width="123">Std.Error</th><th width="118">Statistic</th><th>P.Value</th></tr></thead><tbody><tr><td>(Intercept)</td><td>2.59</td><td>0.204</td><td>12.7</td><td>5.13e-27</td></tr><tr><td>subject_racecaucasian</td><td>0.214</td><td>0.231</td><td>0.928</td><td>3.55e-1</td></tr><tr><td>subject_racehispanic_or_latino</td><td>0.197</td><td>0.441</td><td>0.446</td><td>6.56e-1</td></tr><tr><td>visit_number_num</td><td>-0.00852</td><td>0.0547</td><td>-0.156</td><td>8.76e-1</td></tr><tr><td>subject_racecaucasian:visit_number_num</td><td>-0.0105</td><td>0.0617</td><td>-0.170</td><td>8.65e-1</td></tr><tr><td>subject_racehispanic_or_latino:visit_number_num</td><td>0.0515</td><td>0.116</td><td>0.443</td><td>6.58e-1</td></tr><tr><td>subject_race:visit_number_num</td><td>NA</td><td>NA</td><td>0.175</td><td>8.40e-1</td></tr></tbody></table>

**Observed Species Diversity**

<table><thead><tr><th>Term</th><th width="112">Estimate</th><th width="125">Std.Error</th><th width="131">Statistic</th><th>P.Value</th></tr></thead><tbody><tr><td>(Intercept)</td><td>118</td><td>16.1</td><td>7.36</td><td>3.22e-12</td></tr><tr><td>subject_racecaucasian</td><td>23.2</td><td>18.2</td><td>1.28</td><td>2.02e-1</td></tr><tr><td>subject_racehispanic_or_latino</td><td>20.1</td><td>34.6</td><td>0.580</td><td>5.62e-1</td></tr><tr><td>visit_number_num</td><td>-0.152</td><td>4.35</td><td>-0.0349</td><td>9.72e-1</td></tr><tr><td>subject_racecaucasian:visit_number_num</td><td>-0.792</td><td>4.90</td><td>-0.162</td><td>8.72e-1</td></tr><tr><td>subject_racehispanic_or_latino:visit_number_num</td><td>2.71</td><td>9.28</td><td>0.292</td><td>7.70e-1</td></tr><tr><td>subject_race:visit_number_num</td><td>NA</td><td>NA</td><td>0.0910</td><td>9.13e-1</td></tr></tbody></table>

In the trend test, our primary focus is on the interaction term between `group.var` and `time.var`. When the levels of `group.var` are greater than 2, an ANOVA is performed, which is represented in the last row of the table.

Another useful function is `generate_alpha_volatility_test_long`. This function calculates the volatility of alpha diversity measures in longitudinal data and tests the association between the volatility and a group variable. Volatility is calculated as the mean of absolute differences between consecutive alpha diversity measures, normalized by the time difference.

In mathematical terms, volatility (V) can be represented like this:

First, let's define a few terms:

* "alpha\_i" is the alpha diversity measure at time "i".
* "delta\_t\_i" is the time difference between time "i" and "i+1".

With these terms, the volatility for a subject is calculated as:

$$
V = \frac{1}{N} \sum \left| \frac{\alpha\_{i+1} - \alpha\_i}{\Delta t\_i} \right|
$$

Here:

* "N" is the total number of time points for the subject.
* The summation "sum" is over all time points for which "alpha\_(i+1)" is defined.

```r
data("subset_T2D.obj") 
alpha_volatility_test_results <- generate_alpha_volatility_test_long(
  data.obj = subset_T2D.obj,
  alpha.obj = NULL,
  alpha.name = c("shannon","observed_species"),
  time.var = "visit_number_num",
  subject.var = "subject_id",
  group.var = "subject_race",
  adj.vars = "sample_body_site"
)
```

**Shannon**

<table><thead><tr><th align="center">Term</th><th width="127" align="center">Estimate</th><th width="112" align="center">Std.Error</th><th align="center">Statistic</th><th align="center">P.Value</th></tr></thead><tbody><tr><td align="center">(Intercept)</td><td align="center">0.544</td><td align="center">0.0959</td><td align="center">5.67</td><td align="center">0.000000423</td></tr><tr><td align="center">subject_racecaucasian</td><td align="center">0.0222</td><td align="center">0.108</td><td align="center">0.205</td><td align="center">0.838</td></tr><tr><td align="center">subject_racehispanic_or_latino</td><td align="center">-0.0705</td><td align="center">0.222</td><td align="center">-0.318</td><td align="center">0.752</td></tr><tr><td align="center">subject_race</td><td align="center">NA</td><td align="center">NA</td><td align="center">0.114</td><td align="center">0.893</td></tr><tr><td align="center">Residuals</td><td align="center">NA</td><td align="center">NA</td><td align="center">NA</td><td align="center">NA</td></tr></tbody></table>

**Observed Species**

<table><thead><tr><th width="148">Term</th><th width="141" align="center">Estimate</th><th width="109" align="center">Std.Error</th><th width="185" align="center">Statistic</th><th align="center">P.Value</th></tr></thead><tbody><tr><td>(Intercept)</td><td align="center">40.6</td><td align="center">5.82</td><td align="center">6.98</td><td align="center">2.51e-9</td></tr><tr><td>subject_racecaucasian</td><td align="center">-1.95</td><td align="center">6.56</td><td align="center">-0.297</td><td align="center">7.67e-1</td></tr><tr><td>subject_racehispanic_or_latino</td><td align="center">-7.04</td><td align="center">13.4</td><td align="center">-0.524</td><td align="center">6.02e-1</td></tr><tr><td>subject_race</td><td align="center">NA</td><td align="center">NA</td><td align="center">0.143</td><td align="center">8.67e-1</td></tr><tr><td>Residuals</td><td align="center">NA</td><td align="center">NA</td><td align="center">NA</td><td align="center">NA</td></tr></tbody></table>

After discussing the functions `generate_alpha_trend_test_long` and `generate_alpha_volatility_test_long`, let's explore another important aspect of analyzing longitudinal alpha diversity data in the context of Type 2 Diabetes (T2D) dataset.

In addition to the trend and volatility tests, MicrobiomeStat provides the capability to perform detailed alpha diversity tests at each time point in a longitudinal study. This is achieved using the `generate_alpha_per_time_test_long` function. This function allows for a comprehensive examination of alpha diversity measures such as Shannon, Simpson, Observed Species, Chao1, ACE, and Pielou's Evenness across different time points in the dataset.

To perform the longitudinal alpha diversity test for the T2D dataset, we apply the `generate_alpha_per_time_test_long` function. This function requires specifying various parameters including alpha diversity measures, time variable, levels for time points, group variable, and any additional variables for adjustment. Here's an example:

```r
alpha_test_results_T2D <- generate_alpha_per_time_test_long(
  data.obj = subset_T2D.obj,
  alpha.name = c("shannon", "simpson", "observed_species", "chao1", "ace", "pielou"),
  time.var = "visit_number",
  t0.level = unique(subset_T2D.obj$meta.dat$visit_number)[1],
  ts.levels = unique(subset_T2D.obj$meta.dat$visit_number)[-1],
  group.var = "subject_race",
  adj.vars = c("sample_body_site")
)
```

Subsequently, to visualize the results of these tests, the `generate_alpha_per_time_dotplot_long` function can be utilized. This function creates dot plots for the alpha diversity measures, allowing for an intuitive understanding of the changes and differences across time points and groups. The visualization includes specifying the group and time variables, setting the levels for time points, and choosing the desired theme and base size for the plot. The following example demonstrates how to generate dot plots for the T2D dataset results:

```r
dot_plots_T2D <- generate_alpha_per_time_dotplot_long(
  data.obj = subset_T2D.obj,
  test.list = alpha_test_results_T2D,
  group.var = "subject_race",
  time.var = "visit_number",
  t0.level = unique(subset_T2D.obj$meta.dat$visit_number)[1],
  ts.levels = unique(subset_T2D.obj$meta.dat$visit_number)[-1],
  base.size = 16,
  theme.choice = "bw"
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FV8MItOmnxVMSaXgDwBEz%2FScreenshot%202024-01-18%20at%2016.34.59.png?alt=media&amp;token=e29b62b3-8cb5-487c-820a-28c372019a6e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FaIV0R9GLbKNlSz7Pw5Gh%2FScreenshot%202024-01-18%20at%2016.33.47.png?alt=media&amp;token=02edab2a-3f6a-4bf2-a0e1-1ff57a73bc16" alt=""><figcaption></figcaption></figure>

In the dot plots generated by `generate_alpha_per_time_dotplot_long`, you'll notice that some dots are marked with an asterisk (\*). These asterisks signify statistical significance.

Further enhancing our analysis, we introduce the `generate_alpha_change_per_time_test_long` function. This function is specifically designed to assess the change in alpha diversity for each subject at different time points relative to a baseline level (`t0.level`). It performs statistical tests to evaluate the significance of changes in alpha diversity, using measures like "log fold change" to quantify these alterations. This approach is particularly insightful in longitudinal studies where the focus is on understanding how individual subjects' microbial communities evolve over time.

```r
alpha_test_results_T2D <- generate_alpha_change_per_time_test_long(
  data.obj = subset_T2D.obj,
  alpha.name = c("shannon", "simpson", "observed_species", "chao1", "ace", "pielou"),
  time.var = "visit_number",
  t0.level = unique(subset_T2D.obj$meta.dat$visit_number)[1],
  ts.levels = unique(subset_T2D.obj$meta.dat$visit_number)[-1],
  subject.var = "subject_id",
  group.var = "subject_race",
  adj.vars = c("sample_body_site"),
  alpha.change.func = "log fold change"
)
```

To visualize the results from `generate_alpha_change_per_time_test_long`, we use the `generate_alpha_per_time_dotplot_long` function. This function creates dot plots for the alpha diversity measures, providing an intuitive understanding of the changes and differences across time points and groups. The plots help in visually interpreting the statistical significance and trends in the data. Here's how you can generate these plots for the T2D dataset:

```r
dot_plots_T2D <- generate_alpha_per_time_dotplot_long(
  data.obj = subset_T2D.obj,
  test.list = alpha_test_results_T2D,
  group.var = "subject_race",
  time.var = "visit_number",
  t0.level = unique(subset_T2D.obj$meta.dat$visit_number)[1],
  ts.levels = unique(subset_T2D.obj$meta.dat$visit_number)[-1],
  base.size = 16,
  theme.choice = "bw"
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FfXEFbANxs4qAkfhpPR7e%2FScreenshot%202024-01-18%20at%2016.54.54.png?alt=media&amp;token=67bd5da9-e64c-45c1-bf89-23249ce46e6d" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FVAgaNkLzuscjMHe8xo9j%2FScreenshot%202024-01-18%20at%2016.55.23.png?alt=media&amp;token=cf01e048-6ab1-402a-aef2-da062e5aedcb" alt=""><figcaption></figcaption></figure>

These functions, `generate_alpha_per_time_test_long`, `generate_alpha_change_per_time_test_long`, and `generate_alpha_per_time_dotplot_long`, complement the earlier discussed functions by providing a more granular view of alpha diversity over time. They are especially useful in studies with multiple time points like the T2D dataset, offering a comprehensive perspective on the dynamics of microbial diversity.

Before we proceed with the visualization, it's crucial to understand the `time.var`, `t0.level`, and `ts.levels` parameters used in the functions `generate_alpha_spaghettiplot_long` and `generate_alpha_boxplot_long`.

The `time.var` parameter can take three forms:

* Numeric: When `time.var` is numeric, you don't need to set `t0.level` and `ts.levels`, as they will be automatically arranged in ascending order.
* Factor: If `time.var` is a factor, and if `t0.level` and `ts.levels` are not set, they will be automatically arranged according to the levels of the factor. However, if you have specific needs for the order of the levels, you can manually adjust `t0.level` and `ts.levels`.
* Character: If `time.var` is character, it's recommended to manually set `t0.level` and `ts.levels`, as the automatic arrangement might not reflect the correct order.

The `t0.level` parameter represents the first time point, while `ts.levels` represents the other time points, arranged in the order you desire, excluding `t0.level`.

Understanding these parameters is pivotal for effective visualization of temporal changes in alpha diversity. Now, let's proceed with creating the spaghetti plot and box plot to visualize alpha diversity changes over time for each individual in the study, grouped by race.

```r
# Generate a spaghetti plot of alpha diversity over time
generate_alpha_spaghettiplot_long(
  data.obj = subset_T2D.obj,
  alpha.obj = NULL,
  alpha.name = c("shannon"),
  depth = NULL,
  subject.var = "subject_id",
  time.var = "visit_number",
  t0.level = sort(unique(subset_T2D.obj$meta.dat$visit_number))[1],
  ts.levels = sort(unique(subset_T2D.obj$meta.dat$visit_number))[-1],
  group.var = "subject_race",
  strata.var = NULL,
  theme.choice = "bw",
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F0tqfHkfQGUMmerhEO8cG%2FScreenshot%202023-10-12%20at%2009.38.19.png?alt=media&amp;token=2162baeb-247f-4cc7-ab12-c92de4963c22" alt=""><figcaption></figcaption></figure>

Before we proceed with the `generate_alpha_boxplot_long()` function, it's important to note that when dealing with multiple time points, a boxplot might not provide the most effective visualization. The boxplot can become cluttered and harder to interpret with the addition of more time points. In such cases, a spaghetti plot, as generated by the `generate_alpha_spaghettiplot_long()` function, is often a better choice as it can more clearly illustrate the individual changes over time.

However, if you still wish to use a boxplot for visualizing alpha diversity over time, here's how you can do it with the `generate_alpha_boxplot_long()` function:

```r
# Render a boxplot encapsulating alpha diversity across chosen time points
generate_alpha_boxplot_long(
  data.obj = subset_T2D.obj,
  alpha.obj = NULL,
  alpha.name = c("shannon"),
  depth = NULL,
  subject.var = "subject_id",
  time.var = "visit_number_num",
  t0.level = sort(unique(subset_T2D.obj$meta.dat$visit_number_num))[1],
  ts.levels = sort(unique(subset_T2D.obj$meta.dat$visit_number_num))[2:4],
  group.var = "subject_race",
  strata.var = NULL,
  base.size = 20,
  theme.choice = "bw",
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 20,
  pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fe26gd6x5C1hFzel9kQ0O%2FScreenshot%202023-10-12%20at%2009.42.30.png?alt=media&amp;token=41273ae1-0cb7-4d74-8a78-a358abb1104a" alt=""><figcaption></figcaption></figure>


# Beta Diversity Analysis

This guide outlines how to use MicrobiomeStat for beta diversity analysis, specifically focusing on visualizing and quantifying temporal changes in microbial community composition. MicrobiomeStat offers tools for examining longitudinal patterns in beta diversity.

For those beta diversity-based functions, they all have a `dist.obj` parameter, which accepts a list of distance matrices. If the parameter is not specified, `mStat_calculate_beta_diversity` will be automatically called. Or the users can create their own list of distance matrices and pass it to `dist.obj`. We recommend the user to create a list of distance matrices once in the analysis and then use it repeatedly.

When covariates (`adj.vars`) are identified, the `mStat_calculate_adjusted_distance` function refines the microbial community dissimilarities using a method based on the reference below.

> Chen J, Zhang X. dICC: distance-based intraclass correlation coefficient for metagenomic reproducibility studies. Bioinformatics. 2022 Oct 31;38(21):4969-4971. doi: 10.1093/bioinformatics/btac618. PMID: 36083005; PMCID: PMC9801959.

This process ensures the extracted microbial patterns are not confounded by the specified covariates, thus presenting a more accurate representation of the microbial community structures.

Based on the distance matrices, we can also extract their first several principal coordinates (PCs), which capture the main variation in the data. PCs can be calculated by calling `mStat_calculate_PC` function. While users are free to select between "mds" and "nmds" as their ordination method, in scenarios where `pc.obj` isn't provided beforehand, the toolkit defaults to the "mds" method. Researchers favoring advanced ordination techniques like t-SNE or UMAP can employ external tools to compute results. For those PC-based functions, they all have a `pc.obj` parameter, which accepts a list of PC matrices based on a variety of beta diversity measures. If the parameter is not specified, `mStat_calculate_PC` will be called automatically. Or the users can create their own list of PC matrices and pass it to `pc.obj`. We recommend the user to create the list once in the analysis and use it repeatedly.

MicrobiomeStat supports "BC" (Bray-Curtis), "Jaccard", "UniFrac" (unweighted), "GUniFrac" (generalized), "WUniFrac" (weighted), and "JS" (Jensen-Shannon divergence). These measures can be computed using the `mStat_calculate_beta_diversity` function, which is designed to handle a range of distance calculations for assessing the dissimilarity between microbial communities.

Building on these distance measures, the `generate_beta_trend_test_long()` function in MicrobiomeStat utilizes a linear mixed effects model for longitudinal beta diversity trend analysis. This function uses the distance matrix as the response, time as a fixed effect, and subject as a random effect. It also supports interaction with a grouping variable and inclusion of covariates for model refinement.

```r
data(subset_T2D.obj)
generate_beta_trend_test_long(
  data.obj = subset_T2D.obj,
  dist.obj = NULL,
  subject.var = "subject_id",
  time.var = "visit_number_num",
  group.var = "subject_race",
  adj.vars = c("subject_gender", "sample_body_site"),
  dist.name = c("BC", "Jaccard")
)
```

<table><thead><tr><th>Term</th><th width="133">Estimate</th><th>Std.Error</th><th>Statistic</th><th>P.Value</th></tr></thead><tbody><tr><td>(Intercept)</td><td>1.95</td><td>0.142</td><td>13.8</td><td>1.59e-20</td></tr><tr><td>subject_racecaucasian</td><td>-0.280</td><td>0.162</td><td>-1.73</td><td>8.90e-2</td></tr><tr><td>subject_racehispanic_or_latino</td><td>0.248</td><td>0.308</td><td>0.805</td><td>4.25e-1</td></tr><tr><td>visit_number_num</td><td>-0.0235</td><td>0.0245</td><td>-0.959</td><td>3.44e-1</td></tr><tr><td>subject_racecaucasian:visit_number_num</td><td>0.0490</td><td>0.0280</td><td>1.75</td><td>8.88e-2</td></tr><tr><td>subject_racehispanic_or_latino:visit_number_num</td><td>0.0264</td><td>0.0484</td><td>0.545</td><td>5.90e-1</td></tr><tr><td>subject_race:visit_number_num</td><td>NA</td><td>NA</td><td>1.56</td><td>2.27e-1</td></tr></tbody></table>

The `generate_beta_volatility_test_long()` function performs a volatility test for beta diversity in longitudinal data. This function calculates the beta diversity volatility by determining the average rate of change in beta diversity over time for each subject.

In mathematical terms, the volatility (V) can be calculated as follows:

First, let's define a few terms:

* "d\_i" represents the beta diversity (distance) between time "i" and "i+1".
* "delta\_t\_i" is the time difference between time "i" and "i+1".

With these terms, the volatility for a subject is calculated as:

$$
V = \frac{1}{N-1} \sum \left| \frac{d\_i}{\Delta t\_i} \right|
$$

Here:

* "N" is the total number of time points for the subject.
* The summation "sum" is over all time points for which "d\_i" is defined.

This formula calculates the average rate of change in distance per unit time, which is an appropriate measure of volatility in this context.

To account for the adjustment variables in the distance calculation, the function employs Multidimensional Scaling (MDS). This technique transforms the distance matrix into a set of coordinates. These coordinates are then adjusted to account for the influence of the covariates, and the adjusted coordinates are used to compute the adjusted distances.

After the volatility is calculated, the function tests the relationship between the calculated volatility and a specified group variable. This is done using linear regression or ANOVA for multi-category variables, allowing for the exploration of how beta diversity volatility differs across different groups.

```r
generate_beta_volatility_test_long(
  data.obj = subset_T2D.obj,
  dist.obj = NULL,
  subject.var = "subject_id",
  time.var = "visit_number_num",
  group.var = "subject_race",
  adj.vars = "sample_body_site",
  dist.name = c("BC", "Jaccard")
)
```

<table><thead><tr><th>Term</th><th width="140">Estimate</th><th>Std.Error</th><th>Statistic</th><th>P.Value</th></tr></thead><tbody><tr><td>(Intercept)</td><td>0.956</td><td>0.161</td><td>5.93</td><td>0.000000164</td></tr><tr><td>subject_racecaucasian</td><td>-0.104</td><td>0.182</td><td>-0.571</td><td>0.570</td></tr><tr><td>subject_racehispanic_or_latino</td><td>-0.502</td><td>0.372</td><td>-1.35</td><td>0.183</td></tr><tr><td>subject_race</td><td>NA</td><td>NA</td><td>0.909</td><td>0.408</td></tr><tr><td>Residuals</td><td>NA</td><td>NA</td><td>NA</td><td>NA</td></tr></tbody></table>

In addition to trend and volatility analysis, we introduce the `generate_beta_change_per_time_test_long` function. This function evaluates the change in beta diversity for each subject at different time points relative to a baseline level (`t0.level`). It's designed to assess the statistical significance of these changes over time, adding depth to our understanding of beta diversity dynamics in longitudinal studies.

```r
result1 <- generate_beta_change_per_time_test_long(
  data.obj = subset_T2D.obj,
  dist.obj = NULL,
  time.var = "visit_number_num",
  t0.level = unique(subset_T2D.obj$meta.dat$visit_number_num)[1],
  ts.levels = unique(subset_T2D.obj$meta.dat$visit_number_num)[-1],
  subject.var = "subject_id",
  group.var = "subject_race",
  adj.vars = NULL,
  dist.name = c('BC', 'Jaccard', 'JS')
)
```

To visualize the results of the `generate_beta_change_per_time_test_long` analysis, the `generate_beta_per_time_dotplot_long` function is used. This function produces dot plots that illustrate the changes in beta diversity across different time points and groups. Such visualizations are instrumental in highlighting significant trends and variations in the dataset.

```r
dotplot_T2D <- generate_beta_per_time_dotplot_long(
  data.obj = subset_T2D.obj,
  test.list = result1,
  group.var = "subject_race",
  time.var = "visit_number_num",
  t0.level = unique(subset_T2D.obj$meta.dat$visit_number_num)[1],
  ts.levels = unique(subset_T2D.obj$meta.dat$visit_number_num)[-1],
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FFGZJyf5VW1p0NCod0SvN%2FScreenshot%202024-01-18%20at%2017.21.08.png?alt=media&amp;token=d6c149ec-8524-47dd-b577-d0f2d4c499f6" alt="" width="563"><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FozExbFnynceDu2h8LP1I%2FScreenshot%202024-01-18%20at%2017.21.39.png?alt=media&amp;token=a4de16c3-8d67-49cd-ba0d-947d8f027266" alt="" width="563"><figcaption></figcaption></figure>

In addition to these statistical analyses, MicrobiomeStat also provides visualization tools for beta diversity. For instance, the `generate_beta_pc_boxplot_long()` function creates a plot that shows individual trajectories across ordination axes, connecting data points from one timepoint to the next.

```r
data(ecam.obj)
generate_beta_pc_boxplot_long(
  data.obj = ecam.obj,
  dist.obj = NULL,
  pc.obj = NULL,
  subject.var = "studyid",
  time.var = "month",
  t0.level = "0",
  ts.levels = as.character(sort(as.numeric(unique(ecam.obj$meta.dat$month))))[2:4],
  group.var = "diet", 
  strata.var = "delivery",
  dist.name = c('BC'),
  base.size = 20,
  theme.choice = "bw",
  custom.theme = NULL,
  palette = NULL,
  pdf = TRUE,
  file.ann = "test",
  pdf.wid = 11,
  pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FP9EOygN2yvvuwNuCZHmZ%2FScreenshot%202023-10-12%20at%2010.49.33.png?alt=media&amp;token=82a75a06-8f33-4063-95f2-08a2ce79c5b0" alt=""><figcaption></figcaption></figure>

Expanding on this, the `generate_beta_ordination_long()` function creates a plot where samples cluster based on similarity, providing a global overview of the data.

```r
generate_beta_ordination_long(
  data.obj = subset_T2D.obj,
  dist.obj = NULL,  
  pc.obj = NULL,
  subject.var = "subject_id",
  time.var = "visit_number",
  t0.level = sort(unique(subset_T2D.obj$meta.dat$visit_number))[1],
  ts.levels = sort(unique(subset_T2D.obj$meta.dat$visit_number))[2:4],
  group.var = "subject_race",
  strata.var = "subject_gender",
  dist.name = c("BC"),
  base.size = 16,
  theme.choice = "bw",
  custom.theme = NULL,
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5  
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FsiFfuFCKr8WohJ57H4Aa%2FScreenshot%202023-10-12%20at%2010.51.29.png?alt=media&amp;token=40e366fe-95b4-47af-ac44-f9d17bcc3151" alt=""><figcaption></figcaption></figure>

Lastly, the `generate_beta_change_spaghettiplot_long()` function creates a plot that shows individual trajectories of microbial change, providing a detailed view of each subject's journey through time.

```r
generate_beta_change_spaghettiplot_long(
  data.obj = ecam.obj,
  dist.obj = NULL,
  subject.var = "studyid",
  time.var = "month", 
  t0.level = NULL,
  ts.levels = NULL,
  group.var = "diet",
  strata.var = "antiexposedall",
  dist.name = c("BC"),
  base.size = 20,
  theme.choice = "bw",
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11, 
  pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F8QvOyHpTtcjFVPkF7zwg%2FScreenshot%202023-10-12%20at%2010.52.24.png?alt=media&amp;token=04a402e8-1f15-4c5c-9c25-14d37211afc5" alt=""><figcaption></figcaption></figure>

## Within-Group and Between-Group Beta Diversity Changes

The `generate_beta_change_boxplot_long()` function compares within-group and between-group beta diversity across time points. This is useful for understanding whether samples within a group become more similar or different over time.

```r
generate_beta_change_boxplot_long(
  data.obj = subset_T2D.obj,
  dist.obj = NULL,
  subject.var = "subject_id",
  time.var = "visit_number",
  group.var = "subject_race",
  strata.var = NULL,
  adj.vars = NULL,
  t0.level = sort(unique(subset_T2D.obj$meta.dat$visit_number))[1],
  ts.levels = sort(unique(subset_T2D.obj$meta.dat$visit_number))[2:4],
  dist.name = c("BC"),
  base.size = 16,
  theme.choice = "bw",
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5
)
```

## Principal Coordinate Trend and Volatility Analysis

For more detailed analysis of beta diversity changes along specific ordination axes, MicrobiomeStat provides functions to test trends and volatility of principal coordinates.

The `generate_beta_pc_trend_test_long()` function performs linear trend tests on selected Principal Coordinates (PCs) over time:

```r
generate_beta_pc_trend_test_long(
  data.obj = subset_T2D.obj,
  dist.obj = NULL,
  pc.obj = NULL,
  pc.ind = c(1, 2),
  subject.var = "subject_id",
  time.var = "visit_number_num",
  group.var = "subject_race",
  adj.vars = NULL,
  dist.name = c("BC", "Jaccard")
)
```

This function fits linear mixed effects models to test whether PC values change significantly over time, while accounting for repeated measures within subjects.

Similarly, the `generate_beta_pc_volatility_test_long()` function calculates the volatility (rate of change) of PC values:

```r
generate_beta_pc_volatility_test_long(
  data.obj = subset_T2D.obj,
  dist.obj = NULL,
  pc.obj = NULL,
  pc.ind = c(1, 2),
  subject.var = "subject_id",
  time.var = "visit_number_num",
  group.var = "subject_race",
  adj.vars = NULL,
  dist.name = c("BC", "Jaccard")
)
```

The `generate_beta_pc_spaghettiplot_long()` function visualizes individual PC trajectories over time:

```r
generate_beta_pc_spaghettiplot_long(
  data.obj = subset_T2D.obj,
  dist.obj = NULL,
  pc.obj = NULL,
  pc.ind = c(1, 2),
  subject.var = "subject_id",
  time.var = "visit_number",
  t0.level = sort(unique(subset_T2D.obj$meta.dat$visit_number))[1],
  ts.levels = sort(unique(subset_T2D.obj$meta.dat$visit_number))[2:4],
  group.var = "subject_race",
  strata.var = NULL,
  dist.name = c("BC"),
  base.size = 16,
  theme.choice = "bw",
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5
)
```

These PC-based functions complement the distance-based analyses by focusing on specific axes of variation in the microbiome community structure.


# Feature-level Analysis

This guide will walk you through the process of investigating how taxonomic composition changes within a longitudinal context, providing insights into microbial dynamics over time.

MicrobiomeStat provides a set of functions to illuminate the intricate taxonomic changes over time. The `generate_taxa_trend_test_long()` function executes a trend test on longitudinal microbiome data. It commences with the normalization of count data, followed by the generation of a mixed-effects model that incorporates time, group, and subject variables. Special attention is given to the interaction between time and group variables. Finally, the function applies the `linda()` method to discern whether these variables significantly influence taxa abundance.

### Categorical vs Continuous Predictors

The `generate_taxa_trend_test_long()` function automatically distinguishes between categorical and continuous predictor variables for the `group.var` parameter:

* **Categorical variables** (factor/character): Tests group differences and group × time interaction, creating pairwise comparisons vs. the reference level
* **Continuous variables** (numeric/integer): Tests linear association with time

This automatic detection allows the same function to handle both types of predictors appropriately without requiring manual specification.

The `ref.level` parameter allows you to explicitly specify the reference level for categorical `group.var`. By default, R uses the first level of the factor as the reference. Setting `ref.level` overrides this behavior, which is useful when you want to compare against a specific control group.

### Data Type Handling

The `feature.dat.type` parameter plays a crucial role in the data preprocessing phase:

* `"count"`: For raw count data, the function first performs sparsity treatment, followed by a Total Sum Scaling (TSS) normalization. This process ensures that the data is suitably normalized and comparable across samples.
* `"proportion"`: Data presented as proportions remains unaltered.However, it's worth noting that during the LinDA differential abundance analysis, zeroes in the dataset are substituted with half of the smallest non-zero count for each feature. This adjustment is done to mitigate the impact of zero-inflation.
* `"other"`: In scenarios where the data originates from non-compositional sources, like transcriptomics and metabolomics, a different data transformation approach might be more appropriate. When `feature.dat.type` is set to "other", the function does not perform any normalization or scaling operations, allowing users to apply domain-specific transformations if necessary.

Further enhancing data robustness, the `prev.filter` and `abund.filter` parameters filter taxa based on prevalence and average abundance, respectively. Specifically:

* `prev.filter` targets taxa retention based on their prevalence across samples.
* `abund.filter` focuses on the average abundance of taxa across all samples.

Such filtering ensures that the analysis centers on taxa both prevalent and abundant, enhancing result reliability by excluding potential outliers or noise.

For those directly analyzing entities like OTU, ASV, Gene, KEGG, etc., that don't require aggregation, it's recommended to set the `feature.level` parameter to "original". Or we can perform testing on aggregated levels such as "Phylum", "Family" and "Genus" levels for microbiome data.

Furthermore, when interpreting the results, it's essential to understand `feature.sig.level` and `feature.mt.method` parameters:

* `feature.sig.level`: This parameter determines the significance level, primarily influencing the position of the dashed lines in the volcano plot. It sets the threshold for distinguishing between significant and non-significant differences in taxa abundance.
* `feature.mt.method`: The available options are: "fdr" (False Discovery Rate), "bonferroni", and "none". Regardless of how this parameter is set, it's crucial to note that the `generate_taxa_test_single` function always performs adjustments post-testing. However, the `feature.mt.method` specifically influences the visualization in the volcano plot.

Another important parameter is `feature.change.func`, which specifies the method or function used to compute the change between two time points. The options include:

* `"relative change"` (default): Computes the relative change as `(value_time_2 - value_time_1) / (value_time_2 + value_time_1)`. If both time points have a value of 0, the change is defined as 0.
* `"absolute change"`: Computes the absolute difference between the values at the two time points (`value_time_2` and `value_time_1`).
* `"log fold change"`: Computes the log2 fold change between the two time points. For zero values, imputation is performed using half of the minimum nonzero value for each feature level at the respective time point before taking the logarithm.
* A custom function: If a user-defined function is provided, it should take two numeric vectors as input corresponding to the values at the two time points (`value_time_1` and `value_time_2`) and return a numeric vector of the computed change. This custom function will be applied directly to calculate the difference.

By understanding and appropriately setting these parameters, users can ensure a more accurate and contextually relevant interpretation of the plotted results.

```r
data("subset_T2D.obj")
test.list <- generate_taxa_trend_test_long(
  data.obj = subset_T2D.obj,
  subject.var = "subject_id",
  time.var = "visit_number_num",
  group.var = "subject_race",
  adj.vars = "sample_body_site",
  prev.filter = 0.1,
  abund.filter = 0.001,
  feature.level = c("Family"),
  feature.dat.type = c("count")
)
plot.list <- generate_taxa_trend_volcano_long(
  data.obj = subset_T2D.obj,
  group.var = "subject_race",
  time.var = "visit_number_num",
  test.list = test.list,
  feature.sig.level = 0.1,
  feature.mt.method = "none"
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Ft65cAq5DOZUvkBDM9NtL%2FScreenshot%202023-10-12%20at%2019.37.52.png?alt=media&amp;token=1987aca4-5564-4433-a7a2-8be3fdaddd1e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FruckPzF3Pb1m27Q0qdd1%2FScreenshot%202023-10-12%20at%2019.38.25.png?alt=media&amp;token=4a7930ec-eee7-4ff3-848f-b51036eaed85" alt=""><figcaption></figcaption></figure>

The function `generate_taxa_volatility_test_long()` is designed to analyze longitudinal microbiome data by calculating the volatility of taxa abundances and testing for an association with a grouping variable. Prior to the calculation of volatility, a centered log-ratio (CLR) transformation is performed on the data.

After the transformation, the volatility, denoted as 'V', is computed as the mean rate of change in abundance over time, defined as:

$$
V = \frac{1}{n} \sum\_{i=1}^{n} \left| \frac{A(t\_{i+1}) - A(t\_i)}{t\_{i+1} - t\_i} \right|
$$

where 'A(t)' is the abundance at time 't' and 'Δt = t\_{i+1} - t\_i' is the time difference.

This function fits a linear model to the volatility data with the formula 'V = β\_0 + β\_1\_G + β\_2\_X + ε', where 'V' is the volatility, 'G' is the group variable, 'X' represents adjustment variables, and 'ε' is the error term. If the group variable is multi-categorical, an ANOVA test is also performed to test the overall significance of the group variable, while considering the adjustment variables.

The function is applied as follows:

```r
data("subset_T2D.obj")
test.list <- generate_taxa_volatility_test_long(
  data.obj = subset_T2D.obj,
  time.var = "visit_number_num",
  subject.var = "subject_id",
  group.var = "subject_race",
  adj.vars = "sample_body_site",
  prev.filter = 0.1,
  abund.filter = 0.001,
  feature.level = c("Species"),
  feature.dat.type = "count",
  transform = "CLR"
)
plot.list <- generate_taxa_volatility_volcano_long(
  data.obj = subset_T2D.obj,
  group.var = "subject_race",
  test.list = test.list,
  feature.sig.level = 0.1,
  feature.mt.method = "none"
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fmw5xsX3Yxl30bMIzS2OG%2FScreenshot%202023-10-12%20at%2020.04.46.png?alt=media&amp;token=794f369c-e5c3-4bd3-b13e-00dbaca9377e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FFiJ8TjxEMAI9ojrywxIe%2FScreenshot%202023-10-12%20at%2020.05.53.png?alt=media&amp;token=06dc094c-86c4-47e2-937e-72d000452e18" alt=""><figcaption></figcaption></figure>

To extend our analysis further, we use the `generate_taxa_association_test_long` function. This function analyzes the microbiome data by treating longitudinal data as cross-sectional, effectively ignoring the time component. It is especially useful in situations where the focus is on understanding the overall association between microbiome composition and other variables, without considering the fluctuations over time. This approach can yield more robust results by diminishing the influence of time-point specific variations on the microbiome.

```r
data("subset_T2D.obj")
test.list_T2D <- generate_taxa_association_test_long(
  data.obj = subset_T2D.obj,
  subject.var = "subject_id",
  feature.level = "Genus",
  group.var = "subject_race",
  feature.dat.type = c("count"),
  prev.filter = 0.1,
  abund.filter = 0.001
)

volcano_plots_T2D <- generate_taxa_volcano_single(
  data.obj = subset_T2D.obj,
  group.var = "subject_race",
  test.list = test.list_T2D,
  feature.sig.level = 0.1,
  feature.mt.method = "none"
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FhKVvv5LaYeyJk4UzQvMf%2FScreenshot%202024-01-18%20at%2018.07.50.png?alt=media&amp;token=e6f33e86-b931-478c-897f-50e6b3cc528b" alt=""><figcaption></figcaption></figure>

Building on this, we also use the `generate_taxa_per_time_test_long` function to analyze the microbiome data at each individual time point. This function performs a subset analysis on the dataset, followed by a statistical test using the linda method for each time point. It enables a detailed investigation of taxa changes over time, considering various factors such as subject characteristics and sample sites.

```r
result2 <- generate_taxa_per_time_test_long(
  data.obj = subset_T2D.obj,
  subject.var = "subject_id",
  time.var = "visit_number",
  group.var = "subject_race",
  adj.vars = "sample_body_site",
  prev.filter = 0.1,
  abund.filter = 0.001,
  feature.level = c("Genus", "Family"),
  feature.dat.type = "count"
)
```

To effectively visualize these results, we employ the `generate_taxa_per_time_dotplot_long` function. This function creates dot plots that provide a clear and intuitive visualization of the taxa changes at different time points, facilitating an understanding of the temporal dynamics within the dataset.

```r
dotplot_T2D <- generate_taxa_per_time_dotplot_long(
  data.obj = subset_T2D.obj,
  test.list = result2,
  group.var = "subject_race",
  time.var = "visit_number",
  feature.level = c("Genus", "Family")
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FeJZFARyX3UoX7YBIUiqb%2FScreenshot%202024-01-18%20at%2017.38.01.png?alt=media&amp;token=b16fd880-6774-4cd9-8558-ef886ecc097f" alt=""><figcaption></figcaption></figure>

These methods, including both the `generate_taxa_per_time_test_long` and `generate_taxa_per_time_dotplot_long`, enhance our ability to scrutinize and understand the intricate patterns and variations in taxa abundance throughout the course of the Type 2 Diabetes study, thereby enriching our analysis and insights.

Further advancing our analysis, we introduce the `generate_taxa_change_per_time_test_long` function. This function is designed to analyze the change in taxa abundance relative to a baseline time point (`t0.level`). It provides insights into the changes in microbiome composition from the baseline to subsequent time points, considering the diversity at different taxonomic levels such as Genus and Family.

```r
result <- generate_taxa_change_per_time_test_long(
  data.obj = subset_T2D.obj,
  subject.var = "subject_id",
  time.var = "visit_number",
  t0.level = unique(subset_T2D.obj$meta.dat$visit_number)[1],
  ts.levels = unique(subset_T2D.obj$meta.dat$visit_number)[-1],
  group.var = "subject_race",
  adj.vars = "sample_body_site",
  prev.filter = 0.1,
  abund.filter = 0.001,
  feature.level = c("Genus", "Family"),
  feature.dat.type = "count"
)
```

The results from this function can be visualized using `generate_taxa_per_time_dotplot_long`, which provides a comprehensive view of the taxa changes from the baseline across different time points. This visualization aids in identifying significant shifts in the microbiome composition over the course of the study.

```r
dotplot_T2D <- generate_taxa_per_time_dotplot_long(
  data.obj = subset_T2D.obj,
  test.list = result,
  t0.level = unique(subset_T2D.obj$meta.dat$visit_number)[1],
  ts.levels = unique(subset_T2D.obj$meta.dat$visit_number)[-1],
  group.var = "subject_race",
  time.var = "visit_number",
  feature.level = c("Genus", "Family")
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FdtLaH6novs9rs0lmph4F%2FScreenshot%202024-01-18%20at%2017.52.59.png?alt=media&amp;token=54cc425e-b955-4c85-9501-857b4ccffc79" alt=""><figcaption></figcaption></figure>

To visualize the abundance trajectories of specific taxa across multiple timepoints, the function `generate_taxa_areaplot_long()` can be used. Let's touch upon an essential parameter that fundamentally steers the visual output – the `feature.number`.

* `feature.number`: This parameter determines the maximum number of taxa/features that will be visualized directly in the barplot. For datasets with numerous features, it's practical to limit to the most abundant or significant taxa, ensuring that the visualization remains informative and isn't cluttered. When the number of taxa surpasses the value defined in `feature.number`, the function aggregates low-abundance taxa into a collective category labeled "other". This means, for instance, if there are over 20 features in the dataset but `feature.number` is set to 20, the least abundant features that exceed this count will be collectively presented as "other" in the visualization. This approach ensures that the chart remains legible, highlighting the most dominant features, while still accounting for the contributions of less abundant taxa.

```r
generate_taxa_areaplot_long(
  data.obj = ecam.obj,
  subject.var = "studyid", 
  time.var = "month",
  group.var = "diet",
  strata.var = "antiexposedall",
  feature.level = "Family",
  feature.dat.type = "proportion",  
  feature.number = 8,
  t0.level = unique(ecam.obj$meta.dat$month)[1],
  ts.levels = unique(ecam.obj$meta.dat$month)[-1],
  base.size = 10,
  theme.choice = "bw",
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FfPjX9mCAl1RmzN4Fdtc6%2FScreenshot%202023-08-05%20at%2014.28.37.png?alt=media&amp;token=aceecb85-3369-4ade-8000-bca12a033ec2" alt=""><figcaption></figcaption></figure>

This longitudinal area plot allows us to track the changes of specific taxa over time, comparing trajectories between groups.

For insights into the taxonomic composition within groups at each timepoint, `generate_taxa_barplot_long()` can be utilized:

```r
generate_taxa_barplot_long(
  data.obj = ecam.obj,
  subject.var = "studyid",
  time.var = "month", 
  group.var = "delivery",
  strata.var = "diet",
  feature.level = "Family",
  feature.dat.type = "proportion",
  feature.number = 10, 
  t0.level = NULL,
  ts.levels = NULL,
  theme.choice = "bw",
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fwb1vmBG3irtekTwiOlga%2FScreenshot%202023-08-05%20at%2014.33.16.png?alt=media&amp;token=8df8ecbb-8387-464e-9933-60a87819c864" alt=""><figcaption></figcaption></figure>

In the context of large-scale microbiome datasets, it is often beneficial to focus on a subset of taxa that are either abundant or exhibit significant variability. The parameters `top.k.plot` and `top.k.func` facilitate this focus:

* `top.k.func` assists in determining the criteria for this selection, offering three choices:
  * `"mean"`: Highlights taxa with the highest average abundances spread across samples.
  * `"sd"`: Selects taxa with the greatest variability (standard deviation) across samples, useful for identifying taxa with notable differences under varying conditions.
  * `"prevalence"`: Chooses taxa with the highest occurrence across samples, targeting those most consistently present.
  * Custom function: Users can input their own function to rank taxa based on a numeric vector it returns when applied to the abundance matrix. This allows for custom criteria beyond "mean", "sd", or "prevalence".

These parameters are particularly effective when generating heatmaps, as they enable concentration on the most pertinent taxa for the research question at hand.

Heatmaps are particularly insightful for discerning clusters of microbial families that exhibit similar abundance profiles across different samples. Two critical parameters, `cluster.rows` and `cluster.cols`, control the clustering behavior in these functions:

* `cluster.rows`: By default, the `generate_taxa_heatmap_long()` function will cluster rows (taxa/features) based on their abundance patterns, set by `cluster.rows = TRUE`. If researchers wish to see the taxa in their original order without clustering, they can achieve this by setting `cluster.rows = FALSE`. However, when clustering is enabled, patterns of microbial families with congruent abundance become readily discernible, painting a vivid picture of microbial dynamics.
* `cluster.cols`: The `generate_taxa_change_heatmap_long()` function allows for column clustering when `cluster.cols = TRUE`, which can be instrumental in revealing samples that share analogous abundance characteristics. This could be pivotal in unearthing hidden sample groups or conditions that exhibit similar microbial compositions. By default, this function clusters rows (`cluster.rows = TRUE`) and does not cluster columns (`cluster.cols = FALSE`).

With these parameters in mind, let's look at the implementation of these functions:

To uncover intricate abundance change patterns, `generate_taxa_change_heatmap_long()` can be used:

```r
generate_taxa_change_heatmap_long(
  data.obj = ecam.obj,
  subject.var = "studyid",
  time.var = "month_num",
  t0.level = NULL,
  ts.levels = NULL,  
  group.var = "antiexposedall",
  strata.var = "diet",
  feature.level = c("Family"),
  feature.dat.type = "proportion",
  features.plot = NULL,
  cluster.rows = NULL,
  cluster.cols = NULL,
  top.k.plot = 15,
  top.k.func = "sd",
  feature.change.func = "log fold change",
  palette = NULL,
  prev.filter = 0.01,
  abund.filter = 0.01,
  pdf = TRUE,
  file.ann = NULL  
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FK2DPL1zF4uAxGdlAi3t4%2FScreenshot%202023-10-12%20at%2018.58.00.png?alt=media&amp;token=4a14742c-9246-4ff9-82cd-9b018b1277dc" alt=""><figcaption></figcaption></figure>

For a comprehensive heatmap of taxonomic composition, `generate_taxa_heatmap_long()` can be employed:

```r
generate_taxa_heatmap_long(
  data.obj = ecam.obj,
  subject.var = "studyid",
  time.var = "month_num",
  t0.level = NULL,
  ts.levels = NULL,
  group.var = "delivery",
  strata.var = "diet",
  feature.level = "Family",
  feature.dat.type = "proportion",
  features.plot = NULL,
  top.k.plot = NULL,
  top.k.func = NULL,
  prev.filter = 0.01,
  abund.filter = 0.01,
  cluster.rows = NULL,
  cluster.cols = NULL,
  pdf = TRUE,
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F4FIKjIbzyPQ1qP0En92D%2FScreenshot%202023-10-12%20at%2019.00.58.png?alt=media&amp;token=6127bd16-e213-469c-a170-a69f745d8ffb" alt=""><figcaption><p>Longitudinal Microbiome Composition Heatmap: This heatmap visualizes the longitudinal taxonomic composition at the family level. Generated via <code>generate_taxa_heatmap_long()</code>, color intensity represents abundance. It provides an intuitive overview of community dynamics over time, stratified by delivery mode and diet. Filtering focuses the analysis on relevant families. The plot enables visualization of temporal abundance patterns.</p></figcaption></figure>

For spaghetti plots showcasing individual trajectories, `generate_taxa_indiv_spaghettiplot_long()` can be used:

```r
generate_taxa_indiv_spaghettiplot_long(
  data.obj = ecam.obj,
  subject.var = "studyid",
  time.var = "month_num", 
  t0.level = NULL,
  ts.levels = NULL,
  group.var = "diet",
  strata.var = "antiexposedall",
  feature.level = c("Phylum"),
  features.plot = NULL,
  feature.dat.type = "proportion",
  top.k.plot = 5,
  top.k.func = "mean",
  prev.filter = 0.01,
  abund.filter = 0.01,
  base.size = 16,
  theme.choice = "bw",  
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FIsFpl8v3ufRIadRUHSZa%2FScreenshot%202023-10-12%20at%2020.06.40.png?alt=media&amp;token=6d4d2bcb-3c9b-4ab3-a276-9fd8553ab11d" alt=""><figcaption><p>Individual Phylum Abundance Spaghetti Plots: This function generates spaghetti plots showing longitudinal abundance trajectories for specific phyla within each individual. It focuses on the top 5 phyla by mean abundance. Each line represents one subject's phylum abundance over time. These plots enable analysis of individual temporal dynamics.</p></figcaption></figure>

To assess group changes, `generate_taxa_spaghettiplot_long()` can be used:

```r
generate_taxa_spaghettiplot_long(
  data.obj = ecam.obj,
  subject.var = "studyid",
  time.var = "month_num",
  t0.level = NULL,
  ts.levels = NULL,
  group.var = "diet",
  strata.var = "antiexposedall",
  feature.level = c("Phylum"),
  features.plot = NULL,
  feature.dat.type = "proportion",
  top.k.plot = 3,
  top.k.func = "mean",
  prev.filter = 0,
  abund.filter = 0,
  base.size = 16,
  theme.choice = "bw",
  palette = NULL,
  pdf = TRUE,
  file.ann = NULL  
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2Fa8wRayOm49JP6PFF9cq0%2FScreenshot%202023-08-05%20at%2015.04.49.png?alt=media&amp;token=79fdb959-e8c4-4e18-8664-d544dba29489" alt=""><figcaption></figcaption></figure>

Before delving into the specifics of the `generate_taxa_boxplot_long()` function, it's worth noting the `transform` parameter. This string indicates the transformation to apply to the axis when plotting. The options are:

* `"sqrt"`: Square root transformation (default)
* `"identity"`: No transformation
* `"log"`: Logarithmic transformation. Zeros are replaced with half of the minimum non-zero value for each taxon before log transformation.

Now, for an in-depth look at the distribution of specific phyla over time, `generate_taxa_boxplot_long()` can be used:

```r
generate_taxa_boxplot_long(
  data.obj = subset_T2D.obj,
  subject.var = "subject_id",
  time.var = "visit_number_num",
  t0.level = NULL,
  ts.levels = NULL,  
  group.var = "subject_race",
  strata.var = NULL,
  feature.level = c("Family"),
  features.plot = NULL,
  top.k.plot = 8,
  top.k.func = "sd",
  feature.dat.type = "count",
  transform = "sqrt",
  prev.filter = 0.01,
  abund.filter = 0.001,
  base.size = 12,
  theme.choice = "bw",
  custom.theme = NULL,
  palette = NULL,
  pdf = TRUE,  
  file.ann = NULL,
  pdf.wid = 11,
  pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FxtlLj7gJQxMV8yTwtHzE%2FScreenshot%202023-10-12%20at%2018.56.27.png?alt=media&amp;token=55236313-1079-4e1f-bff9-ef0341e878d0" alt=""><figcaption></figcaption></figure>

To construct detailed individual boxplots, `generate_taxa_indiv_boxplot_long()` can be used:

```r
generate_taxa_indiv_boxplot_long(
    data.obj = ecam.obj,
    subject.var = "studyid",
    time.var = "month",
    t0.level = unique(ecam.obj$meta.dat$month)[1],
    ts.levels = unique(ecam.obj$meta.dat$month)[2:5],
    group.var = "diet",  
    strata.var = NULL,
    feature.level = c("Phylum"),
    feature.dat.type = "proportion",
    transform = "log",
    prev.filter = 0.01,
    abund.filter = 0.01,
    base.size = 20,
    theme.choice = "bw",
    custom.theme = NULL,
    palette = NULL,
    pdf = TRUE,
    file.ann = NULL,
    pdf.wid = 11,
    pdf.hei = 8.5
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FLGnes41A8yHvseBg8S9h%2FScreenshot%202023-10-12%20at%2020.08.07.png?alt=media&amp;token=5a347550-cb81-4584-b14a-ea580db00ee4" alt=""><figcaption></figcaption></figure>


# One-Click Reports Generation

Automate integrated analysis reporting for longitudinal microbiome studies with MicrobiomeStat.

MicrobiomeStat provides an efficient solution by generating integrated reports for longitudinal studies. These reports include:

* Visualizations to illustrate key findings
* Statistical summaries that highlight significant results

The `mStat_generate_report_long()` function generates an integrated reports. It performs:

* **Alpha diversity**: Functions used include `generate_alpha_boxplot_long()`, `generate_alpha_spaghettiplot_long()`, `generate_alpha_trend_test_long()`, and `generate_alpha_volatility_test_long()`.
* **Beta diversity**: Functions used include `generate_beta_ordination_long()`, `generate_beta_pc_boxplot_long()`, `generate_beta_change_spaghettiplot_long()`, `generate_beta_trend_test_long()`, and `generate_beta_volatility_test_long()`.
* **Feature-level**: Functions used include `generate_taxa_areaplot_long()`, `generate_taxa_heatmap_long()`, `generate_taxa_trend_test_long()`, `generate_taxa_volatility_test_long()`, `generate_taxa_boxplot_long()`, `generate_taxa_spaghettiplot_long()`, `generate_taxa_trend_volcano_long()`, `generate_taxa_volatility_volcano_long()`, `generate_taxa_barplot_long()`, `generate_taxa_change_heatmap_long()`, `generate_taxa_indiv_spaghettiplot_long()`, and `generate_taxa_indiv_boxplot_long()`.

The function then compiles these analyses into a comprehensive PDF report. The report includes:

* A data summary from `mStat_summarize_data_obj()`
* Visual representations like alpha diversity boxplots, beta diversity ordination plots, and taxa composition visualizations
* Tables detailing statistical test results
* Commentary on key findings

Before using the function, it's important to understand the parameters:

* `data.obj`: A list object in a specific format to MicrobiomeStat, which can include components such as feature.tab (matrix), feature.ann (matrix), meta.dat (data.frame), tree, and feature.agg.list (list). This object can be converted from other formats using several functions from the MicrobiomeStat package, or constructed manually. For more detailed information on how to convert data from other formats or how to construct the `data.obj` manually, please refer to the following page.

{% content-ref url="/pages/WK9NC4ukGZbAvQGuCKUR" %}
[Creating the MicrobiomeStat Data Object](/setting-up-microbiomestat-installation-and-data-preparation/laying-the-foundation-creating-the-microbiomestat-data-object)
{% endcontent-ref %}

* Once the data has been successfully constructed, users may wish to perform minor adjustments to the data, such as removing levels with few subjects from the group.var. In such cases, you can refer to this document for guidance.

{% content-ref url="/pages/LLh6oXlfW0M2j5bSG5jU" %}
[Data Filtering](/data-manipulation-and-transformation/data-filtering)
{% endcontent-ref %}

* `group.var`: The name of the variable of primary interest.
* `test.adj.vars`: Names of columns in the metadata containing covariates to be adjusted for in statistical tests and models. Default is NULL, which indicates no covariates are adjusted for in statistical testing.
* `vis.adj.vars`: For alpha and beta diversity visualization functions, the `vis.adj.vars` parameter designates the column names in the metadata that correspond to covariates. When covariates are specified, `vis.adj.vars` will adjust the `alpha.obj` and `dist.obj` accordingly, resulting in an alpha diversity index and a distance matrix that have been modified to account for the additional covariates.
* `strata.var`: Variable to stratify the analysis by (optional).
* `subject.var`: Variable name used for subject identification.
* `time.var`: This parameter represents the time variable in your data. It can take three forms:
  * Numeric: When `time.var` is numeric, you don't need to set `t0.level` and `ts.levels`, as they will be automatically arranged in ascending order.
  * Factor: If `time.var` is a factor, and if `t0.level` and `ts.levels` are not set, they will be automatically arranged according to the levels of the factor. However, if you have specific needs for the order of the levels, you can manually adjust `t0.level` and `ts.levels`.
  * Character: If `time.var` is character, it's recommended to manually set `t0.level` and `ts.levels`, as the automatic arrangement might not reflect the correct order.
* `t0.level`: This parameter represents the first time point in your data.
* `ts.levels`: This parameter represents the other time points in your data, arranged in the order you desire, excluding `t0.level`.
* `alpha.obj`: An optional list containing pre-calculated alpha diversity indices. If NULL (default), alpha diversity indices will be calculated using `mStat_calculate_alpha_diversity` function.
* `alpha.name`: The alpha diversity index to be plotted. Supported indices include "shannon", "simpson", "observed\_species", "chao1", "ace", and "pielou". If you are not interested in alpha diversity for datasets other than microbiome data, you can set this parameter to NULL. In this case, the report will not include any alpha diversity results, only feature-level analysis will be presented.
* `depth`: An integer. The sequencing depth to be used for the "Rarefy" and "Rarefy-TSS" methods. If NULL, the smallest total count across samples is used as the rarefaction depth.
* `dist.obj`: Distance matrix between samples, usually calculated using `mStat_calculate_beta_diversity` function. If NULL, beta diversity will be automatically computed from `data.obj` using `mStat_calculate_beta_diversity`.
* `dist.name`: A character vector specifying which beta diversity indices to calculate. Supported indices are "BC" (Bray-Curtis), "Jaccard", "UniFrac" (unweighted UniFrac), "GUniFrac" (generalized UniFrac), "WUniFrac" (weighted UniFrac), and "JS" (Jensen-Shannon divergence). Similar to `alpha.name`, if you do not care about beta diversity for non-microbiome data, you can set this parameter to NULL. The report will then exclude beta diversity results and only provide feature-level analysis.
* `pc.obj`: A list containing the results of dimension reduction/Principal Component Analysis. This should be the output from functions like `mStat_calculate_PC`, containing the PC coordinates and other metadata. If NULL (default), dimension reduction will be automatically performed using metric multidimensional scaling (MDS) via `mStat_calculate_PC`. The `pc.obj` list structure should contain:
  * `$points`: A matrix with samples as rows and PCs as columns containing the coordinates.
  * `$eig`: Eigenvalues for each PC dimension.
  * `$vectors`: Loadings vectors for features onto each PC.
  * Other metadata like `$method`, `$dist.name`, etc. See `mStat_calculate_PC` function for details on output format.
* `vis.feature.level`: The column name in the feature annotation matrix (feature.ann) of data.obj to use for visualization and plotting. This can be a taxonomic level like "Phylum" or "Genus" for microbiome data. For KEGG data, this could be a pathway level such as "Pathway\_L1", "Pathway\_L2", or "Pathway\_L3". If you want to avoid aggregation, you can set it to "original", and no aggregation will be performed. The selected feature level will be used to aggregate the data at the specified level in the generated visualizations.
* `test.feature.level`: The column name in the feature annotation matrix (feature.ann) of data.obj to use for testing or analytical purposes. This can be a taxonomic level like "Phylum" or "Genus" for microbiome data. For single-cell data, this could be a cell type identifier such as "CellType". For KEGG data, this could be a pathway level such as "Pathway\_L1", "Pathway\_L2", or "Pathway\_L3". If you want to avoid aggregation, you can set it to "original", and no aggregation will be performed. The selected feature level will be used to aggregate the data at the specified level for statistical tests and models.
* `feature.dat.type`: The type of the feature data, which determines how the data is handled in downstream analyses. Should be one of: "count": Raw count data, will be normalized internally. "proportion": Data that has already been normalized to proportions/percentages. "other": Other data types such as transcriptomic and metabolomic data, where the user will decide the QC, normalization, and transformation. If the user wants to normalize/transform the abundance data on his own way, he can also use this option.
* `feature.change.func`: A function or character string specifying how to calculate the change from baseline value. This allows flexible options:
  * If a function is provided, it will be applied to each row to calculate change. The function should take 2 arguments: value at timepoint t and value at baseline t0.
  * If a character string is provided, following options are supported:
    * 'relative change': (value\_t - value\_t0) / (value\_t + value\_t0)
    * 'absolute change': value\_t - value\_t0
    * 'log fold change': log2(value\_t + 1e-5) - log2(value\_t0 + 1e-5)
  * Default is 'relative change'.
  * If none of the above options are matched, an error will be thrown indicating the acceptable options or prompting the user to provide a custom function.
* `feature.box.axis.transform`: A string indicating the transformation to apply to the data before plotting. Options are:
  * "sqrt": Square root transformation (default),
  * "identity": No transformation,
  * "log": Logarithmic transformation.
* `feature.analysis.rarafy`: Logical, indicating whether to rarefy the data at the feature-level for analysis. If TRUE, the feature data will be rarefied before analysis. Default is TRUE.
* `bar.area.feature.no`: A numeric value indicating the number of top abundant features to retain in both barplot and areaplot. Features with average relative abundance ranked below this number will be grouped into 'Other'. Default 30.
* `heatmap.feature.no`: A numeric value indicating the number of top abundant features to retain in the heatmap. Features with average relative abundance ranked below this number will be grouped into 'Other'. Default 30.
* `feature.mt.method`: Character, multiple testing method for features, "fdr", "bonferroni", or "none", default is "fdr".
* `feature.sig.level`: Numeric, significance level cutoff for highlighting features, default is 0.1.
* `base.size`: Base font size for the generated plots.
* `theme.choice`: Plot theme choice. Can be one of: "prism": ggprism::theme\_prism(), "classic": theme\_classic(), "gray": theme\_gray(), "bw": theme\_bw().
* `output.file`: A character string specifying the output file name for the report. Full path can be specified, e.g., "path\_to\_your\_location/report". The file extension (.pdf or .html) will be automatically added based on the `output.format` if not already present. This parameter also determines the title of the generated report. For example, if set to "path\_to\_your\_location/my\_report", the report title will be "my\_report".
* `output.format`: A character string specifying the desired output format of the report. Must be either "pdf" or "html". Default is c("pdf", "html"), which will use the first value ("pdf") if not explicitly specified. This parameter determines whether the report will be generated as a PDF or HTML document.

Note: Before running the function, please be aware of potential compatibility issues between RStudio and LaTeX. These issues can lead to problems such as images from the RStudio Viewer appearing in unexpected locations in the PDF report. To avoid this, it's recommended to clear the current images in the RStudio Viewer before running the function. You can do this by clicking on the broom icon in the RStudio Viewer.

Now, let's see how we can implement the function:

```r
# Load the data
data(subset_T2D.obj)
data.obj = subset_T2D.obj

# Specify variable names
group.var = "subject_race" # Variable used for grouping samples
subject.var = "subject_id" # Variable used for subject identification
time.var = "visit_number_num" # Variable used for time points
strata.var = "subject_gender" # Variable to stratify by in diversity calculations and statistical tests

# Specify diversity indices
alpha.name = c("shannon", "observed_species") # Alpha diversity indices to calculate
dist.name = c("BC",'Jaccard') # Beta diversity indices to calculate

# Specify feature levels for visualization and testing
vis.feature.level = c("Family","Genus") # Feature levels to use for visualization
test.feature.level = c("Family") # Feature level to use for testing

# Specify other parameters
feature.dat.type = "count" # Type of the feature data
theme.choice = "bw" # Theme choice for the plots
base.size = 20 # Base size for the plots
feature.mt.method = "none" # Multiple testing method for features
feature.sig.level = 0.3 # Significance level cutoff for highlighting features
feature.box.axis.transform = "sqrt"

# Specify output file
output.file = "path/to/Omics Analysis Report.pdf" # Replace with your own file path for the output report

# Specify parameters for feature retention
bar.area.feature.no = 30 # Number of top abundant features to retain in barplot and areaplot
heatmap.feature.no = 30 # Number of top abundant features to retain in heatmap

# Specify optional parameters
dist.obj = NULL # Replace with a pre-computed distance matrix if available
alpha.obj = NULL # Replace with a pre-computed alpha diversity matrix if available
feature.change.func = "relative change" # Function for calculating feature change

# Run the function
mStat_generate_report_long(
  data.obj = data.obj,
  group.var = group.var,
  test.adj.vars = NULL,
  vis.adj.vars = NULL,
  strata.var = strata.var,
  subject.var = subject.var,
  time.var = time.var,
  t0.level = NULL,
  ts.levels = NULL,
  alpha.obj = alpha.obj,
  alpha.name = alpha.name,
  dist.obj = dist.obj,
  dist.name = dist.name,
  feature.change.func = feature.change.func,
  vis.feature.level = vis.feature.level,
  test.feature.level = test.feature.level,
  bar.area.feature.no = bar.area.feature.no,
  heatmap.feature.no = heatmap.feature.no,
  feature.dat.type = feature.dat.type,
  feature.mt.method = feature.mt.method,
  feature.sig.level = feature.sig.level,
  feature.box.axis.transform = feature.box.axis.transform,
  theme.choice = theme.choice,
  base.size = base.size,
  output.file = output.file
)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FDURk8znAswSl5IPH8Wbe%2FOmics%20Analysis%20Report%2069%20subjects_page-0001.jpg?alt=media&amp;token=a29761b1-ba4b-4635-b2dd-664eb3b417f8" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FIU6u9CQuwMvgiH68IjLQ%2FOmics%20Analysis%20Report%2069%20subjects_page-0002.jpg?alt=media&amp;token=f935fc73-4465-4fac-8551-d3b023e7e7ac" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FpCULlbekNRXrccpIIdgT%2FOmics%20Analysis%20Report%2069%20subjects_page-0003.jpg?alt=media&amp;token=b0a7e356-eb8b-440b-bb24-681256d7d99f" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FcQq8uwuvV0pjfT7GNg6R%2FOmics%20Analysis%20Report%2069%20subjects_page-0004.jpg?alt=media&amp;token=3da68f2f-c5cb-40fe-b562-697052f19031" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FEPNBqGk4j3ugeIi0qJ7E%2FOmics%20Analysis%20Report%2069%20subjects_page-0005.jpg?alt=media&amp;token=83a96d03-6360-4dc2-b5ac-a5d6477032f2" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F6Cr6h2XhD6k1eJdb6Qm4%2FOmics%20Analysis%20Report%2069%20subjects_page-0006.jpg?alt=media&amp;token=4eaa63ae-a3db-4224-8a71-6ed9c0248592" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FogbJg2gwrka7ZbhUSQjU%2FOmics%20Analysis%20Report%2069%20subjects_page-0007.jpg?alt=media&amp;token=9ffeb8a2-d201-4722-ab0d-9364aa46f7e1" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FnJSKDSfBQzovadVSJvi7%2FOmics%20Analysis%20Report%2069%20subjects_page-0008.jpg?alt=media&amp;token=948c1244-b25e-47e9-bd3d-cd1e8e9381db" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FwgPRaVIdthoA2ILPfBlv%2FOmics%20Analysis%20Report%2069%20subjects_page-0009.jpg?alt=media&amp;token=73f63b25-0eec-47f5-be68-6284dc14ddba" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FQHhc8vPmx4MnWubhAGn7%2FOmics%20Analysis%20Report%2069%20subjects_page-0010.jpg?alt=media&amp;token=ef98dd06-9cc5-4ce7-b2e7-c67f1dae05a3" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FJtRJ0TotWgAvMJaFrW5w%2FOmics%20Analysis%20Report%2069%20subjects_page-0011.jpg?alt=media&amp;token=de279d57-28fc-4446-900c-cdb84da40591" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FfbhyoZ6xcULcXotS9yQZ%2FOmics%20Analysis%20Report%2069%20subjects_page-0012.jpg?alt=media&amp;token=b30883db-684a-4f36-be03-09e97060cf82" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FitorbOOe7gHlUJWUkMi3%2FOmics%20Analysis%20Report%2069%20subjects_page-0013.jpg?alt=media&amp;token=562569be-5af8-4d26-aebc-1ea3140d9097" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F8xoHxCsdD04BDFMeSkK1%2FOmics%20Analysis%20Report%2069%20subjects_page-0014.jpg?alt=media&amp;token=78bb9e7c-6dd0-4123-b1a2-88d5de42e28e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FH7SE6a8y0Kuaqf98Pvfx%2FOmics%20Analysis%20Report%2069%20subjects_page-0015.jpg?alt=media&amp;token=f6ec7590-f281-4cde-8a07-eabf2a3fc774" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FDQTy7LMEZY7LY0r7XXO4%2FOmics%20Analysis%20Report%2069%20subjects_page-0016.jpg?alt=media&amp;token=3011441a-0168-482e-a062-eee893dc2822" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FEiXhyxh5hmGXPFiaOZ8u%2FOmics%20Analysis%20Report%2069%20subjects_page-0017.jpg?alt=media&amp;token=4f2257fa-ed37-4f60-8d14-b21d4057d7f7" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F9Y9m9nkVJMQlyZYA1him%2FOmics%20Analysis%20Report%2069%20subjects_page-0018.jpg?alt=media&amp;token=53d65287-8595-4dcb-9508-528bcdabbbd9" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F44dGAwfnuYWgGgJpq3Da%2FOmics%20Analysis%20Report%2069%20subjects_page-0019.jpg?alt=media&amp;token=755c20fa-7ad3-4b15-a503-e12f09a9e9e2" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FK7gtAPrqiW6uLSuFdpR5%2FOmics%20Analysis%20Report%2069%20subjects_page-0020.jpg?alt=media&amp;token=b26bce9b-2e58-4cc0-a7cd-5770a476416b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FSmXbWarHYB98t9d2s96r%2FOmics%20Analysis%20Report%2069%20subjects_page-0021.jpg?alt=media&amp;token=e08c524f-6cc3-4968-84b2-f98fdf08df87" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F2kfqEyGu98sWE5TAnTHV%2FOmics%20Analysis%20Report%2069%20subjects_page-0022.jpg?alt=media&amp;token=045f186e-6485-4f9f-83de-504d804cd195" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FeypqOZHZD2SY3NlV6Wv8%2FOmics%20Analysis%20Report%2069%20subjects_page-0023.jpg?alt=media&amp;token=017b31de-ad84-425c-a880-19ade39e7736" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F982fziIqKpZ5zrRCOg9Y%2FOmics%20Analysis%20Report%2069%20subjects_page-0024.jpg?alt=media&amp;token=3c77d139-74ee-4b72-a188-94298a7d8def" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FvJygftqvue4q7DruPTnP%2FOmics%20Analysis%20Report%2069%20subjects_page-0025.jpg?alt=media&amp;token=d94c64de-4f67-4543-8ff5-4d388d411808" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FkF7Bj6b6pEuNbosx3hwF%2FOmics%20Analysis%20Report%2069%20subjects_page-0026.jpg?alt=media&amp;token=b6c87d72-bb0b-4073-86ee-23de1dc43131" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FO77nveTHMNcQYpRGXP6i%2FOmics%20Analysis%20Report%2069%20subjects_page-0027.jpg?alt=media&amp;token=67b85d17-adaf-4b3a-956a-de0c7afabd6c" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FcIyD8creTID0nGzczAzN%2FOmics%20Analysis%20Report%2069%20subjects_page-0028.jpg?alt=media&amp;token=6cbb9055-164c-4471-91cc-4d7bb3851d89" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FBkObnhMuUS2FTbG3KH9k%2FOmics%20Analysis%20Report%2069%20subjects_page-0029.jpg?alt=media&amp;token=9c7b8957-40c3-42ac-bbbd-a3e40cb32c82" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FJ5X0BIyrgf4Pg8gPrVei%2FOmics%20Analysis%20Report%2069%20subjects_page-0030.jpg?alt=media&amp;token=e7f057e0-4790-4355-90fd-e3f47c171070" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FOv2IOvp5ECvyztfIKcpx%2FOmics%20Analysis%20Report%2069%20subjects_page-0031.jpg?alt=media&amp;token=04aa55de-81eb-4b9a-b513-cee0fc2b0cfe" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FFQHB0NneCGekGdeWngpU%2FOmics%20Analysis%20Report%2069%20subjects_page-0032.jpg?alt=media&amp;token=c3720afe-23fa-42e3-b62c-70e12d16f944" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F45mg6PyFHrtt8J3nafxr%2FOmics%20Analysis%20Report%2069%20subjects_page-0033.jpg?alt=media&amp;token=3ae889fb-75b7-4099-a442-33951e06b019" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FyljBEj0T2aIbLN0L5vH8%2FOmics%20Analysis%20Report%2069%20subjects_page-0034.jpg?alt=media&amp;token=c8263ea5-7ac8-43ef-ba68-357d08e80bd3" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F380pNj18x07bR2bRTfZM%2FOmics%20Analysis%20Report%2069%20subjects_page-0035.jpg?alt=media&amp;token=2cc0cc85-f3a8-4d79-90eb-bbcc19199a17" alt=""><figcaption></figcaption></figure>

{% file src="/files/555FEzPnc14rL5k11mvE" %}

The automated report reduces the need for manual analysis and ensures consistency. By integrating results from different analytical dimensions, it provides a comprehensive view of the data.

MicrobiomeStat equips researchers with automated workflows to quickly synthesize and report findings from longitudinal studies. The standardized reports integrate multidimensional perspectives, including alpha diversity, beta diversity, and differential abundance analysis, for comprehensive insights.

The reports contain clear visualizations and statistical summaries to aid in biological interpretation and facilitate result dissemination. By automating time-consuming manual analytical tasks, MicrobiomeStat enables rapid, reproducible, and robust reporting to advance microbiome research.


# Data Summary

This page provides an overview of the mStat\_summarize\_data\_obj() function, which summarizes key components of a MicrobiomeStat data object.

## Overview

The `mStat_summarize_data_obj()` function in the MicrobiomeStat package provides a comprehensive summary of a MicrobiomeStat data object, ensuring users have a clear understanding of their data structure and contents. Here are the main components and features of the function:

* **feature.tab**: This is the microbiome feature table. The function computes and displays various summary statistics for this table such as minimum, maximum, average, and median reads per sample, the proportion of zero counts, and the count of features that only appear once in the data.
* **meta.dat**: Contains sample metadata. The function checks for the presence of this component and computes the number of metadata variables. If time-series information is provided through the `time.var` argument, it can further display histograms depicting sample counts over time, either ungrouped or stratified by a specified `group.var`. Additionally, the function showcases a boxplot of sequencing depth over time, a crucial visualization when dealing with longitudinal microbiome data.
* **feature.ann**: Represents feature annotations. For each column in the feature annotations, the function computes the proportion of missing annotations, which can be vital for downstream analysis that relies on these annotations.
* **tree**: This is an optional phylogenetic tree. The function checks for its presence in the data object and informs the user whether the tree exists or not.
* **feature.agg.list**: The function checks for the existence of a list of aggregated taxonomies and returns the names of taxonomies that have been aggregated, if available.

To support visualization, the function integrates with the `ggplot2` package to produce histograms and boxplots. It offers flexibility through optional parameters like `time.var`, `group.var`, and `palette`, allowing users to customize visualizations based on time-series data and specific grouping variables. The produced summary table offers a snapshot of the dataset's key characteristics, aiding in data exploration and ensuring appropriate pre-processing before advanced analyses.

## Usage

```markdown
mStat_summarize_data_obj(
  data.obj,
  time.var = NULL, 
  group.var = NULL,
  palette = NULL
)
```

* `data.obj`: MicrobiomeStat data object to summarize
* `time.var`: Optional time variable column name in meta.dat to analyze temporal distribution
* `group.var`: Optional grouping variable in meta.dat to group time histogram
* `palette`: Vector of colors for grouping in histogram

## Example

In this example, we'll demonstrate how to use the `mStat_summarize_data_obj()` function from the MicrobiomeStat package on a typical dataset `subset_T2D.obj`.

```r
library(MicrobiomeStat)

data(subset_T2D.obj)

# Summarize data object
summary <- mStat_summarize_data_obj(subset_T2D.obj, "visit_number", "subject_race")

# View summary
print(summary)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F2f2rsCgVh6E2uqILwgxo%2FScreenshot%202023-08-07%20at%2018.55.31.png?alt=media&amp;token=4e986d1c-21a3-4f45-b7c7-6f40419d7129" alt=""><figcaption><p>Histogram of sample counts over time by subject race using mStat_summarize_data_obj() on the subset_T2D dataset. The plot shows the distribution of sample counts across visit numbers, grouped by subject race. Samples from African American subjects are shown in red, while samples from Caucasian subjects are shown in blue. This allows visual inspection of the longitudinal sampling distribution stratified by an important covariate. The mStat_summarize_data_obj() function and inclusion of grouping variables enables informative exploration of metadata and temporal distributions.</p></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FP4OZQxds9D6KdMAWYMLC%2FScreenshot%202023-10-08%20at%2021.44.44.png?alt=media&amp;token=85f323e5-6233-49bd-9edf-c49fa0f7b62f" alt=""><figcaption><p>Using the <code>mStat_summarize_data_obj()</code> function on a specified dataset, a boxplot depicting sequencing depth over time has been generated. This plot illustrates the distribution of sequencing depth across various time points, stratified by a provided grouping variable, such as patient race. For instance, if the grouping variable is patient race, samples from African American subjects might be shown in red, while those from Caucasian subjects could be depicted in blue. This visualization aids in the visual inspection of the longitudinal sampling distribution when stratified by a significant covariate. The <code>mStat_summarize_data_obj()</code> function, combined with the inclusion of grouping variables, facilitates an informative exploration of metadata and temporal distributions.</p></figcaption></figure>

After executing the `mStat_summarize_data_obj()` function, we obtain a structured summary table that captures the essential attributes and metrics of the `subset_T2D.obj` dataset. This table encompasses various facets, from basic statistical properties of the microbiome feature table to the detailed insights about metadata, feature annotations, and time-series distribution. Let's delve into the results:

| Category                | Variable                                     | Value    |
| ----------------------- | -------------------------------------------- | -------- |
| Basic Statistics        | Number of samples                            | 575      |
| Basic Statistics        | Number of features                           | 9533     |
| Basic Statistics        | Min. reads per sample                        | 2007     |
| Basic Statistics        | Max. reads per sample                        | 91908    |
| Basic Statistics        | Total reads across all samples               | 14138179 |
| Basic Statistics        | Average reads per sample                     | 1483.078 |
| Basic Statistics        | Median reads per sample                      | 21062    |
| Basic Statistics        | Proportion of zero counts                    | 0.963    |
| Basic Statistics        | Count of features that only appear once      | 1505     |
| Metadata                | Number of metadata variables                 | 14       |
| Feature Annotations     | Proportion of missing annotations in Kingdom | 0        |
| Feature Annotations     | Proportion of missing annotations in Phylum  | 0        |
| Feature Annotations     | Proportion of missing annotations in Class   | 0.002    |
| Feature Annotations     | Proportion of missing annotations in Order   | 0.012    |
| Feature Annotations     | Proportion of missing annotations in Family  | 0.128    |
| Feature Annotations     | Proportion of missing annotations in Genus   | 0.484    |
| Feature Annotations     | Proportion of missing annotations in Species | 0.887    |
| Phylogenetic Tree       | Exists in the dataset                        | No       |
| Time-Series Information | Number of unique time points                 | 6        |
| Time-Series Information | Sample count at time point: 1                | 117      |
| Time-Series Information | Sample count at time point: 2                | 104      |
| Time-Series Information | Sample count at time point: 3                | 97       |
| Time-Series Information | Sample count at time point: 4                | 104      |
| Time-Series Information | Sample count at time point: 5                | 79       |
| Time-Series Information | Sample count at time point: 6                | 74       |

In summary, the `mStat_summarize_data_obj()` function furnishes a detailed and structured overview of a MicrobiomeStat data object. This comprehensive breakdown ensures that the user possesses a firm grasp on their data's intricacies and characteristics, setting the stage for well-informed subsequent statistical analyses.


# Data Aggregation

Data aggregation summarizes microbiome data at broader taxonomic levels. This reveals intuitive compositional patterns and trends.

Data aggregation plays a vital role in simplifying and structuring microbiome data analysis. By summarizing data at broader taxonomic levels or by subject variables, users can gain clearer insights into compositional patterns within their datasets. MicrobiomeStat offers several functions for this purpose: `mStat_aggregate_data()`, `mStat_aggregate_by_taxonomy()`, and `mStat_aggregate_by_taxonomy2()`.

## 1. mStat\_aggregate\_data()

### Function Overview

The `mStat_aggregate_data()` function is designed to aggregate a microbiome dataset based on a specified subject variable. Additionally, users have the option to further stratify the aggregation through an additional variable.

```r
 # Prepare data for the function
data(peerj32.obj)

 # Call the function
aggregated_data <- mStat_aggregate_data(
  data.obj = peerj32.obj,
  subject.var = "subject",
  strata.var = NULL
)
```

Where:

* `data.obj`: Refers to the data object within MicrobiomeStat that needs to be aggregated.
* `subject.var`: Represents the primary variable for aggregation, such as a patient ID.
* `strata.var`: Acts as an optional stratification variable, allowing for more nuanced aggregation based on groups or categories.
* `meta.handle.conflict`: Controls how metadata conflicts are handled when multiple samples per subject have different values. Options are `"first"` (use the first value, default), `"stop"` (raise an error), or `"summarise"` (summarize conflicting values).

In this example, we've prepared the data for our function using the `peerj32.obj` dataset. Next, we call the `mStat_aggregate_data()` function to aggregate the data based on the "subject" variable. We haven't provided any stratification variable (`strata.var`), so the function will aggregate solely based on the "subject" variable.

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FjKUwYsItks2GXlWU3UWX%2FScreenshot%202023-10-09%20at%2019.22.06.png?alt=media&amp;token=37105e1c-5e0e-4a0f-a941-99291f4f372e" alt=""><figcaption><p><strong>Figure 1:</strong> Snapshot of the <code>feature.tab</code> component of the <code>peerj32.obj</code> dataset before aggregation. This table showcases the microbial feature abundances across multiple samples, illustrating the raw distribution and counts of different microbiome features in the original dataset.</p></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FBixto8RDEXrKCPOTfWBj%2FScreenshot%202023-10-09%20at%2019.22.53.png?alt=media&amp;token=202858a8-89ec-44e4-810b-041fb176c42d" alt=""><figcaption><p><strong>Figure 2:</strong> Overview of the <code>meta.dat</code> component of the <code>peerj32.obj</code> dataset prior to aggregation. This table provides metadata information for each sample, including various attributes and characteristics that offer context and additional information about the samples in the dataset.</p></figcaption></figure>

After the aggregation, the data will be restructured and summarized based on the specified "subject" variable.

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F6AcYvJtyoPRNfG4si5LI%2FScreenshot%202023-10-09%20at%2019.23.36.png?alt=media&amp;token=21ed1f33-34ea-4699-a716-edd81ffea81e" alt=""><figcaption><p><strong>Figure 3:</strong> Snapshot of the <code>feature.tab</code> component after applying the <code>mStat_aggregate_data()</code> function. The table now reflects aggregated microbial feature abundances based on the "subject" variable, summarizing the microbiome features for each unique subject in a consolidated manner.</p></figcaption></figure>

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FZAL8MeJRnps9iq1hwndA%2FScreenshot%202023-10-09%20at%2019.24.06.png?alt=media&amp;token=384812cc-1f09-4a00-8d30-8a99a85496c3" alt=""><figcaption><p><strong>Figure 4:</strong> Overview of the <code>meta.dat</code> component post-aggregation. The metadata table has been restructured and condensed to correspond with the aggregated samples in <code>feature.tab</code>, offering a streamlined view of sample attributes in the aggregated dataset.</p></figcaption></figure>

## Detailed Breakdown

The `mStat_aggregate_data()` function performs the following significant steps:

1. **Initialization and Message Communication:** The function starts by conveying to the user its intent to aggregate the data based on the provided criteria.
2. **Aggregation of `feature.agg.list`:** Before diving into the primary feature table aggregation, the function examines whether the `data.obj` contains a `feature.agg.list`. If present, this list contains feature abundance tables that need to be aggregated in a similar manner to the primary feature table.
3. **Main Feature Table Aggregation (`feature.tab`):** The microbiome feature abundances from `feature.tab` are grouped and summarized based on the provided `subject.var` and, if available, `strata.var`. This forms the crux of the aggregation process, effectively collapsing the dataset based on the selected variables.
4. **Metadata Aggregation (`meta.dat`):** The metadata accompanying the samples is equally crucial. The function groups and summarizes this data analogously, ensuring that the metadata remains consistent with the aggregated feature table.
5. **Other Data Elements:** The function retains other essential components of the `data.obj`, like the `tree` and `feature.ann`, ensuring the output remains comprehensive.
6. **Output Formation:** The function culminates by packaging all processed components into a new MicrobiomeStat data object, ready for further exploration and analysis.

## Practical Applications

The `mStat_aggregate_data()` function is indispensable for various microbiome data analysis ventures:

* **Simplifying Complex Data:** By conglomerating data based on subjects or other criteria, it renders dense microbiome tables more interpretable and manageable.
* **Harnessing Detailed Metadata:** The function's ability to integrate and process associated metadata means users can make better-informed decisions based on contextual information alongside microbial abundances.
* **Stratification and Comparative Analysis:** Should users provide a `strata.var`, the function creates a stratified view of the microbiome landscape, vital for dissecting differences among distinct groups or conditions.
* **Streamlined Longitudinal and Cohort Studies:** The aggregated view of the data, especially when based on subjects or time-points, is invaluable for long-term studies, ensuring patterns across time or multiple visits are discernible.

In essence, the `mStat_aggregate_data()` function is a robust tool, simplifying and restructuring microbiome datasets for clearer interpretation and deeper analytical dives.

## 2. mStat\_aggregate\_by\_taxonomy()

### Function Overview

The `mStat_aggregate_by_taxonomy()` function facilitates the aggregation of microbiome data based on specified taxonomic levels, such as "Phylum" or "Family". This function is primarily designed to populate the `feature.agg.list` within the `data.obj`. Through this, microbiome datasets can be represented in terms that are more biologically interpretable. It's noteworthy that if `feature.agg.list` is not generated prior to using certain other functions within the package, those functions will automatically invoke `mStat_aggregate_by_taxonomy()` to ensure the necessary aggregation is performed.

### Usage

```r
 data(peerj32.obj)

 # Specify the taxonomy level
 feature.level <- c("Phylum", "Family")

 # Aggregate data object by taxonomy level
 peerj32.obj <- mStat_aggregate_by_taxonomy(peerj32.obj, feature.level)
```

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FMS4FEaiyGFmnAnPHYP6A%2FScreenshot%202023-10-09%20at%2019.42.36.png?alt=media&amp;token=20aa3021-2c53-4b3c-a7b4-f04d49d03700" alt=""><figcaption><p>An illustrative representation of the <code>feature.agg.list</code> created by the <code>mStat_aggregate_by_taxonomy()</code> function, showcasing the aggregation results.</p></figcaption></figure>

### Detailed Breakdown

The `mStat_aggregate_by_taxonomy()` function undertakes the following steps:

1. **Verification:** It checks if the `feature.level` is provided.
2. **Data Joining:** Loads the OTU table (`feature.tab`) and taxonomy table (`feature.ann`) from the data object. It then joins these two tables based on row names, ensuring a unified dataset.
3. **Consistency Check:** Validates that the row names between the OTU and taxonomy tables are consistent. It provides messages if there are discrepancies.
4. **Taxonomic Aggregation:** Using the chosen taxonomic level, the function aggregates the data, transforming OTUs to a higher taxonomy level representation.
5. **List Update:** It updates or creates the `feature.agg.list` within the data object to include the aggregated tables for the specified taxonomic levels.

### Practical Applications

The `mStat_aggregate_by_taxonomy()` function proves beneficial in scenarios like:

* **Biological Interpretation:** The function aids in presenting data in a manner that’s biologically insightful by focusing on higher taxonomic ranks like Phylum or Family.
* **Data Simplification:** The microbiome OTU tables can be extremely detailed. By aggregating data based on taxonomy, the table's complexity is reduced, making it more manageable and comprehensible.
* **Consistent Data Representation:** By aligning the OTU and taxonomy tables, the function ensures the dataset's integrity and consistency. This is particularly crucial as mismatches can lead to erroneous interpretations or analytical challenges.

Overall, the `mStat_aggregate_by_taxonomy()` function serves as an indispensable tool for microbiome researchers, enabling them to transmute granular OTU-level data into a higher, more interpretable taxonomic hierarchy.

## 3. mStat\_aggregate\_by\_taxonomy2()

### Function Overview

Unlike its predecessor, the `mStat_aggregate_by_taxonomy2` function allows aggregation based on a single taxonomic level at a time. It focuses on merging the OTU table and the taxonomy table based on the provided taxonomy level.

### Usage

```r
feature.tab <- matrix(c(5, 10, 0, 7, 0, 20), nrow=3, byrow=TRUE)
rownames(feature.tab) <- c("OTU1", "OTU2", "OTU3")
colnames(feature.tab) <- c("Sample1", "Sample2")

feature.ann <- data.frame(Phylum = c("Bacteroidetes", "Firmicutes", "Bacteroidetes"))
rownames(feature.ann) <- c("OTU1", "OTU2", "OTU3")

result <- mStat_aggregate_by_taxonomy2(feature.tab, feature.ann, feature.level="Phylum")
```

### Detailed Breakdown

1. **Input Verification:** The function first ensures that a `feature.level` is provided and that it specifies a single taxonomy level.
2. **Consistency Checks:** Before proceeding with aggregation, it verifies that the row names of the OTU (`feature.tab`) and taxonomy (`feature.ann`) tables match.
3. **Data Merging:** It performs an inner join on the OTU and taxonomy tables. This step ensures only rows with consistent names across both tables are considered for aggregation.
4. **Aggregation:** Data is then aggregated based on the provided taxonomy level, with any missing taxonomy labels being replaced with the term "Unclassified".
5. **Final Cleanup:** Finally, rows in the aggregated table with all zeros (i.e., no counts) are removed.

### Practical Applications

* **Single-level Focus:** This function is perfect for users who wish to focus on a specific taxonomic level without any distractions.
* **Consistency Checks:** It ensures data integrity by comparing row names between the OTU and taxonomy tables, alerting users to discrepancies.
* **Data Reduction:** This function simplifies datasets by aggregating at the specified taxonomy level, making it more digestible for subsequent analyses.


# Data Normalization

Data normalization is an essential step in microbiome data analysis. It helps account for sequencing depth differences and make samples comparable.

Microbiome data often exhibit significant variance in sequencing depth among samples. Such variances, if unaccounted for, can skew the analysis and interpretation. Data normalization is crucial to account for this technical variation, ensuring that samples are comparable and results are robust.

MicrobiomeStat provides several normalization techniques. These can be broadly categorized into:

1. Rarefaction
2. Scaling approaches like TSS, CSS, DESeq, TMM, GMPR, and more

## Rarefaction

Rarefaction is a technique that equalizes the sequencing depth by randomly subsampling reads from each sample.

The `mStat_rarefy_data()` function rarefies the feature table to an even sequencing depth.

```r
mStat_rarefy_data(
  data.obj = obj,
  depth = 10000
)
```

When you don't specify a depth, it automatically chooses the smallest total count across samples.

**The function follows these steps:**

* Validates if the data object contains a feature table.
* Subsamples the feature table to achieve an even depth.
* Removes rows that contain only zeros.
* Updates the data object and any associated annotations.

Through rarefaction, technical variations between samples are minimized, promoting a more equitable comparison.

Sure! Here's a more detailed version of the scaling approaches section, integrating the specifics of the `mStat_normalize_data()` function:

## Scaling Approaches in Microbiome Analysis

When working with microbiome data, scaling is a pivotal step in ensuring that the data remains consistent across samples and is ready for downstream analysis. The `mStat_normalize_data()` function in MicrobiomeStat offers a suite of scaling techniques tailored to handle the unique challenges and intricacies of microbiome datasets.

### Available Scaling Techniques:

* **Total Sum Scaling (TSS):** This method involves scaling the counts in each sample so that they sum to a consistent total.
* **Cumulative Sum Scaling (CSS):** This technique adjusts counts based on the cumulative sum, focusing on ensuring consistent summation across the dataset.
* **DESeq Normalization:** Borrowed from the DESeq2 package commonly used for RNA-seq data, this method scales counts based on geometric means.
* **Trimmed Mean M-values (TMM):** This approach calculates scaling factors based on a weighted trimmed mean of the log-expression ratios.
* **Geometric Mean of Pairwise Ratios (GMPR):** GMPR uses A robust normalization method for zero-inflated count data such as microbiome sequencing data.
* **Rarefy-TSS Combination:** This method combines rarefaction, a subsampling approach, with total sum scaling to optimize count representation.

To apply any of these methods, you can use:

```r
normalized_data <- mStat_normalize_data(
  data.obj = obj,
  method = "TSS" # or any other desired method
)
```

For methods involving rarefaction (e.g., "Rarefy-TSS"), a `seed` parameter (default `123`) ensures reproducibility. The rarefaction subsampling will produce the same result across runs without affecting the caller's random number state:

```r
normalized_data <- mStat_normalize_data(
  data.obj = obj,
  method = "Rarefy-TSS",
  seed = 123  # For reproducible rarefaction
)
```

### Function Workflow:

1. **Extract OTU Table:** The function begins by retrieving the OTU (Operational Taxonomic Unit) table from the provided data object.
2. **Determine Scaling Factor:** Depending on the chosen normalization method, an appropriate scaling factor is calculated. This factor will be applied to adjust the counts in the dataset.
3. **Data Scaling:** Counts in the OTU table are then scaled using the derived factor. Some methods, like "TSS" and "CSS," apply direct scaling. Others, like the "Rarefy-TSS" combination, employ a more intricate approach involving both rarefying and scaling.
4. **Re-aggregation (if necessary):** If a `feature.agg.list` exists within the data object, this list will be re-aggregated based on the newly normalized data to ensure consistency.
5. **Return Results:** The function concludes by returning both the normalized data object and the scaling factors that were applied. This ensures that users have a clear understanding of the transformations and can ensure reproducibility in their work.

### Key Considerations:

After constructing your `mStat` data object, it's essential to use `mStat_validate_data()` to validate its integrity. Only then should you proceed with normalization. Moreover, while `mStat_validate_data()` provides comprehensive checks, it isn't exhaustive. If it clears your data, it indicates the absence of obvious issues but doesn't guarantee flawless function operability across the board.

Remember, scaling is a fundamental step in microbiome data analysis, ensuring that your findings are robust, accurate, and reflective of the underlying biological realities.

### Note on Choosing a Method

The best normalization method largely depends on the specific nature and requirements of your study. Rarefaction, for instance, might discard valuable data in samples with higher sequencing depth. Meanwhile, scaling approaches adjust counts without discarding data. Still, the appropriateness of each method varies based on the dataset's characteristics and the research question.

It's crucial to normalize your data, whether through rarefaction or scaling. This ensures the comparability of samples, laying a strong foundation for downstream analyses such as beta-diversity assessments, clustering, and differential abundance testing.


# Data Filtering

Data filtering selectively removes certain features or samples from the dataset.MicrobiomeStat provides key functions to filter data objects based on criteria.

Microbiome data is rich and intricate, requiring specialized tools to aid in preprocessing and analysis. Filtering is one of the key steps in this process, allowing you to selectively focus on relevant samples and features.

## Overview of Data Filtering

Filtering, at its core, selectively removes features or samples from your dataset based on specific criteria. This refined focus can greatly improve the quality and interpretability of downstream analysis.

MicrobiomeStat has been designed to provide researchers with a set of flexible functions tailored to the unique challenges of microbiome data.

### Key Functions

* `mStat_remove_feature()`: This function allows you to remove specific features based on their IDs.
* `mStat_subset_data()`: Subset your data based on sample IDs or even conditions provided in the metadata.
* `mStat_subset_dist()`: If you're working with distance matrices, this function lets you subset them by sample ID.
* `mStat_filter()`: This versatile function aids in filtering taxa based on minimum prevalence and average abundance, ensuring the relevance of your data.

## Diving Deep into Each Function

### Removing Features with `mStat_remove_feature()`

```r
mStat_remove_feature(
  data.obj = obj,
  featureIDs = c("feat1", "feat2"),
  feature.level = "Family"
)
```

What's happening under the hood?

* It verifies the feature IDs.
* Separately handles the 'original' level.
* Subsets the feature and annotation tables.
* Recalculates abundance aggregation.

### Subset by Sample using `mStat_subset_data()`

The `mStat_subset_data()` function allows users to subset their microbiome data based on specific sample IDs or conditions present within the metadata. This operation is useful for focusing on particular samples of interest or when segregating data for analysis.

#### Example: Subsetting by Sample IDs

Load the necessary library and dataset:

```r
# Load the required libraries
library(MicrobiomeStat)

# Prepare data for the function
data(peerj32.obj)
```

Next, subset the data object using specific sample IDs:

```r
# Subset data object by sample IDs
subset.ids <- rownames(peerj32.obj$meta.dat)[1:10] # for demonstration purposes
subset_peerj32.obj <- mStat_subset_data(data.obj = peerj32.obj, samIDs = subset.ids)
```

This example considers only the first ten samples from the `peerj32.obj` dataset for subsetting.

#### Example: Subsetting by a Condition

Continue with the `peerj32.obj` dataset. You can also subset based on conditions present in the metadata:

```r
# Subset data object by condition
condition <- "time == '1'" # for demonstration purposes
subset_peerj32.obj2 <- mStat_subset_data(data.obj = peerj32.obj, condition = condition)
```

In this example, the data object is subsetted to retain only those samples that belong to the first-time point (`time == '1'`).

By following these real-world examples, users can efficiently subset their microbiome datasets using either sample IDs or specific conditions from the metadata.

### Working with Distance Matrices: `mStat_subset_dist()`

```r
mStat_subset_dist(
  dist.obj = dist,
  samIDs = c("s1", "s2", "s3")  
)
```

This function processes each matrix in the list, subsetting based on the provided sample IDs.

### Filtering Microbiome Data by Prevalence and Abundance: `mStat_filter()`

The `mStat_filter()` function serves as a cornerstone within the MicrobiomeStat package for filtering microbiome data based on prevalence and abundance thresholds. Given its integration into various other functions that accept `prev.filter` and `abund.filter` parameters, it plays a critical role in ensuring data quality and relevance. By consistently filtering data to retain only taxa that satisfy specified criteria, the package ensures that analyses are concentrated on the most pertinent and widespread taxa.

#### Usage:

```r
mStat_filter(
  x = data_matrix,
  prev.filter = 0.5,
  abund.filter = 5
)
```

#### Function's Operation:

1. **Data Reshaping:** The function reshapes the input matrix/data frame to a long format, making it more amenable for grouping and filtering operations.
2. **Grouping by Taxa:** Data is grouped by individual taxa. This allows for the computation of both average abundance and prevalence for each taxon.
3. **Calculating Metrics:** Within each group (i.e., for each taxon), the function calculates:
   * `avg_abundance`: The average abundance across all samples.
   * `prevalence`: The proportion of samples where the taxon is present (non-zero).
4. **Filtering:** The function then applies the user-specified thresholds to filter the taxa:
   * Taxa that have a prevalence below `prev.filter` are removed.
   * Taxa that have an average abundance below `abund.filter` are removed.

#### Practical Example:

To illustrate the functionality, let's consider a mock matrix:

```r
# Define a mock matrix
data_matrix <- matrix(c(0, 3, 4, 0, 2, 7, 8, 9, 10), ncol=3)
colnames(data_matrix) <- c("sample1", "sample2", "sample3")
rownames(data_matrix) <- c("taxa1", "taxa2", "taxa3")

# Use the mStat_filter function
filtered_data <- mStat_filter(data_matrix, 0.5, 5)

# Display the filtered data
print(filtered_data)
```

Similarly, you can use the `mStat_filter()` function on real microbiome datasets, like `peerj32.obj`, to streamline your data based on prevalence and abundance before diving into deeper analyses.

## Conclusion

Data filtering is an essential step in microbiome analysis. With MicrobiomeStat, researchers have a comprehensive set of tools to refine their data, ensuring that downstream analysis is both meaningful and interpretable.


# Data Validation

High-quality analysis requires valid, well-formatted data. MicrobiomeStat provides data validation to check format compliance and consistency.

## Function Overview

Working with microbiome data often presents challenges related to consistency, data structure, and correct formatting. After constructing the `mStat` data object, it's pivotal to ensure its structure and content align with the expected standards. To facilitate this crucial validation step, MicrobiomeStat offers the `mStat_validate_data()` function. This tool provides automated checks and rectifications, safeguarding the integrity and validity of your microbiome datasets. By integrating this validation early in your analysis pipeline, you lay a robust foundation for subsequent analytical steps, minimizing potential discrepancies and errors down the line.

```r
data(peerj32.obj)

mStat_validate_data(
  data.obj = peerj32.obj
)
```

The function meticulously evaluates each part of your data object, specifically the `feature.tab`, `meta.dat`, and `feature.ann` components. It ensures these components adhere to a set of predefined rules, safeguarding against common formatting and alignment issues.

{% hint style="info" %}
**Note:** The `mStat_validate_data()` function, while comprehensive, is not exhaustive in its current form. There are scenarios that might not be captured during the validation process. As such, even if the data passes the `mStat_validate_data()` checks, it doesn't guarantee that all functions will operate without issues. It simply indicates that the data does not have any apparent inconsistencies detected by the current validation rules. Users are encouraged to always be vigilant and explore their data further to ensure optimal compatibility across all functions in MicrobiomeStat.
{% endhint %}

## Key Validation Steps:

1. **List Verification:** The initial step is to confirm that `data.obj` is a list, which is essential as microbiome data objects consist of various elements and data structures.
2. **Metadata Structure Verification:** Ensuring that `meta.dat` is a dataframe is crucial for its structured storage and ease of querying. If it isn't already a dataframe, the function converts it.
3. **Row Name Matching:** `feature.tab` and `feature.ann` should have identical row names. The function rectifies any inconsistencies by ensuring the row names of both components match.
4. **Column-Row Alignment:** An essential validation step is to ensure that the column names in `feature.tab` match the row names of `meta.dat`. This ensures alignment between feature abundances and their corresponding metadata.
5. **Matrix Verification:** The function confirms that both `feature.tab` and `feature.ann` are matrices. This validation ensures the data structures are optimally formatted for subsequent analysis within MicrobiomeStat.
6. **Custom Checks:** As datasets and requirements evolve, users can expect the integration of more rules to accommodate new data structures and elements.

### Crucial Points to Remember:

* While `mStat_validate_data()` is adept at adjusting certain inconsistencies, it's crucial for users to ensure data components are structured as base R data.frame and matrix structures. Package-specific formats, such as phyloseq's formal class, might require additional preprocessing.
* A successful validation is an excellent first step, but it doesn't guarantee an absolute absence of data issues. Regular data exploration and supplementary validations are encouraged to ensure comprehensive data accuracy.

## Benefits of Using `mStat_validate_data()`:

* **Analytical Compatibility:** By conforming data to expected structures, users ensure their datasets are primed for analyses using MicrobiomeStat's suite of functions.
* **Proactive Error Handling:** The function anticipates and rectifies potential format issues, preventing errors in later stages of analysis.
* **Data Quality Assurance:** Regular validations ensure consistent data integrity, especially valuable when incorporating new data or making extensive modifications.

In summary, effective microbiome analysis starts with validated and well-structured data. The `mStat_validate_data()` function plays a pivotal role in this process, offering users a streamlined mechanism to validate and adjust their datasets. As the adage goes, "Garbage in, garbage out." With this function, MicrobiomeStat aims to ensure that only quality data drives your analyses.


# Data Combination

In this section, we will cover the key function in MicrobiomeStat for combining multiple microbiome datasets into one object for integrated analysis.

## Data Combination

Combining multiple microbiome datasets is a crucial step in many research projects. The `mStat_combine_data()` function in MicrobiomeStat provides a straightforward way to merge two datasets into one object for integrated analysis.

### Overview

`mStat_combine_data()` is designed specifically for combining two MicrobiomeStat data objects that are in the raw format.

**Each data object should contain:**

* `feature.tab`: OTU/ASV table
* `meta.dat`: Sample metadata
* `feature.ann`: Taxonomic annotations

**The function will:**

* Row-bind the two `feature.tab` matrices
* Row-bind the two `feature.ann` matrices
* Row-bind the two `meta.dat` data frames

The output is a single merged data object ready for integrated analysis.

### Usage

```r
mStat_combine_data(
  data.obj1 = obj1, 
  data.obj2 = obj2
)
```

* `data.obj1`: The first data object to combine
* `data.obj2`: The second data object to combine

### Details

Here is how `mStat_combine_data()` works under the hood:

First it checks that both input objects are in the raw MicrobiomeStat format.

It then identifies common features and samples between the two objects.

* For common features, it checks that the data values are consistent between the two objects.
* If no common features or samples are found, it will print a warning message.

Next, it performs:

* A full join of the two `feature.tab` matrices by feature IDs
* Replaces any NA values with 0
* Gathers into a long format
* Spreads back to wide format
* Sets feature IDs as row names

This yields the combined `feature.tab` matrix.

It performs similar operations to combine `feature.ann` and `meta.dat`.

Finally, it returns the merged data object containing all three components.

### Applications

Key applications of this function include:

* Merge case and control groups for differential abundance analysis
* Combine multiple cohorts for meta-analysis
* Compile temporal datasets for longitudinal analysis
* Create one large dataset from multiple studies of a population

Proper dataset integration is crucial for maximizing the potential of your microbiome research. `mStat_combine_data()` lets you seamlessly merge compatible data objects, enabling more powerful integrated analysis.


# Metadata Management

Metadata provides crucial sample information for microbiome analysis. Effective metadata management enables robust comparative analysis.

## Metadata Management

Metadata provides key sample information for integrated microbiome analysis. MicrobiomeStat offers functions to update and synchronize metadata.

### Update Metadata

The `mStat_update_meta_data()` function updates metadata from a file or dataframe:

```r
mStat_update_meta_data(
  data.obj = obj,
  map.file = "new_meta.csv",
  meta.sep = "\t"  # Use "," for CSV, "\t" for TSV (default)
)
```

**Parameters:**

* `data.obj`: The MicrobiomeStat data object to update.
* `map.file`: Path to the metadata file, or a data.frame.
* `meta.sep`: Column separator for the metadata file. Default is `"\t"` (tab-separated). Use `","` for CSV files.
* `quote`: Quote character used in the file. Default is `"\""`.
* `comment`: Comment character. Default is `""` (none).

It can handle CSVs, TSVs, etc.

**Steps include**:

* Load metadata file or dataframe
* Replace existing `meta.dat`
* Subset feature table by intersecting samples
* Return updated data object

This allows incorporating new metadata to enable more powerful integrated analyses.

### Update Sample Names

The `mStat_update_sample_name()` function updates sample names across data components:

```r
mStat_update_sample_name(
  data.obj = obj,
  new.name = c("s1", "s2", "s3")
)
```

It synchronizes sample names in `meta.dat`, `feature.tab`, and `feature.agg.list`.

**Key steps**:

* Check new names are valid
* Update `meta.dat` rownames
* Update `feature.agg.list` colnames
* Update `feature.tab` colnames

This maintains data consistency when updating sample identifiers.

Proper metadata management ensures high-quality integrated analyses. MicrobiomeStat empowers seamless metadata updates to enable robust microbiome discoveries.


# Color Palette

## Custom Color Palette Retrieval

### mStat\_get\_palette Function

Choosing the right color palette is essential for creating visually appealing and informative data visualizations. The `mStat_get_palette()` function in MicrobiomeStat allows users to easily access and utilize a variety of color palettes, especially those inspired by and sourced from the scientific publication realm, through the `ggsci` package.

#### Overview

`mStat_get_palette()` is tailored for users who need predefined or custom color palettes for their data visualizations in R. It offers an extensive selection from the `ggsci` package, known for its scientific journal-inspired palettes, as well as the flexibility to specify custom color sets.

**Functionality:**

* Access predefined palettes like 'npg', 'aaas', 'nejm', 'lancet', 'jama', 'jco', and 'ucscgb' from the `ggsci` package.
* Provide a vector of custom color codes.
* Return a default palette in case of `NULL` input or unrecognized palette names.

#### Usage

```r
# Default palette
mStat_get_palette()

# Predefined `ggsci` palette: 'nejm'
mStat_get_palette("nejm")

# Custom color vector
mStat_get_palette(c("#123456", "#654321"))
```

#### Parameters

* `palette`: A character string for predefined palettes or a vector of color codes. If `NULL` or unrecognized, a default palette is used.

#### Details

Here's a glimpse into the functioning of `mStat_get_palette()`:

* It first checks if the `palette` parameter is `NULL`, a character string, or a vector.
* For a character string, it verifies if the name matches one of the predefined palettes in the `ggsci` database.
* If a match is found, the corresponding palette is returned.
* For a vector input, the vector itself is returned as the palette.
* In case of `NULL` or an unrecognized input, a default set of colors is provided.

#### Applications

This function is highly beneficial for:

* Enhancing the visual appeal of data plots in scientific publications.
* Customizing color schemes to match specific publication or presentation themes.
* Ensuring consistency and accuracy of color representation in multiple visualizations.

#### Visual Representation

* npg

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F0P1uwvzksQA6XZzBPQcP%2FScreenshot%202024-01-10%20at%2015.26.49.png?alt=media&amp;token=54aceda4-ab4c-4af2-934e-d33a14ad6509" alt=""><figcaption></figcaption></figure>

* lancet

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FxONmpQiHNtqzBa8qTRJz%2FScreenshot%202024-01-10%20at%2015.27.24.png?alt=media&amp;token=ebc71dd7-d18b-4ae4-b324-c1f3a3d23ff4" alt=""><figcaption></figcaption></figure>

* aaas

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F0bEYMWrUQUkVktUiIPIW%2FScreenshot%202024-01-10%20at%2015.27.06.png?alt=media&amp;token=9ba4550c-a14b-42a1-8e6a-95719e0ac9f1" alt=""><figcaption></figcaption></figure>

* nejm

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FuS6KmJWD6kmiyYCHRLBW%2FScreenshot%202024-01-10%20at%2015.28.02.png?alt=media&amp;token=a6848143-d17b-4246-bf28-19c7cefbc33b" alt=""><figcaption></figcaption></figure>

* jama

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FUXvNbh4WD9eF9BPalVbO%2FScreenshot%202024-01-10%20at%2015.28.41.png?alt=media&amp;token=6fb7de49-fb0f-4fbf-951e-090a4a753954" alt=""><figcaption></figcaption></figure>

* jco

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2FiYtJX0QmnLgE05xbAj1G%2FScreenshot%202024-01-10%20at%2015.30.36.png?alt=media&amp;token=7d602103-34e3-498b-b486-a6b350380772" alt=""><figcaption></figcaption></figure>

* ucscgb

<figure><img src="https://3375851868-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FhFAmY4z7d1R15Cv49vXQ%2Fuploads%2F3LmKGgaMjMgOFmWCJPRz%2FScreenshot%202024-01-10%20at%2015.31.27.png?alt=media&amp;token=bae369a0-1925-4988-9c03-e39208374450" alt=""><figcaption></figcaption></figure>


# General FAQs

This document is a collection of frequently asked questions (FAQs) and their solutions regarding the use of the MicrobiomeStat package in R. These FAQs are based on common issues and inquiries encountered by users in the past. For additional questions or if you encounter new issues, please feel free to visit the GitHub issues section of the MicrobiomeStat repository at <https://github.com/cafferychen777/MicrobiomeStat/issues>, where you can post your questions and receive support from the community and the package developers.

## I'm having an issue converting a phyloseq object to a MicrobiomeStat object using `mStat_convert_phyloseq_to_data_obj()`

Despite installing the latest version of MicrobiomeStat from GitHub, I'm still getting the error "could not find function 'mStat\_convert\_phyloseq\_to\_data\_obj'". Any suggestions?

**Solution:**

It appears there may have been an issue with the installation. After downloading and installing, pay attention to the version numbers. The current GitHub version is 1.5.1. If the installation of the GitHub version is unsuccessful, this issue may arise. Ensure you have installed all necessary dependencies before attempting to install from GitHub:

```r
packages_to_install <- c(
  "rlang", "tibble", "ggplot2", "matrixStats", "lmerTest", "foreach", 
  "modeest", "dplyr", "pheatmap", "tidyr", "ggh4x", "GUniFrac", "stringr",
  "rmarkdown", "knitr", "pander", "tinytex", "vegan", "scales", "ape",
  "ggrepel", "parallel", "ggprism", "aplot", "yaml", "biomformat", "Biostrings"
)
install.packages(packages_to_install)
```

Then install MicrobiomeStat: `devtools::install_github("cafferychen777/MicrobiomeStat")`

If issues persist, check for error messages during installation.

## Accessing Bray-Curtis distances from `generate_beta_ordination_pair`

I successfully plotted Bray-Curtis distance over time, but cannot access the calculated distances. Will this option be included in the future?

**Solution:**

The distances are accessible in the object generated by `generate_beta_ordination_pair`:

```r
plot <- generate_beta_ordination_pair(data.obj = your_data_object, ...)
bray_curtis_data <- plot$BC$data
```

We continuously improve MicrobiomeStat and appreciate suggestions for new features.

## Difference between `generate_beta_ordination_pair` and `generate_beta_change_spaghettiplot_long`

I can get BC distance data with the former but not the latter when `dist.name = c("BC")` is included. Are they equivalent?

**Solution:**

No, the two methods differ:

* `generate_beta_ordination_pair` uses PC1 and PC2 from multidimensional scaling (MDS)
* `generate_beta_change_spaghettiplot_long` calculates distances relative to original points

To get BC distances from `generate_beta_change_spaghettiplot_long`:

```r
a <- generate_beta_change_spaghettiplot_long(data.obj = your_data_object, dist.name = c("BC"), ...)
a$BC$layers[[1]]$data
```

## Error with `generate_beta_test_single()`

When running the tutorial, I got: `Error in colnames<-(*tmp*, value = colnames(lhs)) : attempt to set 'colnames' on an object with less than two dimensions`. Any idea what's happening?

**Solution:**

This could be due to conflicts/issues with your setup. Try:

1. Reinstall MicrobiomeStat package
2. Reinstall GUniFrac package
3. Ensure latest versions of all dependencies

If issues persist, provide more details on your system and error messages.

## Error with `generate_alpha_trend_test_long`

I get `Error in vec_data() : ! 'x' must be a vector, not a <sample_data> object` when running this function. Time variable is numeric, any idea what's wrong?

**Solution:**

The `feature.tab`, `meta.dat`, and `feature.ann` components may not be in expected R matrix/data.frame format. Convert them:

```r
ms_rare$feature.tab <- as.data.frame(ms_rare$feature.tab) %>% as.matrix()
ms_rare$meta.dat <- as.matrix(ms_rare$meta.dat) %>% as.data.frame() 
ms_rare$feature.ann <- ms_rare$feature.ann %>% as.data.frame() %>% as.matrix()
```

This should ensure the components are in the correct format. Reach out if issues persist.

## Error normalizing data with GMPR method

I get `Error in GMPR(otu_tab) : could not find function "GMPR"` when trying to normalize using the GMPR method. How to resolve?

**Solution:**

This error occurs when the required GUniFrac package is not loaded. Load it first:

```r
library(GUniFrac) 
```

Then you should be able to normalize using GMPR without the error.

## Missing timepoints in `generate_taxa_areaplot_long` visualization

I'm missing some timepoints and `subject.var` values when visualizing taxa changes across timepoints. My timepoints are 0, 1, 2, 3, 5, 6, 7, 8, 10, 12, 18, 24 (not all present in each sample). Suggestions?

**Solution:**

Try pairing `mStat_subset_data` with `generate_taxa_areaplot_long` in a loop to generate plots for each subject:

```r
data(subset_T2D.obj)
unique.subject.id <- subset_T2D.obj$meta.dat$subject_id

plot.list <- lapply(unique.subject.id, function(subject.id){
  sample.ids <- rownames(subset_T2D.obj$meta.dat[subset_T2D.obj$meta.dat$subject_id == subject.id, ])
  sub_subset_T2D.obj <- mStat_subset_data(subset_T2D.obj, sample.ids)
  
  generate_taxa_areaplot_long(sub_subset_T2D.obj,
                              subject.var = "subject_id",
                              time.var = "visit_number_num", 
                              feature.level = c("Genus"),
                              feature.dat.type = "count",
                              file.ann = subject.id)
})
```

Modify `group.var` as needed to group data by specific variables.

## Reason for `feature.mt.method` option in `generate_taxa_volcano_single()`

The `linda()` function already accounts for FDR, but `generate_taxa_volcano_single()` has a `feature.mt.method` option to use "none" or "fdr". Why add another FDR layer?

**Solution:**

FDR adjustment is crucial for high-dimensional data to control multiple testing issues, which `linda()` inherently does.

The `feature.mt.method` parameter allows users to choose between adjusted p-values (via FDR) or raw p-values for visualization in the volcano plot. Using raw p-values is for aesthetic reasons to improve plot clarity and interpretability.

While FDR adjustment is integral to MicrobiomeStat's statistical procedures, `feature.mt.method` offers flexibility in visualization without compromising statistical rigor.

## Issue with Corrupted Lazy-Load Database for MicrobiomeStat Package

**Problem:** When running functions from the MicrobiomeStat package, the following error is encountered:

```
Warning: restarting interrupted promise evaluation 
Warning: internal error -3 in R_decompress1
Error in FUN(X[[i]], ...) : The lazy-load database '/R/x86_64-pc-linux-gnu-library/4.2/MicrobiomeStat/R/MicrobiomeStat.rdb' is corrupted.
```

**Solution:**

1. Restart the R session: This often resolves issues related to the lazy-load database.
2. Reinstall the MicrobiomeStat package: If restarting the R session does not work, try reinstalling the package using:

```r
devtools::install_github("cafferychen777/MicrobiomeStat")
```

If these steps do not resolve the issue, please provide more detailed information for further troubleshooting.

## Windows Installation Error: "System command 'Rcmd.exe' failed"

**Problem:** Users encountering "System command 'Rcmd.exe' failed" error or issues with file path lengths during Windows installation.

**Solution:**

Several approaches can resolve this issue:

1. Using pak Package (Recommended):

```r
if (!requireNamespace("pak", quietly = TRUE)) {
  install.packages("pak")
}
pak::pkg_install("cafferychen777/MicrobiomeStat", dependencies = TRUE)
```

2. Using Shorter Temporary Directory Path:

```r
# Set temporary directory to a shorter path
dir.create("C:/Rtemp", showWarnings = FALSE)
Sys.setenv(TMPDIR = "C:/Rtemp")

# Install the package
devtools::install_github("cafferychen777/MicrobiomeStat", build_vignettes = FALSE)
```

3. Modify Windows Path Length Limit:
   * Open PowerShell as Administrator
   * Run: `Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem" -Name "LongPathsEnabled" -Value 1`
   * Restart computer

If issues persist, check:

```r
# Check temporary directory
Sys.getenv("TMPDIR")

# Check working directory
getwd()
```

Ensure latest Rtools is installed and try running R/RStudio as administrator.


