{"data":{"slug":"github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-batch-effect-correction-8f2ede0fcdb0","title":"Batch Effect Correction for Expression Matrices","summary":"Correct batch effects in merged bulk expression matrices using sample-level batch metadata while preserving biological group structure and generating QC plots.","url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-batch-effect-correction-8f2ede0fcdb0","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-batch-effect-correction-8f2ede0fcdb0","markdown_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-batch-effect-correction-8f2ede0fcdb0.md","download_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-batch-effect-correction-8f2ede0fcdb0\/download","category":{"slug":"data-research","name":"Data & Research"},"editor_note":"Install required R packages (`sva`, `limma`, and `ggplot2`) before running the skill. Ensure gene IDs, sample column names, and expression values meet specific formatting and data requirements. Decide whether log transformation is needed (`auto`, `yes`, or `no`) during preparation.","instructions":"---\nname: batch-effect-correction\ndescription: \"Use when correcting batch effects in merged bulk expression matrices with sample-level batch metadata while preserving biological group structure and generating before-and-after QC plots. NOT for: single-cell integration, raw FASTQ processing, differential expression without batch labels, or datasets without biological groups.\"\nlicense: MIT\nskill-author: AIPOCH\n---\n\n# Batch Effect Correction\n\n## Prerequisites\n\nRun the following before the first analysis to install all required R packages:\n\n```bash\nRscript -e \"if (!require('BiocManager', quietly=TRUE)) install.packages('BiocManager'); BiocManager::install(c('sva', 'limma')); install.packages('ggplot2', repos='https:\/\/cloud.r-project.org')\"\n```\n\n> Note: `sva` and `limma` are Bioconductor packages and require `BiocManager` for installation. `ggplot2` is a standard CRAN package.\n\n**The skill cannot run until these packages are installed.** In new or bare R environments, always run the prerequisite step first.\n\n---\n\n## When to Read External Files\n\n| Situation | File to Read | Purpose |\n|-----------|--------------|---------|\n| **Need algorithm details** | `references\/algorithm.md` | ComBat workflow, assumptions, and QC logic |\n| **Need to run analysis** | `scripts\/main.R` | Execute: `Rscript scripts\/main.R --input_file ... --group_file ...` |\n| **Encounter errors** | `references\/troubleshooting.md` | Common errors and solutions |\n| **Need CLI examples** | `references\/cli-guide.md` | Detailed CLI usage examples and baseline run record |\n| **Need test data** | `tests\/data\/` | Sample input files for testing |\n\n---\n\n## Usage\n\n```bash\nRscript scripts\/main.R \\\n  --input_file .\/expression_matrix.csv \\\n  --group_file .\/sample_info.csv \\\n  --output_dir .\/output\/ \\\n  --batch_column batch \\\n  --group_column group \\\n  --sample_column sample \\\n  --log_transform auto \\\n  --timeout_seconds 600 \\\n  --seed 42\n```\n\n---\n\n## Arguments\n\n| Short | Long | Type | Default | Description |\n|-------|------|------|---------|-------------|\n| `-i` | `--input_file` | character | **required** | Expression matrix file (genes as rows, samples as columns) |\n| `-g` | `--group_file` | character | **required** | Sample metadata file (sample ID, group, and batch columns) |\n| `-o` | `--output_dir` | character | `.\/output\/` | Output directory |\n| `-b` | `--batch_column` | character | `batch` | Batch column name in metadata |\n| `-c` | `--group_column` | character | `group` | Biological group column name in metadata |\n| `-n` | `--sample_column` | character | `sample` | Sample ID column name in metadata |\n| `-l` | `--log_transform` | character | `auto` | Log transform mode: `auto`, `yes`, `no` |\n| `-t` | `--timeout_seconds` | integer | `600` | Elapsed time limit in seconds; use `0` to disable |\n| `-s` | `--seed` | integer | `42` | Random seed for reproducibility |\n\n---\n\n## Input Format\n\n### Expression Matrix (input_file)\n\nGenes as rows, samples as columns, CSV format with gene ID in the first column.\n\n```csv\n\"\",\"Sample01\",\"Sample02\",\"Sample03\"\n\"GeneA\",5.12,4.87,6.03\n\"GeneB\",8.44,8.11,7.95\n```\n\nRequirements:\n- Gene IDs must be unique and non-empty\n- Sample column names must be unique and non-empty\n- Expression values must be numeric and finite\n- Extra expression-matrix sample columns not present in metadata are allowed and will be ignored with a warning\n\n### Sample Metadata (group_file)\n\nCSV with sample ID, biological group, and batch columns.\n\n```csv\n\"sample\",\"group\",\"batch\"\n\"Sample01\",\"Control\",\"Batch1\"\n\"Sample02\",\"Case\",\"Batch1\"\n\"Sample03\",\"Case\",\"Batch2\"\n```\n\nRequirements:\n- Sample IDs must be unique and non-empty\n- At least 2 biological groups are required\n- At least 2 batches are required\n- Each group and each batch must contain at least 2 samples\n- Metadata may describe a subset of expression-matrix samples; the analysis will keep only metadata-matched samples and warn about ignored expression columns\n\n---\n\n## Output Files\n\n| File | Description |\n|------|-------------|\n| `corrected_expression_matrix.csv` | Batch-corrected expression matrix |\n| `matched_sample_info.csv` | Standardized metadata used in the analysis |\n| `batch_before_boxplot.pdf` | Sample distribution boxplot before correction |\n| `batch_after_boxplot.pdf` | Sample distribution boxplot after correction |\n| `batch_before_pca.pdf` | PCA scatter plot before correction with batch-colored points |\n| `batch_after_pca.pdf` | PCA scatter plot after correction with batch-colored points |\n| `batch_before_clustering.pdf` | Hierarchical clustering before correction |\n| `batch_after_clustering.pdf` | Hierarchical clustering after correction |\n| `session_info.txt` | R session and package version info |\n\n---\n\n## Workflow\n\n### Step 1: Validate Input\n- Check file existence and non-empty input files\n- Validate metadata column presence\n- Verify expression values are numeric and finite\n- Confirm at least 2 groups, 2 batches, and at least 2 samples per group\/batch\n\n### Step 2: Align and Prepare Matrix\n- Reorder expression columns to match metadata sample order\n- Keep only metadata-matched samples; warn if the expression matrix contains extra samples absent from metadata\n- Decide whether log transformation is needed (`auto`, `yes`, or `no`)\n- Apply `log2(x + 1)` only when required\n\n### Step 3: Run Batch Correction\n- Build the design matrix with biological group information\n- Run `sva::ComBat()` to remove batch-driven variation\n- Preserve modeled biological group structure during correction\n\n### Step 4: Normalize and Export Results\n- Apply `limma::normalizeBetweenArrays()` after ComBat\n- Write the corrected matrix and matched metadata\n- Save before\/after QC plots and session information\n\n---\n\n## Methods\n\n### ComBat\nEmpirical Bayes batch-effect correction using `sva::ComBat()`. Recommended when merged bulk expression datasets contain known batch labels and at least two biological groups.\n\n### Log Transformation\nSupports `auto`, `yes`, and `no`. The `auto` mode applies `log2(x + 1)` only when the matrix appears to be on a raw-like scale.\n\n### normalizeBetweenArrays\nPost-correction normalization with `limma::normalizeBetweenArrays()` to reduce remaining cross-sample distribution differences.\n\n### QC Visualization\nGenerates paired boxplots, PCA scatter plots with conditional batch ellipses, and hierarchical clustering plots before and after correction to assess whether batch-driven structure is reduced.\n\n---\n\n## Agent Response Contract\n\nAfter a successful run, report:\n\n1. **Sample count** retained after metadata matching and any subset filtering\n2. **Batch count** and **group count** used in the ComBat design matrix\n3. **Log transformation** applied (auto-detected, forced yes, or skipped)\n4. **QC assessment**: describe whether before\/after PCA plots show reduced batch clustering\n5. **Artifact paths**: `corrected_expression_matrix.csv`, `batch_after_pca.pdf`, `batch_after_clustering.pdf`\n\n---\n\n## Examples\n\n### Basic Usage\n```bash\nRscript scripts\/main.R \\\n  -i expression_matrix.csv \\\n  -g sample_info.csv \\\n  -o .\/output\n```\n\n### With Custom Metadata Columns\n```bash\nRscript scripts\/main.R \\\n  -i expression_matrix.csv \\\n  -g metadata.csv \\\n  -o .\/output \\\n  -n sample_id \\\n  -c condition \\\n  -b platform_batch\n```\n\n### Disable Log Transform and Timeout\n```bash\nRscript scripts\/main.R \\\n  -i expression_matrix.csv \\\n  -g sample_info.csv \\\n  -o .\/output \\\n  -l no \\\n  -t 0 \\\n  -s 42\n```\n\n---\n\n## Error Handling\n\n### Common Errors\n\n| Error | Cause | Solution |\n|-------|-------|----------|\n| `SKILL_FILE_NOT_FOUND` | Input file does not exist | Check file path |\n| `SKILL_EMPTY_FILE` | Input file exists but contains no data | Recreate or re-export the file |\n| `SKILL_MISSING_COLUMNS` | Metadata file is missing sample, group, or batch columns | Check header names or pass custom column names |\n| `SKILL_SAMPLE_MISMATCH` | Metadata sample IDs do not match expression matrix columns | Verify sample names between files |\n| `SKILL_INVALID_DATA` | Dataset fails minimum design checks (< 2 batches, < 2 groups, < 2 samples per batch\/group) | Review group counts, batch counts, and ID validity |\n| `SKILL_INVALID_TYPE` | Expression values are non-numeric or non-finite | Clean matrix values before running |\n| `SKILL_TIMEOUT` | Run exceeded the configured time limit | Increase `--timeout_seconds` or set it to `0` |\n| `SKILL_DEPENDENCY_MISSING` | Required R package is not installed | Install with: `Rscript -e \"BiocManager::install(c('sva','limma')); install.packages('ggplot2')\"` |\n| `SKILL_RUNTIME_ERROR` | Runtime I\/O or filesystem error occurred | Check read\/write permissions and environment |\n\n**IF error persists**, READ: `references\/troubleshooting.md`\n\n**Troubleshooting note:** In environments where packages are not yet installed, `SKILL_DEPENDENCY_MISSING` will fire before file-validation or `--help`. Install dependencies first, then re-run to expose file-related errors or access `--help`.\n\n---\n\n## Input Validation\n\nThis skill accepts:\n1. A bulk RNA-seq or microarray expression matrix (CSV, genes as rows, samples as columns)\n2. A sample metadata file (CSV) with sample ID, biological group, and batch columns; at least 2 batches and 2 biological groups are required\n\nIf the user's request does not involve batch effect correction on merged bulk expression matrices \u2014 for example, asking to integrate single-cell RNA-seq data, process raw FASTQ files, run differential expression without batch labels, or analyze datasets with only one batch \u2014 do not proceed with the workflow. Instead respond:\n\n> \"Batch Effect Correction is designed to remove batch-driven variation from merged bulk expression matrices using ComBat, while preserving biological group structure. Your request appears to be outside this scope. Please provide a multi-batch expression matrix with sample-level batch metadata, or use a more appropriate tool for single-cell integration, differential expression, or raw sequencing processing.\"\n\n---\n\n## Testing\n\n### Test with Sample Data\n\n```bash\n# Check help (requires packages installed)\nRscript scripts\/main.R --help\n\n# Run with bundled test data\nRscript scripts\/main.R \\\n  -i tests\/data\/expression_matrix_merged.csv \\\n  -g tests\/data\/sample_info.csv \\\n  -o tests\/output\/\n```\n\n### Validation Commands\n\n```bash\n# Check corrected matrix exists\nls -la tests\/output\/corrected_expression_matrix.csv\n\n# Check matched metadata exists\nls -la tests\/output\/matched_sample_info.csv\n\n# Check PCA output exists\nls -la tests\/output\/batch_after_pca.pdf\n```\n\n---\n\n## Implementation Checklist\n\n- [x] CLI parsing with `optparse`\n- [x] `set.seed()` for reproducibility\n- [x] `requireNamespace()` dependency checks\n- [x] Session info recording\n- [x] Time-limit support through `setTimeLimit()`\n- [x] File reading instructions in SKILL.md\n- [x] Modular script structure in `scripts\/`\n- [x] Test data provided\n- [x] Error handling with `SKILL_*` codes\n- [x] QC plots generated before and after correction\n- [x] References in `references\/` directory\n\n---\n\n*Last updated: 2026-04-27 | Version: 1.1.0*\n","use_cases":["Correct batch effects in RNA-seq expression matrices with sample-level batch metadata","Preserve biological group structure during batch effect correction","Generate QC plots to assess batch effect correction"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/aipoch\/medical-research-skills\/blob\/686e09dfdb45d9fa1a08664f06bb93769b3c9d91\/awesome-med-research-skills\/Data%20Analysis\/batch-effect-correction\/SKILL.md","source_commit":"686e09dfdb45d9fa1a08664f06bb93769b3c9d91","license":"MIT","version":null,"listing_approved_at":"2026-11-24","created_at":"2026-11-23T06:53:33.000000Z","updated_at":"2026-11-24T07:13:04.000000Z","seo_title":"Batch Effect Correction for Expression Matrices","seo_description":"Correct batch effects in merged bulk expression matrices using sample-level batch metadata while preserving biological group structure and generating QC plots.","seo_keywords":["batch effect correction","expression matrix correction","batch effect qc plots","biological group preservation","RNA-seq batch correction"]}}