[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7CV9C6SVYHZ1DBS5GKX7X2D":3,"skill-same:01M7CV9C6SVYHZ1DBS5GKX7X2D":59},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":26,"commitSha":27,"skillDirectory":28,"forksCount":29,"repositoryHtmlUrl":30,"repositoryHomepageUrl":6,"ownerHtmlUrl":31,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":32,"install":33,"resources":46},"01M7CV9C6SVYHZ1DBS5GKX7X2D","bio-experimental-design-batch-design",null,"Designs genomics experiments so technical nuisance variation (batch, lane, plate, flow cell, operator, reagent lot, processing day) is balanced against the biological variable of interest and therefore estimable rather than confounded, using constrained sample-to-batch assignment (designit, OSAT), the confounder\u002Fmediator\u002Fcollider distinction, and the principle that no post-hoc correction recovers a fully confounded design. Covers detecting hidden batches with surrogate variable analysis, a decision table for downstream correction (ComBat-seq, RUVSeq, SVA) whose execution is deferred to differential-expression\u002Fbatch-correction, and reproducibility metadata. Use when assigning samples to sequencing batches\u002Flanes\u002Fplates, avoiding batch-condition confounding, deciding whether a design is salvageable by correction, choosing a correction method, or estimating the number of hidden batches. For the experimental unit, randomization, and blocking concepts see experimental-design\u002Frandomization-blocking.","mrsonord2240\u002Fopenscience-specialists","mrsonord2240","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F76487430?v=4","01M7CTEM40S43GSJZ9A3YCCXZK","Samuel Nord","01M7CTEM4K69JD1GBYNHVJ9ZP4",2,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Fmass-spec-proteomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-experimental-design-batch-design\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: bio-experimental-design-batch-design\ndescription: Designs genomics experiments so technical nuisance variation (batch, lane, plate, flow cell, operator, reagent lot, processing day) is balanced against the biological variable of interest and therefore estimable rather than confounded, using constrained sample-to-batch assignment (designit, OSAT), the confounder\u002Fmediator\u002Fcollider distinction, and the principle that no post-hoc correction recovers a fully confounded design. Covers detecting hidden batches with surrogate variable analysis, a decision table for downstream correction (ComBat-seq, RUVSeq, SVA) whose execution is deferred to differential-expression\u002Fbatch-correction, and reproducibility metadata. Use when assigning samples to sequencing batches\u002Flanes\u002Fplates, avoiding batch-condition confounding, deciding whether a design is salvageable by correction, choosing a correction method, or estimating the number of hidden batches. For the experimental unit, randomization, and blocking concepts see experimental-design\u002Frandomization-blocking.\ntool_type: r\nprimary_tool: designit\n---\n\n## Version Compatibility\n\nReference examples tested with: designit 0.5+, OSAT 1.50+ (Bioconductor), sva 3.50+, RUVSeq 1.36+, limma 3.58+, edgeR 4.0+.\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- R: `packageVersion('\u003Cpkg>')` then `?function_name` to verify parameters\n\nIf code throws an error, introspect the installed package and adapt to the actual API. Notes: OSAT uses `optimal.shuffle()` on a setup object (there is no bare `osat()` function); designit is R6 (`BatchContainer$new()`, `optimize_design()`, `*_score_generator()`) and its signatures drift between releases; `sva::ComBat_seq()` is for integer counts while `ComBat()` expects log-normalized values. Confirm each against the installed vignette before relying on it.\n\n# Batch Design\n\n**\"Design my experiment so batch effects don't ruin it\"** -> Assign samples to batches\u002Flanes\u002Fplates so the biological variable is balanced against (orthogonal to) every technical nuisance factor, making batch estimable rather than confounded — because no post-hoc correction recovers a design where batch and condition are aliased.\n- R: `designit::optimize_design()`, `OSAT::optimal.shuffle()` — constrained assignment at design time\n- R: `sva::sva()`\u002F`num.sv()` — detect hidden batches; `sva::ComBat_seq()`, `RUVSeq::RUVg()` — DOWNSTREAM correction (executed in differential-expression\u002Fbatch-correction)\n\n## The Single Most Important Modern Insight -- No Post-Hoc Method Recovers a Confounded Design\n\nWhen a technical factor is perfectly aliased with the biological factor (all treated in batch 1, all controls in batch 2), batch and condition occupy the same column space and are mathematically non-identifiable; ComBat, SVA, and RUV cannot separate them, and \"removing the batch effect\" removes the biology with it. Worse, on *partially* confounded or merely **unbalanced** designs, mean-centering batches can *manufacture* false positives and inflate downstream confidence — Nygaard, Rødland & Hovig 2016 *Biostatistics* 17:29 showed a pipeline that returned >1000 spurious DE probes where the honest analysis (batch kept *in the model*) found 11. The operative rules: (1) balance the biological variable across batches **at design time** because correction is not a rescue (Leek 2010 *Nat Rev Genet* 11:733); (2) for inference, keep batch *in the model* so its degrees of freedom are charged honestly — reserve a batch-\"cleaned\" matrix for visualization and clustering only. The experimental unit, not the measurement, still defines replication (see experimental-design\u002Frandomization-blocking).\n\n## Confounding vs Blocking vs Nuisance -- the Causal-Graph View\n\nBatch is the genomics face of confounding, and not all metadata should be \"adjusted for\". A **confounder** is a common cause of treatment and outcome (adjust for it); a **mediator** lies on the causal path (adjusting removes signal); a **collider** is a common effect (adjusting *induces* spurious association). \"Adjust for everything measured\" is therefore wrong in general — conditioning on a collider opens a backdoor path. In a properly *randomized* design the biological variable has no confounders by construction, so batch is handled by **balanced assignment + a block\u002Fcovariate term**, not by scrubbing every measured variable.\n\n## Algorithmic Taxonomy -- Design Strategies for Technical Variation\n\n| Strategy | What it does | When to use | Fails when |\n|----------|--------------|-------------|------------|\n| Balanced (orthogonal) assignment | every condition appears equally in every batch | always achievable when batches hold >=1 of each condition | not all conditions fit per batch |\n| Block randomization across batches | randomize condition within each batch | batch = a block; conditions fit per batch | batch variance is genuinely zero (rare) |\n| Incomplete block + batch in model | conditions split across smaller batches, batch term retained | plate\u002Fchip smaller than #conditions | unbalanced split inflates artifacts (Nygaard 2016) |\n| Reference \u002F bridge sample per batch | shared anchor measured in every batch | cross-batch normalization (TMT proteomics, large cohorts) | anchor not representative |\n| Multiplexing + demultiplexing | pool biological units in one lane, split by barcode\u002Fgenotype | breaking the donor\u003C->lane confound (scRNA-seq) | insufficient SNPs\u002Fhashes to assign |\n| Run-order randomization | randomize processing\u002Finjection order | position\u002Ftime gradients (LC-MS, plate edge) | order set by convenience |\n\n## Decision Tree by Scenario\n\n| Scenario | Recommended design | Why |\n|----------|--------------------|-----|\n| 24 samples, 3 batches, 2 conditions | balanced: 4 of each condition per batch | batch orthogonal to condition; estimable |\n| Conditions outnumber batch capacity | incomplete block; keep batch in the DE model | preserves estimability; no scrubbing |\n| Large cohort across many runs | include a shared reference sample per batch | enables cross-batch normalization |\n| scRNA-seq, several donors, few lanes | pool donors per lane, demultiplex (demuxlet \u002F hashing) | removes donor\u003C->lane confound (Kang 2018) |\n| Hidden\u002Funknown technical structure suspected | estimate surrogate variables (SVA), include in model | captures unmodeled variation (Leek & Storey 2007) |\n| Design already confounds batch with condition | redesign; no correction will rescue it | non-identifiable (Nygaard 2016; Leek 2010) |\n| General randomization \u002F blocking \u002F unit choice | -> experimental-design\u002Frandomization-blocking | foundational design structure |\n| Running ComBat-seq \u002F RUVSeq \u002F SVA on real data | -> differential-expression\u002Fbatch-correction | execution lives there; this skill decides |\n\n## Confounded vs Balanced -- the Canonical Contrast\n\n**Goal:** Make batch effects correctable by keeping the biological variable orthogonal to batch.\n\n**Approach:** Never place all of one condition in one batch. Distribute conditions (and known covariates such as sex) equally across batches so a linear model can estimate batch and condition separately.\n\n```r\n# BAD (confounded): batch is aliased with condition -> non-identifiable\n#   batch 1: treat, treat, treat, treat       batch 2: ctrl, ctrl, ctrl, ctrl\n# GOOD (balanced): batch is orthogonal to condition -> batch effect estimable, removable\n#   batch 1: 2 treat + 2 ctrl                 batch 2: 2 treat + 2 ctrl\n```\n\n## Constrained Sample-to-Batch Assignment\n\n**Goal:** Allocate samples to batches\u002Flanes\u002Fplates to minimize correlation between batch and the biological variables of interest.\n\n**Approach:** Use a block-randomization-with-optimization tool that scores assignments by how evenly the biological factors spread across batches and returns a near-optimal layout.\n\n```r\nlibrary(designit)                              # verify API against installed vignette\nsamples \u003C- data.frame(id = sprintf('S%02d', 1:24),\n                      condition = rep(c('ctrl', 'treat'), each = 12),\n                      sex = rep(c('M', 'F'), 12))\nbc \u003C- BatchContainer$new(dimensions = list(batch = 3, position = 8))\nbc \u003C- assign_in_order(bc, samples = samples)\nbc \u003C- optimize_design(\n  bc,\n  scoring = osat_score_generator(batch_vars = 'batch',\n                                 feature_vars = c('condition', 'sex')))   # balance both factors\nassignment \u003C- bc$get_samples()                # R6 method on the container (no standalone get_samples())\n\n# OSAT alternative (Bioconductor): build a setup object, then optimal.shuffle() -- NOT a bare osat().\n```\n\n## Downstream Correction -- Choose by Design, Execute Elsewhere\n\nCorrection method selection is a design decision; the execution lives in differential-expression\u002Fbatch-correction (and single-cell\u002Fbatch-integration for scRNA-seq). Prefer keeping batch in the analysis model over producing a \"cleaned\" matrix for inference.\n\n| Method | When it applies | Assumption \u002F caveat | Owner of execution |\n|--------|-----------------|---------------------|--------------------|\n| Batch as a model covariate | batch known, balanced | charges df honestly; the default for inference | differential-expression |\n| ComBat-seq | known batch, integer counts | batch ~ orthogonal to biology; Nygaard caveat if unbalanced | differential-expression\u002Fbatch-correction |\n| ComBat (parametric eB) | known batch, log-normalized data | Gaussian; not for raw counts | differential-expression\u002Fbatch-correction |\n| RUVSeq (RUVg\u002FRUVs\u002FRUVr) | negative-control genes\u002Fsamples available | controls must be truly null to the biology | differential-expression\u002Fbatch-correction |\n| SVA | hidden\u002Funknown structure | surrogate variables can absorb biology if confounded | this skill estimates; DE consumes |\n| limma removeBatchEffect | visualization\u002Fclustering ONLY | not for the hypothesis test | data-visualization |\n| Harmony \u002F scVI \u002F Seurat anchors | scRNA-seq integration | integration, not DE inference | single-cell\u002Fbatch-integration |\n\n## Detecting Hidden Batch Effects (SVA)\n\n**Goal:** Estimate unmodeled technical structure (hidden batches) so it can be included in the downstream model.\n\n**Approach:** Fit a model matrix for the biological variable and a null matrix, estimate the number of surrogate variables, then compute them for inclusion as covariates in the DE analysis.\n\n```r\nlibrary(sva)\nmod  \u003C- model.matrix(~ condition, data = colData)   # full model\nmod0 \u003C- model.matrix(~ 1, data = colData)           # null model\nn_sv \u003C- num.sv(expr_normalized, mod)                # estimate number of hidden batches\nsvobj \u003C- sva(expr_normalized, mod, mod0, n.sv = n_sv)\n# Add svobj$sv to the design used by differential-expression\u002Fde-results; do NOT subtract them\n# from the data for the test (subtracting is for visualization only).\n```\n\n## Per-Method Failure Modes\n\n### Batch confounded with condition\n- **Trigger:** all of one condition processed in one batch\u002Frun.\n- **Mechanism:** batch and condition are aliased -> non-identifiable.\n- **Symptom:** condition effect vanishes (or an artifact appears) after correction.\n- **Fix:** redesign with balanced assignment; no post-hoc method recovers it (Leek 2010).\n\n### ComBat on unbalanced groups\n- **Trigger:** ComBat applied when condition is partially confounded with batch.\n- **Mechanism:** mean-centering batches injects between-group differences and understates residual variance.\n- **Symptom:** inflated DE counts and over-confident downstream inference (Nygaard 2016).\n- **Fix:** keep batch in the model (ComBat-seq with the biological covariate, or batch as a DE covariate); best is balanced design.\n\n### Subtracting surrogate variables before testing\n- **Trigger:** feeding an SV-\"cleaned\" matrix into the DE test.\n- **Mechanism:** double-counts the adjustment and loses degrees of freedom.\n- **Symptom:** anti-conservative p-values.\n- **Fix:** include SVs as covariates in the model; reserve cleaned matrices for plots.\n\n### Adjusting for a collider\n- **Trigger:** \"adjust for everything measured\" includes a downstream\u002Fcommon-effect variable.\n- **Mechanism:** conditioning on a collider opens a spurious path.\n- **Symptom:** associations that appear only after adjustment.\n- **Fix:** adjust for confounders (common causes), not mediators or colliders.\n\n## Quantitative Thresholds\n\n| Threshold | Source | Rationale |\n|-----------|--------|-----------|\n| Balance every condition equally across batches | Leek 2010 *Nat Rev Genet* 11:733 | makes batch estimable and removable |\n| Unbalanced ComBat can inflate DE (>1000 vs 11 in one case) | Nygaard 2016 *Biostatistics* 17:29 | mean-centering injects group differences |\n| ~50 SNPs\u002Fcell suffice to demultiplex pooled donors | Kang 2018 *Nat Biotechnol* 36:89 | breaks donor\u003C->lane confound |\n| Keep batch in the model for inference; clean only for viz | Nygaard 2016; Leek 2010 | honest degrees of freedom |\n\n## Common Errors\n\n| Error \u002F symptom | Cause | Solution |\n|-----------------|-------|----------|\n| Condition effect disappears after ComBat | batch confounded with condition | balance at design time |\n| Inflated DE list after batch correction | unbalanced ComBat | keep batch in model; ComBat-seq with covariate |\n| scRNA-seq donor effect equals lane effect | one donor per lane | pool + demultiplex (demuxlet \u002F hashing) |\n| Spurious associations after \"adjusting for all metadata\" | conditioning on a collider\u002Fmediator | adjust only for confounders |\n| Cannot reconstruct who\u002Fwhen\u002Fwhich-lot | no metadata captured | record date, lot, operator, lane, position |\n\n## Reproducibility Metadata\n\nRecord for every sample, because these become the batch\u002Fblocking variables: processing date, reagent and kit lot numbers, operator, instrument\u002Fflow-cell\u002Flane and well\u002Fplate position, library prep batch, and any protocol deviations. Unrecorded technical variation cannot be modeled or balanced after the fact, and is a leakage source for any downstream machine-learning model (see machine-learning\u002Fmodel-validation).\n\n## References\n\n- Leek JT, Scharpf RB, Bravo HC, Simcha D, Langmead B, Johnson WE, Geman D, Baggerly K, Irizarry RA. 2010. Tackling the widespread and critical impact of batch effects in high-throughput data. *Nat Rev Genet* 11:733-739.\n- Nygaard V, Rødland EA, Hovig E. 2016. Methods that remove batch effects while retaining group differences may lead to exaggerated confidence in downstream analyses. *Biostatistics* 17:29-39.\n- Johnson WE, Li C, Rabinovic A. 2007. Adjusting batch effects in microarray expression data using empirical Bayes methods. *Biostatistics* 8:118-127.\n- Zhang Y, Parmigiani G, Johnson WE. 2020. ComBat-seq: batch effect adjustment for RNA-seq count data. *NAR Genom Bioinform* 2:lqaa078.\n- Leek JT, Storey JD. 2007. Capturing heterogeneity in gene expression studies by surrogate variable analysis. *PLoS Genet* 3:e161.\n- Gagnon-Bartsch JA, Speed TP. 2012. Using control genes to correct for unwanted variation in microarray data. *Biostatistics* 13:539-552.\n- Kang HM, Subramaniam M, Targ S, et al. 2018. Multiplexed droplet single-cell RNA-sequencing using natural genetic variation. *Nat Biotechnol* 36:89-94.\n- Yan L, Ma C, Wang D, Hu Q, Qin M, Conroy JM, Sucheston LE, Ambrosone CB, Johnson CS, Wang J, Liu S. 2012. OSAT: a tool for sample-to-batch allocations in genomics experiments. *BMC Genomics* 13:689.\n\n## Related Skills\n\n- randomization-blocking - The experimental unit, randomization, and blocking concepts behind a good batch layout\n- power-analysis - Account for blocking\u002Fbatch factors in the power calculation\n- sample-size - Balanced designs assume equal n per group\n- multiple-testing - Surrogate variables change the effective number of tests\n- differential-expression\u002Fbatch-correction - Executes ComBat-seq\u002FRUVSeq\u002FSVA on real data\n- single-cell\u002Fbatch-integration - scRNA-seq integration (Harmony, scVI, Seurat anchors)\n- machine-learning\u002Fmodel-validation - Batch confounding is a data-leakage source for ML\n- clinical-biostatistics\u002Fpower-and-sample-size - Trial randomization and design (regulated regime)\n","## Version Compatibility\n\nReference examples tested with: designit 0.5+, OSAT 1.50+ (Bioconductor), sva 3.50+, RUVSeq 1.36+, limma 3.58+, edgeR 4.0+.\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- R: `packageVersion('\u003Cpkg>')` then `?function_name` to verify parameters\n\nIf code throws an error, introspect the installed package and adapt to the actual API. Notes: OSAT uses `optimal.shuffle()` on a setup object (there is no bare `osat()` function); designit is R6 (`BatchContainer$new()`, `optimize_design()`, `*_score_generator()`) and its signatures drift between releases; `sva::ComBat_seq()` is for integer counts while `ComBat()` expects log-normalized values. Confirm each against the installed vignette before relying on it.\n\n# Batch Design\n\n**\"Design my experiment so batch effects don't ruin it\"** -> Assign samples to batches\u002Flanes\u002Fplates so the biological variable is balanced against (orthogonal to) every technical nuisance factor, making batch estimable rather than confounded — because no post-hoc correction recovers a design where batch and condition are aliased.\n- R: `designit::optimize_design()`, `OSAT::optimal.shuffle()` — constrained assignment at design time\n- R: `sva::sva()`\u002F`num.sv()` — detect hidden batches; `sva::ComBat_seq()`, `RUVSeq::RUVg()` — DOWNSTREAM correction (executed in differential-expression\u002Fbatch-correction)\n\n## The Single Most Important Modern Insight -- No Post-Hoc Method Recovers a Confounded Design\n\nWhen a technical factor is perfectly aliased with the biological factor (all treated in batch 1, all controls in batch 2), batch and condition occupy the same column space and are mathematically non-identifiable; ComBat, SVA, and RUV cannot separate them, and \"removing the batch effect\" removes the biology with it. Worse, on *partially* confounded or merely **unbalanced** designs, mean-centering batches can *manufacture* false positives and inflate downstream confidence — Nygaard, Rødland & Hovig 2016 *Biostatistics* 17:29 showed a pipeline that returned >1000 spurious DE probes where the honest analysis (batch kept *in the model*) found 11. The operative rules: (1) balance the biological variable across batches **at design time** because correction is not a rescue (Leek 2010 *Nat Rev Genet* 11:733); (2) for inference, keep batch *in the model* so its degrees of freedom are charged honestly — reserve a batch-\"cleaned\" matrix for visualization and clustering only. The experimental unit, not the measurement, still defines replication (see experimental-design\u002Frandomization-blocking).\n\n## Confounding vs Blocking vs Nuisance -- the Causal-Graph View\n\nBatch is the genomics face of confounding, and not all metadata should be \"adjusted for\". A **confounder** is a common cause of treatment and outcome (adjust for it); a **mediator** lies on the causal path (adjusting removes signal); a **collider** is a common effect (adjusting *induces* spurious association). \"Adjust for everything measured\" is therefore wrong in general — conditioning on a collider opens a backdoor path. In a properly *randomized* design the biological variable has no confounders by construction, so batch is handled by **balanced assignment + a block\u002Fcovariate term**, not by scrubbing every measured variable.\n\n## Algorithmic Taxonomy -- Design Strategies for Technical Variation\n\n| Strategy | What it does | When to use | Fails when |\n|----------|--------------|-------------|------------|\n| Balanced (orthogonal) assignment | every condition appears equally in every batch | always achievable when batches hold >=1 of each condition | not all conditions fit per batch |\n| Block randomization across batches | randomize condition within each batch | batch = a block; conditions fit per batch | batch variance is genuinely zero (rare) |\n| Incomplete block + batch in model | conditions split across smaller batches, batch term retained | plate\u002Fchip smaller than #conditions | unbalanced split inflates artifacts (Nygaard 2016) |\n| Reference \u002F bridge sample per batch | shared anchor measured in every batch | cross-batch normalization (TMT proteomics, large cohorts) | anchor not representative |\n| Multiplexing + demultiplexing | pool biological units in one lane, split by barcode\u002Fgenotype | breaking the donor\u003C->lane confound (scRNA-seq) | insufficient SNPs\u002Fhashes to assign |\n| Run-order randomization | randomize processing\u002Finjection order | position\u002Ftime gradients (LC-MS, plate edge) | order set by convenience |\n\n## Decision Tree by Scenario\n\n| Scenario | Recommended design | Why |\n|----------|--------------------|-----|\n| 24 samples, 3 batches, 2 conditions | balanced: 4 of each condition per batch | batch orthogonal to condition; estimable |\n| Conditions outnumber batch capacity | incomplete block; keep batch in the DE model | preserves estimability; no scrubbing |\n| Large cohort across many runs | include a shared reference sample per batch | enables cross-batch normalization |\n| scRNA-seq, several donors, few lanes | pool donors per lane, demultiplex (demuxlet \u002F hashing) | removes donor\u003C->lane confound (Kang 2018) |\n| Hidden\u002Funknown technical structure suspected | estimate surrogate variables (SVA), include in model | captures unmodeled variation (Leek & Storey 2007) |\n| Design already confounds batch with condition | redesign; no correction will rescue it | non-identifiable (Nygaard 2016; Leek 2010) |\n| General randomization \u002F blocking \u002F unit choice | -> experimental-design\u002Frandomization-blocking | foundational design structure |\n| Running ComBat-seq \u002F RUVSeq \u002F SVA on real data | -> differential-expression\u002Fbatch-correction | execution lives there; this skill decides |\n\n## Confounded vs Balanced -- the Canonical Contrast\n\n**Goal:** Make batch effects correctable by keeping the biological variable orthogonal to batch.\n\n**Approach:** Never place all of one condition in one batch. Distribute conditions (and known covariates such as sex) equally across batches so a linear model can estimate batch and condition separately.\n\n```r\n# BAD (confounded): batch is aliased with condition -> non-identifiable\n#   batch 1: treat, treat, treat, treat       batch 2: ctrl, ctrl, ctrl, ctrl\n# GOOD (balanced): batch is orthogonal to condition -> batch effect estimable, removable\n#   batch 1: 2 treat + 2 ctrl                 batch 2: 2 treat + 2 ctrl\n```\n\n## Constrained Sample-to-Batch Assignment\n\n**Goal:** Allocate samples to batches\u002Flanes\u002Fplates to minimize correlation between batch and the biological variables of interest.\n\n**Approach:** Use a block-randomization-with-optimization tool that scores assignments by how evenly the biological factors spread across batches and returns a near-optimal layout.\n\n```r\nlibrary(designit)                              # verify API against installed vignette\nsamples \u003C- data.frame(id = sprintf('S%02d', 1:24),\n                      condition = rep(c('ctrl', 'treat'), each = 12),\n                      sex = rep(c('M', 'F'), 12))\nbc \u003C- BatchContainer$new(dimensions = list(batch = 3, position = 8))\nbc \u003C- assign_in_order(bc, samples = samples)\nbc \u003C- optimize_design(\n  bc,\n  scoring = osat_score_generator(batch_vars = 'batch',\n                                 feature_vars = c('condition', 'sex')))   # balance both factors\nassignment \u003C- bc$get_samples()                # R6 method on the container (no standalone get_samples())\n\n# OSAT alternative (Bioconductor): build a setup object, then optimal.shuffle() -- NOT a bare osat().\n```\n\n## Downstream Correction -- Choose by Design, Execute Elsewhere\n\nCorrection method selection is a design decision; the execution lives in differential-expression\u002Fbatch-correction (and single-cell\u002Fbatch-integration for scRNA-seq). Prefer keeping batch in the analysis model over producing a \"cleaned\" matrix for inference.\n\n| Method | When it applies | Assumption \u002F caveat | Owner of execution |\n|--------|-----------------|---------------------|--------------------|\n| Batch as a model covariate | batch known, balanced | charges df honestly; the default for inference | differential-expression |\n| ComBat-seq | known batch, integer counts | batch ~ orthogonal to biology; Nygaard caveat if unbalanced | differential-expression\u002Fbatch-correction |\n| ComBat (parametric eB) | known batch, log-normalized data | Gaussian; not for raw counts | differential-expression\u002Fbatch-correction |\n| RUVSeq (RUVg\u002FRUVs\u002FRUVr) | negative-control genes\u002Fsamples available | controls must be truly null to the biology | differential-expression\u002Fbatch-correction |\n| SVA | hidden\u002Funknown structure | surrogate variables can absorb biology if confounded | this skill estimates; DE consumes |\n| limma removeBatchEffect | visualization\u002Fclustering ONLY | not for the hypothesis test | data-visualization |\n| Harmony \u002F scVI \u002F Seurat anchors | scRNA-seq integration | integration, not DE inference | single-cell\u002Fbatch-integration |\n\n## Detecting Hidden Batch Effects (SVA)\n\n**Goal:** Estimate unmodeled technical structure (hidden batches) so it can be included in the downstream model.\n\n**Approach:** Fit a model matrix for the biological variable and a null matrix, estimate the number of surrogate variables, then compute them for inclusion as covariates in the DE analysis.\n\n```r\nlibrary(sva)\nmod  \u003C- model.matrix(~ condition, data = colData)   # full model\nmod0 \u003C- model.matrix(~ 1, data = colData)           # null model\nn_sv \u003C- num.sv(expr_normalized, mod)                # estimate number of hidden batches\nsvobj \u003C- sva(expr_normalized, mod, mod0, n.sv = n_sv)\n# Add svobj$sv to the design used by differential-expression\u002Fde-results; do NOT subtract them\n# from the data for the test (subtracting is for visualization only).\n```\n\n## Per-Method Failure Modes\n\n### Batch confounded with condition\n- **Trigger:** all of one condition processed in one batch\u002Frun.\n- **Mechanism:** batch and condition are aliased -> non-identifiable.\n- **Symptom:** condition effect vanishes (or an artifact appears) after correction.\n- **Fix:** redesign with balanced assignment; no post-hoc method recovers it (Leek 2010).\n\n### ComBat on unbalanced groups\n- **Trigger:** ComBat applied when condition is partially confounded with batch.\n- **Mechanism:** mean-centering batches injects between-group differences and understates residual variance.\n- **Symptom:** inflated DE counts and over-confident downstream inference (Nygaard 2016).\n- **Fix:** keep batch in the model (ComBat-seq with the biological covariate, or batch as a DE covariate); best is balanced design.\n\n### Subtracting surrogate variables before testing\n- **Trigger:** feeding an SV-\"cleaned\" matrix into the DE test.\n- **Mechanism:** double-counts the adjustment and loses degrees of freedom.\n- **Symptom:** anti-conservative p-values.\n- **Fix:** include SVs as covariates in the model; reserve cleaned matrices for plots.\n\n### Adjusting for a collider\n- **Trigger:** \"adjust for everything measured\" includes a downstream\u002Fcommon-effect variable.\n- **Mechanism:** conditioning on a collider opens a spurious path.\n- **Symptom:** associations that appear only after adjustment.\n- **Fix:** adjust for confounders (common causes), not mediators or colliders.\n\n## Quantitative Thresholds\n\n| Threshold | Source | Rationale |\n|-----------|--------|-----------|\n| Balance every condition equally across batches | Leek 2010 *Nat Rev Genet* 11:733 | makes batch estimable and removable |\n| Unbalanced ComBat can inflate DE (>1000 vs 11 in one case) | Nygaard 2016 *Biostatistics* 17:29 | mean-centering injects group differences |\n| ~50 SNPs\u002Fcell suffice to demultiplex pooled donors | Kang 2018 *Nat Biotechnol* 36:89 | breaks donor\u003C->lane confound |\n| Keep batch in the model for inference; clean only for viz | Nygaard 2016; Leek 2010 | honest degrees of freedom |\n\n## Common Errors\n\n| Error \u002F symptom | Cause | Solution |\n|-----------------|-------|----------|\n| Condition effect disappears after ComBat | batch confounded with condition | balance at design time |\n| Inflated DE list after batch correction | unbalanced ComBat | keep batch in model; ComBat-seq with covariate |\n| scRNA-seq donor effect equals lane effect | one donor per lane | pool + demultiplex (demuxlet \u002F hashing) |\n| Spurious associations after \"adjusting for all metadata\" | conditioning on a collider\u002Fmediator | adjust only for confounders |\n| Cannot reconstruct who\u002Fwhen\u002Fwhich-lot | no metadata captured | record date, lot, operator, lane, position |\n\n## Reproducibility Metadata\n\nRecord for every sample, because these become the batch\u002Fblocking variables: processing date, reagent and kit lot numbers, operator, instrument\u002Fflow-cell\u002Flane and well\u002Fplate position, library prep batch, and any protocol deviations. Unrecorded technical variation cannot be modeled or balanced after the fact, and is a leakage source for any downstream machine-learning model (see machine-learning\u002Fmodel-validation).\n\n## References\n\n- Leek JT, Scharpf RB, Bravo HC, Simcha D, Langmead B, Johnson WE, Geman D, Baggerly K, Irizarry RA. 2010. Tackling the widespread and critical impact of batch effects in high-throughput data. *Nat Rev Genet* 11:733-739.\n- Nygaard V, Rødland EA, Hovig E. 2016. Methods that remove batch effects while retaining group differences may lead to exaggerated confidence in downstream analyses. *Biostatistics* 17:29-39.\n- Johnson WE, Li C, Rabinovic A. 2007. Adjusting batch effects in microarray expression data using empirical Bayes methods. *Biostatistics* 8:118-127.\n- Zhang Y, Parmigiani G, Johnson WE. 2020. ComBat-seq: batch effect adjustment for RNA-seq count data. *NAR Genom Bioinform* 2:lqaa078.\n- Leek JT, Storey JD. 2007. Capturing heterogeneity in gene expression studies by surrogate variable analysis. *PLoS Genet* 3:e161.\n- Gagnon-Bartsch JA, Speed TP. 2012. Using control genes to correct for unwanted variation in microarray data. *Biostatistics* 13:539-552.\n- Kang HM, Subramaniam M, Targ S, et al. 2018. Multiplexed droplet single-cell RNA-sequencing using natural genetic variation. *Nat Biotechnol* 36:89-94.\n- Yan L, Ma C, Wang D, Hu Q, Qin M, Conroy JM, Sucheston LE, Ambrosone CB, Johnson CS, Wang J, Liu S. 2012. OSAT: a tool for sample-to-batch allocations in genomics experiments. *BMC Genomics* 13:689.\n\n## Related Skills\n\n- randomization-blocking - The experimental unit, randomization, and blocking concepts behind a good batch layout\n- power-analysis - Account for blocking\u002Fbatch factors in the power calculation\n- sample-size - Balanced designs assume equal n per group\n- multiple-testing - Surrogate variables change the effective number of tests\n- differential-expression\u002Fbatch-correction - Executes ComBat-seq\u002FRUVSeq\u002FSVA on real data\n- single-cell\u002Fbatch-integration - scRNA-seq integration (Harmony, scVI, Seurat anchors)\n- machine-learning\u002Fmodel-validation - Batch confounding is a data-leakage source for ML\n- clinical-biostatistics\u002Fpower-and-sample-size - Trial randomization and design (regulated regime)\n",{"name":5,"tool_type":24,"description":7,"primary_tool":25},"r","designit","main","e0956dc9606356ab78468936b502e55a365282e2","specialists\u002Fmass-spec-proteomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-experimental-design-batch-design",0,"https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists","https:\u002F\u002Fgithub.com\u002Fmrsonord2240","2026-10-12 03:19:04",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add mrsonord2240\u002Fopenscience-specialists --skill bio-experimental-design-batch-design",{"tool":39,"command":40},"bunx","bunx skills add mrsonord2240\u002Fopenscience-specialists --skill bio-experimental-design-batch-design",{"tool":42,"command":43},"pnpm","pnpm dlx skills add mrsonord2240\u002Fopenscience-specialists --skill bio-experimental-design-batch-design","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Fmass-spec-proteomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-experimental-design-batch-design\u002FSKILL.md",true,[47,53],{"path":48,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":51,"sourceHtmlUrl":52},"examples\u002Fbatch_design.R","OTHER","其他",3810,"https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Fmass-spec-proteomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-experimental-design-batch-design\u002Fexamples\u002Fbatch_design.R",{"path":54,"resourceType":55,"resourceTypeDesc":56,"sizeBytes":57,"sourceHtmlUrl":58},"usage-guide.md","REFERENCE","参考文档",3799,"https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Fmass-spec-proteomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-experimental-design-batch-design\u002Fusage-guide.md",[60,67,74,81,88,95],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M7CW36A6QAGWFE2C008M1XPG","bio-workflows-metabolomics-pipeline","Orchestrates the untargeted LC-MS metabolomics pipeline end-to-end (xcms 4.x feature extraction, QC\u002Fdrift\u002Fnormalization, confidence-stratified annotation, permutation-validated statistics, background-aware pathway mapping), naming what each stage decides and where it silently fails. Use when running a full LC-MS metabolomics study from raw mzML to enriched pathways and needing the honest handoffs between stages. Each stage defers to its component skill for parameters and traps; for stable-isotope flux (a separate branch, not this untargeted flow) see metabolomics\u002Fisotope-tracing.","https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Funtargeted-metabolomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-workflows-metabolomics-pipeline\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M7CW2Y18623NA2S1Y30FRQW1","bio-metabolomics-xcms-preprocessing","Programmatic untargeted LC-MS feature extraction in R with the modern xcms 4.x MsExperiment\u002FXcmsExperiment API, taking raw mzML to a feature table via CentWave peak detection, retention-time alignment, peak-density correspondence, gap-filling, CAMERA redundancy collapse, and built-in QC feature filtering. Use when converting centroided LC-MS runs into a features-by-samples matrix and deciding centWave\u002Fgrouping\u002Falignment parameters. For drift correction and QC\u002FCV filtering execution see metabolomics\u002Fnormalization-qc; for metabolite identification see metabolomics\u002Fmetabolite-annotation; for the MS-DIAL GUI alternative with MS2Dec deconvolution see metabolomics\u002Fmsdial-preprocessing; for downstream statistics see metabolomics\u002Fstatistical-analysis.","https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Funtargeted-metabolomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-metabolomics-xcms-preprocessing\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M7CW2M364HVWPNQEKE2WP4PP","bio-metabolomics-statistical-analysis","Decision-grade statistical analysis for metabolomics intensity tables. Covers transformation and scaling (Pareto vs unit-variance as a hidden hypothesis), unsupervised structure (PCA\u002FHCA for QC), permutation-validated PLS-DA\u002FOPLS-DA (R2 vs Q2, double CV, VIP as heuristic), univariate testing (Welch\u002FMann-Whitney\u002FANOVA\u002FLMM with covariate adjustment), and dependence-aware multiple testing. Use when testing which metabolites differ, building or validating a discriminant model, choosing a scaling, or correcting many correlated tests. For sample-wise normalization\u002Fdrift correction see metabolomics\u002Fnormalization-qc; for ML classifiers and selection-inside-CV leakage see machine-learning\u002Fbiomarker-discovery and machine-learning\u002Fmodel-validation; for pathway interpretation see metabolomics\u002Fpathway-mapping; for design\u002Fpower\u002Fmultiplicity regime see experimental-design\u002Fmultiple-testing.","https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Funtargeted-metabolomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-metabolomics-statistical-analysis\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M7CW2BCBF851WYE03Z8XPEDQ","bio-metabolomics-pathway-mapping","Maps metabolomics results to biological pathways via over-representation (ORA), metabolite-set enrichment (MSEA\u002FQEA), mummichog\u002FPSEA on raw m\u002Fz peaks, and network-diffusion enrichment (FELLA), with correct background-set construction and honest interpretive ceilings. Use when interpreting differential metabolites or an untargeted LC-MS feature table in pathway context, choosing ORA vs MSEA vs mummichog vs topology, or setting the reference\u002Fbackground set. For annotation confidence levels feeding ORA see metabolomics\u002Fmetabolite-annotation; for gene-set concepts see pathway-analysis\u002Fgo-enrichment and pathway-analysis\u002Fgsea; for joint gene+metabolite pathways see multi-omics-integration\u002Fmofa-integration.","https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Funtargeted-metabolomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-metabolomics-pathway-mapping\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M7CW21NSZMCPMF7D9CHJM718","bio-metabolomics-normalization-qc","Designs QC, corrects signal drift, removes batch effects, filters features, normalizes samples, and imputes missing values for untargeted LC-MS\u002FGC-MS metabolomics, framing each step as a measurement model that can create or erase biological signal. Use when processing a peak\u002Ffeature table before statistical analysis, choosing a drift-correction or sample-normalization method, deciding QC RSD vs D-ratio filtering, or handling left-censored missing values. The feature table is produced by metabolomics\u002Fxcms-preprocessing or metabolomics\u002Fmsdial-preprocessing; transformation\u002Fscaling for modeling defers to metabolomics\u002Fstatistical-analysis; cross-study design issues link to experimental-design\u002Fbatch-design.","https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Funtargeted-metabolomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-metabolomics-normalization-qc\u002FSKILL.md",[],[],{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":19},"01M7CW1SWVM0NYHVE6Q7MA3G7R","bio-metabolomics-msdial-preprocessing","Runs the MS-DIAL preprocessing workflow (peak picking, MS2Dec spectral deconvolution, alignment, gap-filling) and imports the alignment-result table into R or Python with honest filtering. Use when preprocessing LC-MS DDA\u002FDIA (SWATH) or GC-MS raw data with MS-DIAL, deciding MS-DIAL vs XCMS, configuring the MSDIALCUI console run, or parsing an MS-DIAL export into a clean feature matrix. For programmatic R peak detection and the feature-table-as-artifact framing see metabolomics\u002Fxcms-preprocessing; for lipid annotation mode see metabolomics\u002Flipidomics; for MSI-level confidence honesty see metabolomics\u002Fmetabolite-annotation; for drift correction and QC see metabolomics\u002Fnormalization-qc.","https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Funtargeted-metabolomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-metabolomics-msdial-preprocessing\u002FSKILL.md",[],[]]