ANCOM-BC Tutorial

Huang Lin\(^1\)

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

November 04, 2022

1. Introduction

Analysis of Compositions of Microbiomes with Bias Correction (ANCOM-BC) (Lin and Peddada 2020) is a methodology of differential abundance (DA) analysis for microbial absolute abundances. ANCOM-BC estimates the unknown sampling fractions, corrects the bias induced by their differences through a log linear regression model including the estimated sampling fraction as an offset terms, and identifies taxa that are differentially abundant according to the variable of interest. For more details, please refer to the ANCOM-BC paper.

2. Installation

Download package.

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

Load the package.

library(ANCOMBC)

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

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

4 ANCOM-BC Implementation

4.1 Run ancombc function

out = ancombc(data = tse, assay_name = "counts", 
              tax_level = "Family", phyloseq = NULL, 
              formula = "age + region + bmi", 
              p_adj_method = "holm", prv_cut = 0.10, lib_cut = 1000, 
              group = "bmi", struc_zero = TRUE, neg_lb = TRUE, tol = 1e-5, 
              max_iter = 100, conserve = TRUE, alpha = 0.05, global = TRUE,
              n_cl = 1, verbose = TRUE)

res = out$res
res_global = out$res_global

# ancombc also supports importing data in phyloseq format
# tse_alt = agglomerateByRank(tse, "Family")
# pseq = makePhyloseqFromTreeSummarizedExperiment(tse_alt)
# out = ancombc(data = NULL, assay_name = NULL,
#               tax_level = "Family", phyloseq = pseq,
#               formula = "age + region + bmi",
#               p_adj_method = "holm", prv_cut = 0.10, lib_cut = 1000,
#               group = "region", struc_zero = TRUE, neg_lb = TRUE, tol = 1e-5,
#               max_iter = 100, conserve = TRUE, alpha = 0.05, global = TRUE,
#               n_cl = 1, verbose = TRUE)

4.2 ANCOMBC primary result

Result from the ANCOM-BC log-linear model to determine taxa that are differentially abundant according to the covariate of interest. It contains: 1) log fold changes; 2) standard errors; 3) test statistics; 4) p-values; 5) adjusted p-values; 6) indicators whether the taxon is differentially abundant (TRUE) or not (FALSE).

LFC

tab_lfc = res$lfc
col_name = c("Taxon", "Intercept", "Age", "NE - CE", "SE - CE", 
             "US - CE", "Overweight - Obese", "Lean - Obese")
colnames(tab_lfc) = col_name
tab_lfc %>% 
  datatable(caption = "Log Fold Changes from the Primary Result") %>%
  formatRound(col_name[-1], digits = 2)

SE

tab_se = res$se
colnames(tab_se) = col_name
tab_se %>% 
  datatable(caption = "SEs from the Primary Result") %>%
  formatRound(col_name[-1], digits = 2)

Test statistic

tab_w = res$W
colnames(tab_w) = col_name
tab_w %>% 
  datatable(caption = "Test Statistics from the Primary Result") %>%
  formatRound(col_name[-1], digits = 2)

P-values

tab_p = res$p_val
colnames(tab_p) = col_name
tab_p %>% 
  datatable(caption = "P-values from the Primary Result") %>%
  formatRound(col_name[-1], digits = 2)

Adjusted p-values

tab_q = res$q
colnames(tab_q) = col_name
tab_q %>% 
  datatable(caption = "Adjusted p-values from the Primary Result") %>%
  formatRound(col_name[-1], digits = 2)

Differentially abundant taxa

tab_diff = res$diff_abn
colnames(tab_diff) = col_name
tab_diff %>% 
  datatable(caption = "Differentially Abundant Taxa from the Primary Result")

Bias-corrected abundances

Step 1: obtain estimated sample-specific sampling fractions (in log scale).

Step 2: correct the log observed abundances by subtracting the estimated sampling fraction from log observed abundances of each sample.

Note that we are only able to estimate sampling fractions up to an additive constant. Thus, only the difference between bias-corrected abundances are meaningful.

samp_frac = out$samp_frac
# Replace NA with 0
samp_frac[is.na(samp_frac)] = 0 
# Add pesudo-count (1) to avoid taking the log of 0
log_obs_abn = log(out$feature_table + 1)
# Adjust the log observed abundances
log_corr_abn = t(t(log_obs_abn) - samp_frac)
# Show the first 6 samples
round(log_corr_abn[, 1:6], 2) %>% 
  datatable(caption = "Bias-corrected log observed abundances")

Visualization for age

df_lfc = data.frame(res$lfc[, -1] * res$diff_abn[, -1], check.names = FALSE) %>%
    mutate(taxon_id = res$diff_abn$taxon) %>%
    dplyr::select(taxon_id, everything())
df_se = data.frame(res$se[, -1] * res$diff_abn[, -1], check.names = FALSE) %>% 
  mutate(taxon_id = res$diff_abn$taxon) %>%
    dplyr::select(taxon_id, everything())
colnames(df_se)[-1] = paste0(colnames(df_se)[-1], "SE")

df_fig_age = df_lfc %>% 
  dplyr::left_join(df_se, by = "taxon_id") %>%
  dplyr::transmute(taxon_id, age, ageSE) %>%
  dplyr::filter(age != 0) %>% 
  dplyr::arrange(desc(age)) %>%
  dplyr::mutate(direct = ifelse(age > 0, "Positive LFC", "Negative LFC"))
df_fig_age$taxon_id = factor(df_fig_age$taxon_id, levels = df_fig_age$taxon_id)
df_fig_age$direct = factor(df_fig_age$direct, 
                        levels = c("Positive LFC", "Negative LFC"))
  
p_age = ggplot(data = df_fig_age, 
           aes(x = taxon_id, y = age, fill = direct, color = direct)) + 
  geom_bar(stat = "identity", width = 0.7, 
           position = position_dodge(width = 0.4)) +
  geom_errorbar(aes(ymin = age - ageSE, ymax = age + ageSE), width = 0.2,
                position = position_dodge(0.05), color = "black") + 
  labs(x = NULL, y = "Log fold change", 
       title = "Log fold changes as one unit increase of age") + 
  scale_fill_discrete(name = NULL) +
  scale_color_discrete(name = NULL) +
  theme_bw() + 
  theme(plot.title = element_text(hjust = 0.5),
        panel.grid.minor.y = element_blank(),
        axis.text.x = element_text(angle = 60, hjust = 1))
p_age

Visualization for BMI

df_fig_bmi = df_lfc %>% 
  filter(bmioverweight != 0 | bmilean != 0) %>%
  transmute(taxon_id, 
            `Overweight vs. Obese` = round(bmioverweight, 2),
            `Lean vs. Obese` = round(bmilean, 2)) %>%
  pivot_longer(cols = `Overweight vs. Obese`:`Lean vs. Obese`, 
               names_to = "group", values_to = "value") %>%
  arrange(taxon_id)
lo = floor(min(df_fig_bmi$value))
up = ceiling(max(df_fig_bmi$value))
mid = (lo + up)/2
p_bmi = df_fig_bmi %>%
  ggplot(aes(x = group, y = taxon_id, fill = value)) + 
  geom_tile(color = "black") +
  scale_fill_gradient2(low = "blue", high = "red", mid = "white", 
                       na.value = "white", midpoint = mid, limit = c(lo, up),
                       name = NULL) +
  geom_text(aes(group, taxon_id, label = value), color = "black", size = 4) +
  labs(x = NULL, y = NULL, title = "Log fold changes as compared to obese subjects") +
  theme_minimal() +
  theme(plot.title = element_text(hjust = 0.5))
p_bmi

4.3 ANCOMBC global test result

Result from the ANCOM-BC global test to determine taxa that are differentially abundant between at least two groups across three or more different groups. In this example, we want to identify taxa that are differentially abundant between at least two regions across CE, NE, SE, and US. The result contains: 1) test statistics; 2) p-values; 3) adjusted p-values; 4) indicators whether the taxon is differentially abundant (TRUE) or not (FALSE).

Test statistics

tab_w = res_global[, c("taxon", "W")]
tab_w %>% datatable(caption = "Test Statistics 
                    from the Global Test Result") %>%
      formatRound(c("W"), digits = 2)

P-values

tab_p = res_global[, c("taxon", "p_val")]
tab_p %>% datatable(caption = "P-values 
                    from the Global Test Result") %>%
      formatRound(c("p_val"), digits = 2)

Adjusted p-values

tab_q = res_global[, c("taxon", "q_val")]
tab_q %>% datatable(caption = "Adjusted p-values 
                    from the Global Test Result") %>%
      formatRound(c("q_val"), digits = 2)

Differentially abundant taxa

tab_diff = res_global[, c("taxon", "diff_abn")]
tab_diff %>% datatable(caption = "Differentially Abundant Taxa 
                       from the Global Test Result")

Visualization

sig_taxa = res_global %>%
  dplyr::filter(diff_abn == TRUE) %>%
  .$taxon

df_bmi = tab_lfc %>%
    dplyr::select(Taxon, `Overweight - Obese`, `Lean - Obese`) %>%
    filter(Taxon %in% sig_taxa)

df_heat = df_bmi %>%
    pivot_longer(cols = -one_of("Taxon"),
                 names_to = "region", values_to = "value") %>%
    mutate(value = round(value, 2))
df_heat$Taxon = factor(df_heat$Taxon, levels = sort(sig_taxa))

lo = floor(min(df_heat$value))
up = ceiling(max(df_heat$value))
mid = (lo + up)/2
p_heat = df_heat %>%
  ggplot(aes(x = region, y = Taxon, fill = value)) + 
  geom_tile(color = "black") +
  scale_fill_gradient2(low = "blue", high = "red", mid = "white", 
                       na.value = "white", midpoint = mid, limit = c(lo, up),
                       name = NULL) +
  geom_text(aes(region, Taxon, label = value), color = "black", size = 4) +
  labs(x = NULL, y = NULL, 
       title = "Log fold changes for globally significant taxa") +
  theme_minimal() +
  theme(plot.title = element_text(hjust = 0.5))
p_heat

Session information

sessionInfo()
R Under development (unstable) (2022-10-25 r83175)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 22.04.1 LTS

Matrix products: default
BLAS:   /home/biocbuild/bbs-3.17-bioc/R/lib/libRblas.so
LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.10.0

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_GB              LC_COLLATE=C              
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

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

other attached packages:
 [1] DT_0.26         forcats_0.5.2   stringr_1.4.1   dplyr_1.0.10   
 [5] purrr_0.3.5     readr_2.1.3     tidyr_1.2.1     tibble_3.1.8   
 [9] ggplot2_3.4.0   tidyverse_1.3.2 ANCOMBC_2.1.1  

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

Lin, Huang, and Shyamal Das Peddada. 2020. “Analysis of Compositions of Microbiomes with Bias Correction.” Nature Communications 11 (1): 1–11.

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.