{"data":{"slug":"github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-knn-imputation-86492349851a","title":"KNN Imputation for Bulk Expression Matrices","summary":"Impute missing values in bulk expression matrices using group-aware KNN with DMwR2. This tool is designed for use when filtering genes with high missingness and imputing values with donor samples restricted by a single annotation column. The output is an imputed matrix with missing values filled based on group-stratified KNN or row-wise filling for small strata.","url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-knn-imputation-86492349851a","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-knn-imputation-86492349851a","markdown_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-knn-imputation-86492349851a.md","download_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-knn-imputation-86492349851a\/download","category":{"slug":"data-research","name":"Data & Research"},"editor_note":"Install DMwR2 from GitHub using `remotes::install_github(\"cran\/DMwR2\")` before running the script, as it is not available on CRAN. Ensure the input file has features in rows and samples in columns, with missing values encoded as empty cells or `NA`. The group file must contain a sample ID column and a single grouping column used for stratification.","instructions":"---\nname: knn-imputation\ndescription: \"Use when filtering genes with high missingness and then imputing missing values in a bulk expression matrix with group-aware KNN through DMwR2, where donor samples are restricted by one annotation column before imputation. For strata with 10 or fewer samples, the script falls back to row-wise direct filling with mean or median. NOT for: single-cell data, multi-column stratification, non-tabular inputs, network access, or interactive workflows.\"\nlicense: MIT\nskill-author: AIPOCH\n---\n\n# KNN Imputation\n\n## When to Use\n\nUse this skill when you need to remove genes with more than 50% missing values from a bulk expression matrix and then run group-aware KNN imputation, with the donor pool restricted by one grouping column.\n\nDo not use this skill for:\n- single-cell data\n- multi-column stratification\n- non-tabular inputs\n- network-dependent workflows\n- interactive analysis sessions\n\n## When to Read External Files\n\n| Situation | File to Read | Purpose |\n|-----------|--------------|---------|\n| **Need algorithm details** | `references\/algorithm.md` | Group-stratified KNN method, fallback rules, and assumptions |\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 |\n| **Need sample input fixtures** | `tests\/data\/` | Repository fixtures for local validation and examples |\n\n## Input Validation\n\nThis skill accepts: a bulk expression matrix CSV (features \u00d7 samples) and a sample annotation CSV file with a single grouping column for KNN stratification.\n\nIf the user's request does not involve imputing missing values in a bulk expression matrix \u2014 for example, asking to impute single-cell data, use multi-column stratification, or run network-dependent workflows \u2014 do not proceed with the workflow. Instead respond:\n> \"knn-imputation is designed to filter and impute missing values in bulk expression matrices using group-aware KNN with DMwR2. Your request appears to be outside this scope. Please provide a bulk expression matrix with a single grouping column, or use a more appropriate tool for your task.\"\n\n## Prerequisites\n\nDMwR2 is **not available on CRAN**. Install it from GitHub before running:\n\n```r\ninstall.packages(\"remotes\")\nremotes::install_github(\"cran\/DMwR2\")\n```\n\nIf `SKILL_DEPENDENCY_MISSING` is raised, use the command above to install DMwR2 before retrying. Standard `install.packages(\"DMwR2\")` will not work.\n\n---\n\n## Usage\n\n```bash\nRscript scripts\/main.R \\\n  --input_file tests\/data\/sample_expression_matrix.csv \\\n  --group_file tests\/data\/sample_groups.csv \\\n  --output_dir tests\/output\/basic_run \\\n  --sample_column sample \\\n  --group_column group \\\n  --k 10 \\\n  --small_strata_fill_method mean \\\n  --overwrite \\\n  --timeout_seconds 0 \\\n  --seed 42\n```\n\nIf re-running into an existing `output_dir`, pass `--overwrite`. Otherwise use a fresh output directory.\n\n---\n\n## Arguments\n\n| Short | Long | Type | Default | Description |\n|-------|------|------|---------|-------------|\n| `-i` | `--input_file` | character | **required** | Expression matrix CSV file with features in rows and samples in columns |\n| `-g` | `--group_file` | character | **required** | Sample annotation CSV file |\n| `-o` | `--output_dir` | character | `.\/output\/` | Output directory |\n| `-c` | `--sample_column` | character | `sample` | Sample ID column in the group file |\n| `-l` | `--group_column` | character | `group` | Single grouping column used to define imputation strata |\n| `-k` | `--k` | integer | `10` | Number of nearest neighbors used inside each stratum |\n| `-m` | `--small_strata_fill_method` | character | `mean` | Fill method for strata with 10 or fewer samples: `mean` or `median` |\n|  | `--overwrite` | flag | `FALSE` | Overwrite existing output files in `output_dir` |\n| `-t` | `--timeout_seconds` | integer | `0` | Optional elapsed timeout in seconds, `0` disables timeout |\n| `-s` | `--seed` | integer | `42` | Random seed for reproducibility |\n\n---\n\n## Input Format\n\n### Expression Matrix (`input_file`)\n\nFeatures as rows, samples as columns, CSV format with feature ID in the first column.\n\n```csv\n,Sample01,Sample02,Sample03\nTSPAN6,1.84,1.83,3.82\nSEMA3F,4.83,4.04,5.28\n```\n\nRequirements:\n- The first column stores feature IDs.\n- All remaining columns must be numeric or empty.\n- Missing values must be encoded as empty cells or `NA`.\n\n### Group File (`group_file`)\n\nCSV with one sample ID column and one grouping column.\n\n```csv\nsample,group\nSample01,case\nSample02,control\nSample03,case\n```\n\nRequirements:\n- `sample_column` must match the expression matrix sample names exactly.\n- The column named in `group_column` must exist in the group file.\n- `sample_column` and the selected grouping column must be non-missing.\n- KNN only runs for strata with at least 11 samples.\n- Strata with 10 or fewer samples use row-wise direct filling with `--small_strata_fill_method`.\n\n---\n\n## Output Files\n\n| File | Format | Description |\n|------|--------|-------------|\n| `imputed_expression_matrix.csv` | CSV | Complete imputed expression matrix |\n| `session_info.txt` | TXT | R session and package version information |\n\n---\n\n## Workflow\n\n### Step 1: Validate Input\n- Check file existence.\n- Validate sample matching between expression matrix and group file.\n- Verify that the requested grouping column exists.\n\n### Step 2: Filter Genes\n- Remove genes whose missing-value fraction across all samples is at least 50%.\n- Stop if all genes are removed by this filter.\n\n### Step 3: Build Strata\n- Construct one stratum per unique value in `group_column`.\n- Keep strata even when they are small; only strata with at least 11 samples run KNN.\n\n### Step 4: Run Imputation\n- Run group-stratified KNN imputation only within strata that contain at least 11 samples.\n- Within each stratum, skip imputation for any gene whose missing-value fraction in that stratum is at least 50%; leave those values as `NA`.\n- For strata with 10 or fewer samples, fill missing values by the row-wise mean or median within that stratum.\n- If a small stratum has an all-missing gene row that is still imputable, fall back to the global row-wise mean or median.\n\n### Step 5: Save Results\n- Write the imputed matrix.\n- Save `session_info.txt` to the output directory.\n\n---\n\n## Methods\n\n### Missingness Filter + Group-Stratified DMwR2 KNN\n\nGenes with at least 50% missing values are removed first. KNN imputation is then applied within user-defined strata built from one grouping column when the stratum contains at least 11 samples.\n\nIf the chosen grouping scheme splits the data into strata of 10 samples or fewer, the command falls back to row-wise direct filling by mean or median inside that stratum. Genes that reach at least 50% missingness within a stratum are skipped in that stratum and remain `NA`. If another small-stratum row is fully missing but still below that threshold, the script falls back to the corresponding global row summary.\n\nFor implementation details, assumptions, and skip behavior for small strata, read `references\/algorithm.md`.\n\n---\n\n## Examples\n\n### Basic Usage\n\n```bash\nRscript scripts\/main.R \\\n  -i tests\/data\/sample_expression_matrix.csv \\\n  -g tests\/data\/sample_groups.csv \\\n  -o tests\/output\/basic_run\n```\n\n### Smaller Neighborhood\n\n```bash\nRscript scripts\/main.R \\\n  -i tests\/data\/sample_expression_matrix.csv \\\n  -g tests\/data\/sample_groups.csv \\\n  -o tests\/output\/k5_run \\\n  -k 5\n```\n\n### Small Strata Fallback\n\n```bash\nRscript scripts\/main.R \\\n  -i tests\/data\/sample_expression_matrix.csv \\\n  -g tests\/data\/sample_groups.csv \\\n  -o tests\/output\/small_strata_run \\\n  -l sample \\\n  -m median \\\n  --overwrite\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 the file path |\n| `SKILL_EMPTY_FILE` | Input file exists but is empty | Replace it with a valid non-empty CSV file |\n| `SKILL_OUTPUT_EXISTS` | Output files already exist | Re-run with `--overwrite` or change `--output_dir` |\n| `SKILL_SAMPLE_MISMATCH` | Sample names do not match between files | Verify exact sample name matching |\n| `SKILL_MISSING_COLUMNS` | Requested grouping column is absent | Add that column to the group file or change `--group_column` |\n| `SKILL_INVALID_PARAMETER` | Multiple grouping columns were supplied | Pass exactly one grouping column in `--group_column` |\n| `SKILL_INVALID_DATA` | Matrix or group file structure is invalid | Check input format, duplicated IDs, and group completeness |\n| `SKILL_DEPENDENCY_MISSING` | DMwR2 not installed | Install with: `Rscript -e \"install.packages('remotes'); remotes::install_github('cran\/DMwR2')\"` \u2014 note: DMwR2 is not on CRAN |\n| `SKILL_TIMEOUT` | Timeout limit was exceeded | Increase `--timeout_seconds` or reduce data size |\n\n**IF error persists**, READ: `references\/troubleshooting.md`\n\n---\n\n## Local Validation\n\n### Validate the CLI Entrypoint\n\n```bash\n# Check help\nRscript scripts\/main.R --help\n\n# Run with sample data\nRscript scripts\/main.R \\\n  -i tests\/data\/sample_expression_matrix.csv \\\n  -g tests\/data\/sample_groups.csv \\\n  -o tests\/output\/basic_run \\\n  --overwrite\n\n# Run forced small-strata fallback\nRscript scripts\/main.R \\\n  -i tests\/data\/sample_expression_matrix.csv \\\n  -g tests\/data\/sample_groups.csv \\\n  -o tests\/output\/small_strata_run \\\n  -l sample \\\n  -m median \\\n  --overwrite\n```\n\n### Output Checks\n\n```bash\n# Count lines in output\nwc -l tests\/output\/basic_run\/imputed_expression_matrix.csv\n\n# Check output files exist\nls -la tests\/output\/basic_run\n```\n\n## Reference Files\n\n| File | Purpose |\n|---|---|\n| `references\/algorithm.md` | Group-stratified KNN method, fallback rules, and assumptions |\n| `references\/troubleshooting.md` | Common errors and solutions |\n| `references\/cli-guide.md` | CLI usage examples |\n","use_cases":["Impute missing values in a bulk expression matrix after filtering out genes with more than 50% missing values.","Perform group-aware KNN imputation with donor samples restricted by a single grouping column."],"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\/knn-imputation\/SKILL.md","source_commit":"686e09dfdb45d9fa1a08664f06bb93769b3c9d91","license":"MIT","version":null,"listing_approved_at":"2026-11-24","created_at":"2026-11-23T07:18:14.000000Z","updated_at":"2026-11-24T07:13:04.000000Z","seo_title":"KNN Imputation for Bulk Expression Matrices","seo_description":"Impute missing values in bulk expression matrices using group-aware KNN with DMwR2. Use when filtering genes with high missingness and imputing values with donor samples.","seo_keywords":["KNN imputation for bulk expression matrices","Group-aware KNN imputation","DMwR2 imputation for gene expression","Bulk expression matrix imputation","Missing value imputation in gene expression data"]}}