# ANCOM Tutorial

#### Huang Lin\(^1\)

#### \(^1\)NICHD, 6710B Rockledge Dr, Bethesda, MD 20892

#### October 18, 2022

# 1. Introduction

Analysis of Composition of Microbiomes (ANCOM) (Mandal et al. 2015) is a differential abundance (DA) analysis for microbial absolute abundances. It accounts for the compositionality of microbiome data by performing the additive log ratio (ALR) transformation. ANCOM employs a heuristic strategy to declare taxa that are significantly differentially abundant. For a given taxon, the output W statistic represents the number ALR transformed models where the taxon is differentially abundant with regard to the variable of interest. The larger the value of W, the more likely the taxon is differentially abundant. For more details, please refer to the ANCOM paper.

# 2. Installation

Download package.

    if (!requireNamespace("BiocManager", quietly = TRUE))
        install.packages("BiocManager")
    BiocManager::install("ANCOMBC")

Load the package.

    library(ANCOMBC)

# 3. Run ANCOM on a real cross-sectional dataset

## 3.1 Import example data

The HITChip Atlas dataset contains genus-level microbiota profiling with HITChip for 1006 western adults with no reported health complications, reported in (Lahti et al. 2014). The dataset is also available via the microbiome R package (Lahti et al. 2017) in phyloseq (McMurdie and Holmes 2013) format. In this tutorial, we consider the following covariates:

- Continuous covariates: “age”

- Categorical covariates: “region”, “bmi”

- The group variable of interest: “bmi”

  - Three groups: “lean”, “overweight”, “obese”

  - The reference group: “obese”

    data(atlas1006)

    # Subset to baseline
    tse = atlas1006[, atlas1006$time == 0]

    # Re-code the bmi group
    tse$bmi = recode(tse$bmi_group,
                     obese = "obese",
                     severeobese = "obese",
                     morbidobese = "obese")
    # Subset to lean, overweight, and obese subjects
    tse = tse[, tse$bmi %in% c("lean", "overweight", "obese")]

    # Note that by default, levels of a categorical variable in R are sorted
    # alphabetically. In this case, the reference level for `bmi` will be
    # `lean`. To manually change the reference level, for instance, setting `obese`
    # as the reference level, use:
    tse$bmi = factor(tse$bmi, levels = c("obese", "overweight", "lean"))
    # You can verify the change by checking:
    # levels(sample_data(tse)$bmi)

    # Create the region variable
    tse$region = recode(as.character(tse$nationality),
                        Scandinavia = "NE", UKIE = "NE", SouthEurope = "SE",
                        CentralEurope = "CE", EasternEurope = "EE",
                        .missing = "unknown")

    # Discard "EE" as it contains only 1 subject
    # Discard subjects with missing values of region
    tse = tse[, ! tse$region %in% c("EE", "unknown")]

    print(tse)

    class: TreeSummarizedExperiment
    dim: 130 873
    metadata(0):
    assays(1): counts
    rownames(130): Actinomycetaceae Aerococcus ... Xanthomonadaceae
      Yersinia et rel.
    rowData names(3): Phylum Family Genus
    colnames(873): Sample-1 Sample-2 ... Sample-1005 Sample-1006
    colData names(12): age sex ... bmi region
    reducedDimNames(0):
    mainExpName: NULL
    altExpNames(0):
    rowLinks: NULL
    rowTree: NULL
    colLinks: NULL
    colTree: NULL

## 3.2 Run ancom function

    set.seed(123)
    out = ancom(data = tse, assay_name = "counts",
                tax_level = "Family", phyloseq = NULL,
                p_adj_method = "holm", prv_cut = 0.10, lib_cut = 1000,
                main_var = "bmi", adj_formula = "age + region",
                rand_formula = NULL, lme_control = NULL, struc_zero = TRUE,
                neg_lb = TRUE, alpha = 0.05, n_cl = 2)

    res = out$res

    # Similarly, if the main variable of interest is continuous, such as age, the
    # ancom model can be specified as
    # out = ancom(data = tse, assay_name = "counts",
    #             tax_level = "Family", phyloseq = NULL,
    #             p_adj_method = "holm", prv_cut = 0.10, lib_cut = 1000,
    #             main_var = "age", adj_formula = "bmi + region",
    #             rand_formula = NULL, lme_control = NULL, struc_zero = FALSE,
    #             neg_lb = FALSE, alpha = 0.05, n_cl = 2)

    # ancom also supports importing data in phyloseq format
    # tse_alt = agglomerateByRank(tse, "Family")
    # pseq = makePhyloseqFromTreeSummarizedExperiment(tse_alt)
    # out = ancom(data = NULL, assay_name = NULL,
    #             tax_level = "Family", phyloseq = pseq,
    #             p_adj_method = "holm", prv_cut = 0.10, lib_cut = 1000,
    #             main_var = "bmi", adj_formula = "age + region",
    #             rand_formula = NULL, lme_control = NULL, struc_zero = TRUE,
    #             neg_lb = TRUE, alpha = 0.05, n_cl = 2)

## 3.3 Scatter plot for W statistics

    q_val = out$q_data
    beta_val = out$beta_data
    # Only consider the effect sizes with the corresponding q-value less than alpha
    beta_val = beta_val * (q_val < 0.05)
    # Choose the maximum of beta's as the effect size
    beta_pos = apply(abs(beta_val), 2, which.max)
    beta_max = vapply(seq_along(beta_pos), function(i)
        beta_val[beta_pos[i], i], FUN.VALUE = double(1))
    # Number of taxa except structural zeros
    n_taxa = ifelse(is.null(out$zero_ind),
                    nrow(feature_table),
                    sum(apply(out$zero_ind, 1, sum) == 0))
    # Cutoff values for declaring differentially abundant taxa
    cut_off = 0.7 * (n_taxa - 1)

    df_fig_w = res %>%
      dplyr::mutate(beta = beta_max,
                    direct = case_when(
                      detected_0.7 == TRUE & beta > 0 ~ "Positive",
                      detected_0.7 == TRUE & beta <= 0 ~ "Negative",
                      TRUE ~ "Not Significant"
                      )) %>%
      dplyr::arrange(W)
    df_fig_w$taxon_id = factor(df_fig_w$taxon_id, levels = df_fig_w$taxon_id)
    df_fig_w$W = replace(df_fig_w$W, is.infinite(df_fig_w$W), n_taxa - 1)
    df_fig_w$direct = factor(df_fig_w$direct,
                             levels = c("Negative", "Positive", "Not Significant"))

    p_w = df_fig_w %>%
      ggplot(aes(x = taxon_id, y = W, color = direct)) +
      geom_point(size = 2, alpha = 0.6) +
      labs(x = "Taxon", y = "W") +
      scale_color_discrete(name = NULL) +
      geom_hline(yintercept = cut_off, linetype = "dotted",
                 color = "blue", size = 1.5) +
      geom_text(aes(x = 2, y = cut_off + 0.5, label = "W[0.7]"),
                size = 5, vjust = -0.5, hjust = 0, color = "orange", parse = TRUE) +
      theme_bw() +
      theme(axis.text.x = element_blank(),
            axis.ticks.x = element_blank(),
            panel.grid.major = element_blank())
    p_w

# 4. Run ANCOM on a real longitudinal dataset

## 4.1 Import example data

A two-week diet swap study between western (USA) and traditional (rural Africa) diets (Lahti et al. 2014). The dataset is also available via the microbiome R package (Lahti et al. 2017) in phyloseq (McMurdie and Holmes 2013) format. In this tutorial, we consider the following fixed effects:

- Continuous covariates: “timepoint”

- Categorical covariates: “nationality”

- The group variable of interest: “group”

  - Three groups: “DI”, “ED”, “HE”

  - The reference group: “DI”

and the following random effects:

- A random intercept

- A random slope: “timepoint”

    data(dietswap)
    tse = dietswap
    print(tse)

    class: TreeSummarizedExperiment
    dim: 130 222
    metadata(0):
    assays(1): counts
    rownames(130): Actinomycetaceae Aerococcus ... Xanthomonadaceae
      Yersinia et rel.
    rowData names(3): Phylum Family Genus
    colnames(222): Sample-1 Sample-2 ... Sample-221 Sample-222
    colData names(8): subject sex ... timepoint.within.group bmi_group
    reducedDimNames(0):
    mainExpName: NULL
    altExpNames(0):
    rowLinks: NULL
    rowTree: NULL
    colLinks: NULL
    colTree: NULL

## 4.2 Run ancom function

    set.seed(123)
    out = ancom(data = tse, assay_name = "counts",
                tax_level = "Family", phyloseq = NULL,
                p_adj_method = "holm", prv_cut = 0.10, lib_cut = 1000,
                main_var = "group",
                adj_formula = "nationality + timepoint",
                rand_formula = "~ timepoint | subject",
                lme_control = list(maxIter = 100, msMaxIter = 100, opt = "optim"),
                struc_zero = TRUE, neg_lb = TRUE, alpha = 0.05, n_cl = 2)

    res = out$res

## 4.3 Visualization for W statistics

    q_val = out$q_data
    beta_val = out$beta_data
    # Only consider the effect sizes with the corresponding q-value less than alpha
    beta_val = beta_val * (q_val < 0.05)
    # Choose the maximum of beta's as the effect size
    beta_pos = apply(abs(beta_val), 2, which.max)
    beta_max = vapply(seq_along(beta_pos), function(i) beta_val[beta_pos[i], i],
                      FUN.VALUE = double(1))
    # Number of taxa except structural zeros
    n_taxa = ifelse(is.null(out$zero_ind),
                    nrow(feature_table),
                    sum(apply(out$zero_ind, 1, sum) == 0))
    # Cutoff values for declaring differentially abundant taxa
    cut_off = 0.7 * (n_taxa - 1)

    df_fig_w = res %>%
      dplyr::mutate(beta = beta_max,
                    direct = case_when(
                      detected_0.7 == TRUE & beta > 0 ~ "Positive",
                      detected_0.7 == TRUE & beta <= 0 ~ "Negative",
                      TRUE ~ "Not Significant"
                      )) %>%
      dplyr::arrange(W)
    df_fig_w$taxon_id = factor(df_fig_w$taxon_id, levels = df_fig_w$taxon_id)
    df_fig_w$W = replace(df_fig_w$W, is.infinite(df_fig_w$W), n_taxa - 1)
    df_fig_w$direct = factor(df_fig_w$direct,
                         levels = c("Negative", "Positive", "Not Significant"))

    p_w = df_fig_w %>%
      ggplot(aes(x = taxon_id, y = W, color = direct)) +
      geom_point(size = 2, alpha = 0.6) +
      labs(x = "Taxon", y = "W") +
      scale_color_discrete(name = NULL) +
      geom_hline(yintercept = cut_off, linetype = "dotted",
                 color = "blue", size = 1.5) +
      geom_text(aes(x = 2, y = cut_off + 0.5, label = "W[0.7]"),
                size = 5, vjust = -0.5, hjust = 0, color = "orange", parse = TRUE) +
      theme_bw() +
      theme(axis.text.x = element_blank(),
            axis.ticks.x = element_blank(),
            panel.grid.major = element_blank())
    p_w

# Session information

    sessionInfo()

    R version 4.2.1 (2022-06-23 ucrt)
    Platform: x86_64-w64-mingw32/x64 (64-bit)
    Running under: Windows Server x64 (build 20348)

    Matrix products: default

    locale:
    [1] LC_COLLATE=C
    [2] LC_CTYPE=English_United States.utf8
    [3] LC_MONETARY=English_United States.utf8
    [4] LC_NUMERIC=C
    [5] LC_TIME=English_United States.utf8

    attached base packages:
    [1] stats4    stats     graphics  grDevices utils     datasets  methods
    [8] base

    other attached packages:
     [1] mia_1.4.0                      MultiAssayExperiment_1.22.0
     [3] TreeSummarizedExperiment_2.4.0 Biostrings_2.64.1
     [5] XVector_0.36.0                 SingleCellExperiment_1.18.1
     [7] SummarizedExperiment_1.26.1    Biobase_2.56.0
     [9] GenomicRanges_1.48.0           GenomeInfoDb_1.32.4
    [11] IRanges_2.30.1                 S4Vectors_0.34.0
    [13] BiocGenerics_0.42.0            MatrixGenerics_1.8.1
    [15] matrixStats_0.62.0             forcats_0.5.2
    [17] stringr_1.4.1                  dplyr_1.0.10
    [19] purrr_0.3.5                    readr_2.1.3
    [21] tidyr_1.2.1                    tibble_3.1.8
    [23] ggplot2_3.3.6                  tidyverse_1.3.2
    [25] ANCOMBC_1.6.4

    loaded via a namespace (and not attached):
      [1] utf8_1.2.2                  tidyselect_1.2.0
      [3] lme4_1.1-30                 RSQLite_2.2.18
      [5] htmlwidgets_1.5.4           grid_4.2.1
      [7] BiocParallel_1.30.4         gmp_0.6-6
      [9] munsell_0.5.0               ScaledMatrix_1.4.1
     [11] codetools_0.2-18            interp_1.1-3
     [13] withr_2.5.0                 colorspace_2.0-3
     [15] energy_1.7-10               highr_0.9
     [17] knitr_1.40                  rstudioapi_0.14
     [19] DescTools_0.99.46           labeling_0.4.2
     [21] Rdpack_2.4                  emmeans_1.8.1-1
     [23] GenomeInfoDbData_1.2.8      farver_2.1.1
     [25] bit64_4.0.5                 coda_0.19-4
     [27] vctrs_0.4.2                 treeio_1.20.2
     [29] generics_0.1.3              TH.data_1.1-1
     [31] xfun_0.33                   R6_2.5.1
     [33] doParallel_1.0.17           ggbeeswarm_0.6.0
     [35] rsvd_1.0.5                  bitops_1.0-7
     [37] cachem_1.0.6                DelayedArray_0.22.0
     [39] assertthat_0.2.1            scales_1.2.1
     [41] googlesheets4_1.0.1         multcomp_1.4-20
     [43] nnet_7.3-18                 beeswarm_0.4.0
     [45] rootSolve_1.8.2.3           gtable_0.3.1
     [47] beachmat_2.12.0             lmom_2.9
     [49] sandwich_3.0-2              rlang_1.0.6
     [51] splines_4.2.1               lazyeval_0.2.2
     [53] gargle_1.2.1                broom_1.0.1
     [55] checkmate_2.1.0             modelr_0.1.9
     [57] yaml_2.3.6                  reshape2_1.4.4
     [59] backports_1.4.1             Hmisc_4.7-1
     [61] tools_4.2.1                 ellipsis_0.3.2
     [63] decontam_1.16.0             jquerylib_0.1.4
     [65] RColorBrewer_1.1-3          proxy_0.4-27
     [67] Rcpp_1.0.9                  plyr_1.8.7
     [69] base64enc_0.1-3             sparseMatrixStats_1.8.0
     [71] zlibbioc_1.42.0             RCurl_1.98-1.9
     [73] rpart_4.1.16                deldir_1.0-6
     [75] viridis_0.6.2               zoo_1.8-11
     [77] haven_2.5.1                 ggrepel_0.9.1
     [79] cluster_2.1.4               fs_1.5.2
     [81] DECIPHER_2.24.0             magrittr_2.0.3
     [83] data.table_1.14.4           lmerTest_3.1-3
     [85] reprex_2.0.2                googledrive_2.0.0
     [87] mvtnorm_1.1-3               gsl_2.1-7.1
     [89] hms_1.1.2                   evaluate_0.17
     [91] xtable_1.8-4                jpeg_0.1-9
     [93] readxl_1.4.1                gridExtra_2.3
     [95] compiler_4.2.1              scater_1.24.0
     [97] crayon_1.5.2                minqa_1.2.4
     [99] htmltools_0.5.3             tzdb_0.3.0
    [101] mgcv_1.8-40                 Formula_1.2-4
    [103] expm_0.999-6                Exact_3.2
    [105] lubridate_1.8.0             DBI_1.1.3
    [107] dbplyr_2.2.1                MASS_7.3-58.1
    [109] boot_1.3-28                 Matrix_1.5-1
    [111] permute_0.9-7               cli_3.4.1
    [113] rbibutils_2.2.9             parallel_4.2.1
    [115] pkgconfig_2.0.3             numDeriv_2016.8-1.1
    [117] foreign_0.8-83              scuttle_1.6.3
    [119] xml2_1.3.3                  foreach_1.5.2
    [121] vipor_0.4.5                 bslib_0.4.0
    [123] DirichletMultinomial_1.38.0 rngtools_1.5.2
    [125] estimability_1.4.1          rvest_1.0.3
    [127] CVXR_1.0-10                 doRNG_1.8.2
    [129] yulab.utils_0.0.5           digest_0.6.30
    [131] vegan_2.6-4                 rmarkdown_2.17
    [133] cellranger_1.1.0            tidytree_0.4.1
    [135] htmlTable_2.4.1             gld_2.6.5
    [137] DelayedMatrixStats_1.18.2   nloptr_2.0.3
    [139] lifecycle_1.0.3             nlme_3.1-160
    [141] jsonlite_1.8.2              BiocNeighbors_1.14.0
    [143] viridisLite_0.4.1           fansi_1.0.3
    [145] pillar_1.8.1                lattice_0.20-45
    [147] fastmap_1.1.0               httr_1.4.4
    [149] survival_3.4-0              glue_1.6.2
    [151] png_0.1-7                   iterators_1.0.14
    [153] bit_4.0.4                   class_7.3-20
    [155] stringi_1.7.8               sass_0.4.2
    [157] blob_1.2.3                  BiocSingular_1.12.0
    [159] latticeExtra_0.6-30         memoise_2.0.1
    [161] Rmpfr_0.8-9                 irlba_2.3.5.1
    [163] e1071_1.7-11                ape_5.6-2

# References

Lahti, Leo, Jarkko Salojärvi, Anne Salonen, Marten Scheffer, and Willem M De Vos. 2014. “Tipping Elements in the Human Intestinal Ecosystem.” Nature Communications 5 (1): 1–10.

Lahti, Leo, Sudarshan Shetty, T Blake, J Salojarvi, and others. 2017. “Tools for Microbiome Analysis in R.” Version 1: 10013.

Mandal, Siddhartha, Will Van Treuren, Richard A White, Merete Eggesbø, Rob Knight, and Shyamal D Peddada. 2015. “Analysis of Composition of Microbiomes: A Novel Method for Studying Microbial Composition.” Microbial Ecology in Health and Disease 26 (1): 27663.

McMurdie, Paul J, and Susan Holmes. 2013. “Phyloseq: An R Package for Reproducible Interactive Analysis and Graphics of Microbiome Census Data.” PloS One 8 (4): e61217.