--- title: "Statistical models and contrasts" author: "dar authors" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Statistical models and contrasts} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include=FALSE} knitr::opts_chunk$set(collapse = TRUE, comment = "#>") library(dar) set.seed(130) ``` `add_model()` defines one statistical design shared by every compatible differential-abundance step. Its `targets` and `tax_level` arguments are the single source of truth for the analysis configuration; other fixed terms provide covariate adjustment. Method-specific thresholds, normalization and rarefaction settings remain active. Preprocessing can run without a model, but differential-abundance execution requires `add_model()` before `prep()`. Steps can be configured before or after adding the model. Inspect the current specification with `get_model(rec)`. ## Small example data These simulated counts illustrate model configuration, not biological findings, statistical performance or power. There are 12 subjects, each measured at three visits. The cross-sectional example uses only their baseline samples. Messages and warnings remain visible; this small example does not establish estimation quality or validate a method's assumptions. ```{r example-data} metadata <- expand.grid( visit = 0:2, subject_index = 1:6, condition = c("control", "treated"), KEEP.OUT.ATTRS = FALSE, stringsAsFactors = FALSE ) metadata$subject <- paste(metadata$condition, metadata$subject_index, sep = "_") metadata$batch <- factor(ifelse(metadata$subject_index %% 2 == 0, "A", "B")) metadata$age <- rep(c(25, 42, 31, 56, 38, 49), each = 3, times = 2) rownames(metadata) <- paste(metadata$subject, metadata$visit, sep = "_") means <- outer(seq(40, 150, length.out = 12), rep(1, nrow(metadata))) means[1, ] <- means[1, ] * ifelse(metadata$condition == "treated", 2, 1) means[2, ] <- means[2, ] * exp( 0.3 * metadata$visit * (metadata$condition == "treated") ) counts <- matrix( rnbinom(length(means), mu = as.vector(means), size = 20), nrow = nrow(means), dimnames = list(paste0("taxon_", seq_len(nrow(means))), rownames(metadata)) ) taxonomy <- cbind( Genus = paste0("Genus_", seq_len(nrow(counts))), Species = paste0("Species_", seq_len(nrow(counts))) ) rownames(taxonomy) <- rownames(counts) longitudinal_phy <- phyloseq::phyloseq( phyloseq::otu_table(counts, taxa_are_rows = TRUE), phyloseq::tax_table(taxonomy), phyloseq::sample_data(metadata) ) phy <- phyloseq::prune_samples(metadata$visit == 0, longitudinal_phy) ``` ## Cross-sectional adjustment ```{r cross-sectional} rec <- recipe(phy) |> add_model( ~ condition + batch + age, targets = "condition", tax_level = "Species", reference = c(condition = "control"), na_action = "error" ) |> step_deseq() get_model(rec) cross_sectional_fit <- prep(rec, parallel = FALSE) ``` The reference is the denominator, so a positive effect for `condition[treated-control]` means higher abundance in `treated`. With `na_action = "drop"`, `prep()` removes one common complete-case cohort before any engine runs and records the sample identifiers in the execution manifest. Use `na_action = "error"` when missing model variables should stop the analysis instead of changing the cohort. ## Longitudinal adjustment Numeric time values are converted internally to a factor whose levels are sorted by numeric value. The original sample metadata are not modified. ```{r longitudinal} longitudinal <- recipe(longitudinal_phy) |> add_model( ~ condition * visit + batch + (1 | subject), targets = "condition", tax_level = "Species", time = "visit", reference = c(condition = "control", visit = "0"), contrasts = "all", na_action = "drop" ) |> step_linda() fit <- prep(longitudinal, parallel = FALSE) tidy_results(fit) |> dplyr::distinct(contrast_id, comparison, contrast_type) ``` For `condition * visit`, the simple plan contains condition comparisons within every visit and all pairwise visit comparisons within every condition. Later time values are numerators. `contrasts = "all"` additionally requests difference-in-differences. More than 12 time points requires an explicit larger `max_time_levels`, preventing accidental contrast explosions. `(1 | subject)` specifies a subject-level random intercept for repeated measurements. Declaring `time` does not itself add a random effect or establish that observations are independent. Include the subject structure required by the study design and choose a compatible method. ## Engine capabilities | Engine | Fixed adjustment | Time interaction | Random effects | |:--|:--:|:--:|:--:| | DESeq2 | yes | yes | no | | ALDEx2 | yes | yes | no | | ALDEx3 | yes | yes | yes (exact lme4) | | ANCOM-BC2 | yes | yes | yes | | corncob | yes | yes | no | | LinDA | yes | yes | yes | | MaAsLin3 | yes | yes | yes | | radEmu | yes | yes | no; explicit GEE clustering | | Wilcoxon | no | no | no | | LEfSe | no | no | no | Fixed adjustment includes an additive time term, even when that column is declared with `time`. Wilcoxon and LEfSe support one categorical target without adjustment; they cannot execute `~ condition + time` with `targets = "condition"`. Incompatible steps are warned about when the chain is built and rechecked after preprocessing. `prep()` records them rather than treating them as failed fits. If no method is compatible, preparation stops. Real engine failures and missing planned contrasts remain errors. Use `contrast_id`, `comparison` and `contrast_type` to identify the hypothesis represented by each result. See [Getting started with dar](dar.html) for extracting results, inspecting execution records and plotting selected contrasts. ## Interpret returned results `tidy_results()` returns one row per returned taxon, contrast and configured step, not a complete grid of all possible tests. `method` identifies the engine and `step_id` identifies its configuration. Custom IDs must not collide with internal columns such as `effect`, `taxa_id` or `sum`; choose distinct IDs such as `linda_sensitivity`. The numerator and denominator define each contrast's orientation. Positive effects point toward the numerator on the reported metric, but the metrics are not numerically interchangeable: | Engine | Effect reported by the centralized API | |:--|:--| | DESeq2 | Log2 fold change, with the configured shrinkage. | | ALDEx2 | Contrast-oriented GLM coefficient. | | ALDEx3 | Log2 abundance coefficient conditional on the scale model. | | ANCOM-BC2 | Bias-corrected log fold change. | | corncob | Logit mean-abundance coefficient. | | LinDA | Bias-corrected log2 fold change. | | MaAsLin3 | Coefficient on the configured transformed abundance scale. | | radEmu | Centred natural-log fold difference across analysis taxa. | | Wilcoxon | Difference in medians on the configured abundance scale. | | LEfSe | Direction-oriented LDA score. | Inspect `effect_metric` and the configured engine options before interpreting an estimate. `significant` preserves the originating method's decision, including any additional criteria such as ANCOM-BC2's pseudocount-sensitivity filter. Missing statistics remain missing: a nonsignificant result does not prove that every estimate was available or that there is no effect. Absent rows are not automatically nonsignificant results. Agreement plots do not establish calibrated false-discovery rates. For centralized ALDEx2 analyses, `effect` is the contrast-oriented coefficient from the same GLM as the adjusted P value, averaged over Monte Carlo instances and labeled `aldex_glm_coefficient`. With default settings it is on the base-2 CLR response scale, not an absolute-abundance fold change or ALDEx2's standardized two-group effect. Advanced native settings can change its scale. ## Advanced native-engine arguments All DA steps accept `engine_args`, a named list grouped by native-call stage. This keeps advanced settings attached to the configured step and avoids an ambiguous `...`. For example: ```{r engine-args} advanced <- recipe(phy) |> add_model( ~ condition + batch + age, targets = "condition", tax_level = "Species", reference = c(condition = "control") ) |> step_deseq( engine_args = list( fit = list(minReplicatesForReplace = Inf), shrink = list(lfcThreshold = 1) ) ) |> step_ancom( engine_args = list( fit = list(iter_control = list(tol = 1e-3, max_iter = 50, verbose = FALSE)) ) ) advanced ``` Nested native control lists replace the corresponding native argument; they are not merged with its defaults. For ANCOM-BC2, supply the complete `iter_control` list, including `verbose`, rather than only the values changed. Available stages are `size_factors`, `fit`, `results`, and `shrink` for DESeq2; `clr` and `fit` for ALDEx2; `fit` for ALDEx3, ANCOM-BC2, corncob, LinDA and radEmu; `fit` and `contrast` for MaAsLin3; `test` for Wilcoxon; and `transform` and `fit` for LEfSe. Data, formulas, contrasts, output paths and arguments already exposed by each dar wrapper are protected. A configured stage that is not used by the selected execution route is reported as an error. Engine-specific validation and errors are left to the engine. dar checks its own configuration, design compatibility and the identities used to align data and results. ALDEx2 effects come directly from the GLM fit. See [Saving and sharing analysis recipes](import_export_recipes.html) for exporting model settings and native options without executing an analysis. ## ALDEx2 and ALDEx3 Use `step_aldex2()` for ALDEx2 and `step_aldex3()` for ALDEx3. Supply sequence counts for ALDEx3 inference. Fixed models use native `lm`; mixed models use exact `lme4`, with one native fit per planned contrast. The approximate `blmm` engine is not enabled. Expect substantial cost for many taxa, Monte Carlo draws and longitudinal contrasts; `nsample = 2000` follows the native default. ```{r aldex3-config} aldex3_rec <- recipe(longitudinal_phy) |> add_model( ~ condition * visit + (1 | subject), targets = "condition", tax_level = "Species", time = "visit", contrasts = "all" ) |> step_aldex3(scale_model = "clr", scale_args = list(gamma = 0.5)) aldex3_rec ``` This is a scale assumption, not a measurement of microbial load. `clr` and `tss` accept a non-negative log2 coefficient SD `gamma`; zero fixes their scale assumption. `sample` accepts external log2 means and SDs named by sample ID (`s.mu`, `s.sd`); `coefficient` accepts means and SDs named by the columns of the resolved fixed design (`c.mu`, `c.sd`). Only independent SDs are supported, not covariance matrices or arbitrary functions. Complete-case selection subsets external information by sample ID. The scale model always uses the original resolved design, so contrast releveling does not change its prior. Shared preprocessing defines the analyzed composition: excluded features are not silently restored as an "other" feature. The default uncertainty is a modeling choice, not a data-derived quantity; coefficient coding and numeric covariate units affect these scale priors. Effects retain their scale-model-dependent interpretation and are labeled `aldex3_log2_abundance_coefficient`. Native P values and adjusted P values include directional Monte Carlo averaging, with adjustment across taxa per coefficient, not across all planned contrasts. Missing estimates stay missing. `get_execution()` records the ALDEx3 version, seed, Monte Carlo settings, scale specification, native engine and elapsed time. ## radEmu: fixed models and clustered inference `step_rademu()` reports native robust score tests by default. Use `test = "wald"` explicitly for native Wald tests. Effects are natural-log fold differences relative to radEmu's pseudo-Huber centre across analysis taxa, not unqualified absolute changes. Each contrast is reparameterized and fitted with its native centring constraint; a nonlinear centre is not replaced by a linear combination of previously centred coefficients. dar adjusts the selected native P values across returned taxa within each contrast, using BH by default. This correction is not joint across planned contrasts. Native missing values and zero-comparison exclusions stay missing. For dependent observations, name a metadata column in `cluster`. This uses radEmu's GEE-based covariance, not a random-intercept model. A formula with random effects is incompatible even if `cluster` is supplied; dar does not silently translate `(1 | subject)` into another dependence model. ```{r rademu-config} rademu_rec <- recipe(longitudinal_phy) |> add_model( ~ condition * visit, targets = "condition", time = "visit", tax_level = "Species", contrasts = "all" ) |> step_rademu(cluster = "subject") rademu_rec ``` Cluster labels follow the common model cohort. Missing cluster IDs are errors, not grounds for a private sample exclusion. Native options can be passed in `engine_args$fit`, for example `tolerance`, `maxit` or `remove_zero_comparison_pvals`; data, tested coordinates and test selection are managed by dar. Native numerical validation stays in radEmu. `get_execution()` records the effective package version, test, centre, requested and effective cluster labels, seed and native convergence diagnostics. Score testing may be expensive because each taxon requires a restricted fit. ```{r session-info} sessionInfo() ```