{"data":{"slug":"github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-hierarchical-clustering-plot-8ef0d747f7e7","title":"Generate Hierarchical Clustering Dendrogram for Sample QC","summary":"Create a sample-level hierarchical clustering dendrogram from a bulk expression matrix and sample annotation table for QC, batch inspection, or sample similarity assessment. The output includes a dendrogram visualizing sample groupings based on expression data.","url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-hierarchical-clustering-plot-8ef0d747f7e7","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-hierarchical-clustering-plot-8ef0d747f7e7","markdown_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-hierarchical-clustering-plot-8ef0d747f7e7.md","download_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-hierarchical-clustering-plot-8ef0d747f7e7\/download","category":{"slug":"data-research","name":"Data & Research"},"editor_note":"Ensure the expression matrix contains unique feature IDs in the first column and numeric sample columns. The sample annotation file must include matching sample IDs and at least one metadata column. Select a label column with non-empty values for dendrogram leaf labels.","instructions":"---\nname: hierarchical-clustering-plot\ndescription: \"Use when building a sample-level hierarchical clustering dendrogram from a bulk expression matrix and sample annotation table, especially for QC, batch inspection, or sample similarity assessment. Trigger keywords: hierarchical clustering, dendrogram, sample QC, batch inspection, sample similarity. NOT for: differential expression testing, gene clustering heatmaps, single-cell clustering workflows.\"\n---\n\n# Hierarchical Clustering Plot\n\n## When to Use\n\nUse this skill when you need a sample-level hierarchical clustering dendrogram from a bulk expression matrix and a sample annotation table.\n\n- Good fits: sample QC, batch inspection, sample similarity assessment, checking whether annotated sample groups cluster as expected.\n- Trigger keywords: hierarchical clustering, dendrogram, sample QC, batch inspection, sample similarity.\n- Not for: differential expression testing, gene clustering heatmaps, single-cell clustering workflows.\n\n## When to Read External Files\n\n| Situation | File to Read | Purpose |\n|-----------|--------------|---------|\n| **Need algorithm details** | `references\/algorithm.md` | Distance calculation, linkage rules, and clustering assumptions |\n| **Need to run analysis or inspect CLI entrypoint behavior** | `scripts\/main.R` | Execute the workflow and inspect argument parsing, defaults, required flags, and sourced modules |\n| **Need workflow implementation details** | `scripts\/run_analysis.R` | See orchestration order, temp workspace handling, and output generation |\n| **Need logging or warning behavior** | `scripts\/logging_utils.R` | See standardized console log formatting and memory usage messages |\n| **Need file or parameter validation details** | `scripts\/validation_utils.R` | See path checks, output-directory checks, and scalar validation |\n| **Need timeout, temp workspace, or session info behavior** | `scripts\/runtime_utils.R` | See timeout control, temp cleanup, output copying, and session-info export |\n| **Need expression\/group input handling** | `scripts\/input_functions.R` | See CSV loading, sample matching, and label extraction |\n| **Need clustering logic** | `scripts\/clustering_functions.R` | See distance calculation and `hclust()` generation |\n| **Need output-writing logic** | `scripts\/output_utils.R` | See CSV export and PDF rendering |\n| **Encounter errors, warnings, or unexpected clustering patterns** | `references\/troubleshooting.md` | Common failures, warning follow-up, and interpretation guidance |\n| **Need CLI examples or common parameter combinations** | `references\/cli-guide.md` | Detailed command patterns for standard, variant, and test runs |\n| **Need example input files or schema-concrete fixtures** | `tests\/data\/` | Inspect sample CSV layouts for expression and group inputs |\n| **Need expected output names or artifact formats** | `## Output Files` and `references\/cli-guide.md` | Confirm the files the workflow writes and inspect documented example previews |\n| **Need to run regression tests** | `tests\/run_tests.R` | Execute the automated test suite |\n| **Need exact test assertions or edge cases** | `tests\/testthat\/test-clustering.R` | Inspect validation, reproducibility, and output checks |\n\n---\n\n## Usage\n\n```bash\nRscript scripts\/main.R \\\n  --input_file .\/expression_matrix.csv \\\n  --group_file .\/sample_groups.csv \\\n  --output_dir .\/output\/ \\\n  --distance_method euclidean \\\n  --linkage_method complete \\\n  --label_column batch \\\n  --timeout_seconds 300 \\\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 (features as rows, samples as columns) |\n| `-g` | `--group_file` | character | **required** | Sample annotation file (first column sample ID, one metadata column for labels) |\n| `-o` | `--output_dir` | character | `.\/output\/` | Output directory |\n| `-d` | `--distance_method` | character | `euclidean` | Distance metric for `dist()`: euclidean, maximum, manhattan, canberra, binary, minkowski |\n| `-m` | `--linkage_method` | character | `complete` | Linkage method for `hclust()`: complete, single, average, mcquitty, median, centroid, ward.D, ward.D2 |\n| `-l` | `--label_column` | character | second column | Column used as dendrogram labels |\n| `-c` | `--label_cex` | numeric | `0.8` | Dendrogram label size, must be `> 0` |\n| `-t` | `--timeout_seconds` | integer | `300` | Elapsed time limit in seconds, must be `> 0` |\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 IDs in the first column.\n\n```csv\n,Sample01,Sample02,Sample03\nTSPAN6,1.847876677,1.831755661,3.827625975\nTNMD,0.034919984,0.053250385,1.388850793\n```\n\n**Requirements:**\n- The first column contains unique feature IDs.\n- All sample columns must be numeric.\n- Sample column names must be unique and non-empty.\n- At least two matched samples are required.\n\n### Sample Annotation (`group_file`)\n\nCSV with sample IDs in the first column. The second column is used by default for leaf labels unless `--label_column` is provided.\n\n```csv\nsample,batch\nSample01,batch1\nSample02,batch2\nSample03,batch1\n```\n\n**Requirements:**\n- Sample IDs must match expression matrix column names exactly.\n- The selected label column must exist and contain no empty values.\n- The file must contain at least one metadata column in addition to sample IDs.\n\n---\n\n## Output Files\n\n| File | Description |\n|------|-------------|\n| `hierarchical_clustering_plot.pdf` | Sample dendrogram plot |\n| `sample_distance_matrix.csv` | Pairwise sample distance matrix |\n| `clustering_order.csv` | Leaf order shown in the dendrogram |\n| `matched_samples.csv` | Sample-to-label table used for plotting |\n| `session_info.txt` | R session and package version info |\n\n## Workflow\n\n### Step 1: Validate Input\n**WHEN checking file or parameter validation**, READ: `scripts\/validation_utils.R`\n\n**WHEN checking expression\/group CSV handling**, READ: `scripts\/input_functions.R`\n\n- Check file existence\n- Reject empty files before parsing\n- Read the expression matrix and sample annotation CSV files\n- Validate required columns, unique IDs, and numeric expression values\n\n### Step 2: Align Samples\n**WHEN checking sample matching logic**, READ: `scripts\/input_functions.R`\n\n- Match sample IDs between the annotation file and expression matrix\n- Reorder matrix columns to the annotation file order\n- Select the label column used for plotting\n\n### Step 3: Build Hierarchical Clustering\n**WHEN interpreting distance or linkage behavior**, READ: `references\/algorithm.md`\n\n**WHEN checking clustering implementation**, READ: `scripts\/clustering_functions.R`\n\n- Transpose the expression matrix to sample-by-feature form\n- Compute pairwise sample distances with `dist()`\n- Build the dendrogram with `hclust()`\n\n### Step 4: Save Outputs\n**WHEN checking output staging and cleanup behavior**, READ: `scripts\/run_analysis.R`\n\n**WHEN checking PDF\/CSV export behavior**, READ: `scripts\/output_utils.R`\n\n**WHEN checking timeout, session info, or final file copy behavior**, READ: `scripts\/runtime_utils.R`\n\n- Stage outputs in a temporary workspace\n- Export the pairwise distance matrix\n- Export the plotted leaf order\n- Render the dendrogram as PDF\n- Copy finalized outputs into the requested output directory\n\n---\n\n## Methods\n\n### Distance Matrix\nSample distances are computed from the transposed expression matrix using base R `dist()`.\n\n### Hierarchical Clustering\nThe clustering tree is built with base R `hclust()`. The default linkage method is `complete`, matching the source analysis script.\n\n---\n\n## Examples\n\n### Basic Usage\n```bash\nRscript scripts\/main.R \\\n  -i tests\/data\/sample_expression_matrix.csv \\\n  -g tests\/data\/sample_groups.csv \\\n  -o .\/output\/ \\\n  -t 300\n```\n\n### Use Sample IDs as Labels\n```bash\nRscript scripts\/main.R \\\n  -i tests\/data\/sample_expression_matrix.csv \\\n  -g tests\/data\/sample_groups.csv \\\n  -o .\/output_sample_labels\/ \\\n  -l sample\n```\n\n### Use Average Linkage\n```bash\nRscript scripts\/main.R \\\n  -i tests\/data\/sample_expression_matrix.csv \\\n  -g tests\/data\/sample_groups.csv \\\n  -o .\/output_average\/ \\\n  -m average\n```\n\n---\n\n## Error Handling\n\n### Common Errors\n\n| Error | Cause | Solution | Read More |\n|-------|-------|----------|-----------|\n| `SKILL_DEPENDENCY_MISSING` | Required R package is not installed | Install the missing package and rerun | `references\/troubleshooting.md#skill_dependency_missing` |\n| `SKILL_FILE_NOT_FOUND` | Input file does not exist or output directory could not be created | Check the path and permissions | `references\/troubleshooting.md#skill_file_not_found` |\n| `SKILL_EMPTY_FILE` | Input file is empty | Re-export the CSV and confirm it contains data | `references\/troubleshooting.md#skill_empty_file` |\n| `SKILL_EMPTY_DATA` | CSV parsed successfully but contains no data rows | Confirm the CSV has at least one data row | `references\/troubleshooting.md#skill_empty_data` |\n| `SKILL_PARSE_ERROR` | CSV parsing failed | Check encoding, delimiters, and CSV structure | `references\/troubleshooting.md#skill_parse_error` |\n| `SKILL_MISSING_COLUMNS` | Expected columns or headers are missing | Check CSV headers and metadata columns | `references\/troubleshooting.md#skill_missing_columns` |\n| `SKILL_INVALID_TYPE` | Expression values or parameters have the wrong type | Ensure numeric fields are numeric | `references\/troubleshooting.md#skill_invalid_type` |\n| `SKILL_SAMPLE_MISMATCH` | Sample IDs do not match | Ensure the first column in `group_file` matches matrix column names | `references\/troubleshooting.md#skill_sample_mismatch` |\n| `SKILL_INVALID_DATA` | Expression or annotation data is malformed | Check duplicate IDs, missing labels, and numeric values | `references\/troubleshooting.md#skill_invalid_data` |\n| `SKILL_INVALID_PARAMETER` | Unsupported distance, linkage, or label parameter | Use one of the documented parameter values | `references\/troubleshooting.md#skill_invalid_parameter` |\n| `SKILL_TIMEOUT` | Analysis exceeded the time limit | Increase `--timeout_seconds` and rerun | `references\/troubleshooting.md#skill_timeout` |\n| `SKILL_PLOT_ERROR` | Plot device failed while writing PDF | Check output directory permissions and rerun | `references\/troubleshooting.md#skill_plot_error` |\n| `SKILL_WRITE_ERROR` | Output or intermediate files could not be written | Check output directory permissions and free disk space | `references\/troubleshooting.md#skill_write_error` |\n| `SKILL_WARNING` | Non-fatal warning occurred during execution | Inspect console warnings and verify output quality | `references\/troubleshooting.md#skill_warning` |\n| `SKILL_MEMORY_WARNING` | Memory usage exceeded the warning threshold | Reduce input size or rerun with more memory | `references\/troubleshooting.md#skill_memory_warning` |\n\n**IF error persists**, READ: `references\/troubleshooting.md`\n\n---\n\n## Testing\n\n### Test with Sample Data\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 .\/output\/\n\n# Run unit tests (requires testthat and data.table)\nRscript tests\/run_tests.R\n```\n\n### Validation Commands\n\n```bash\n# Check main output plot exists\nls -la .\/output\/hierarchical_clustering_plot.pdf\n\n# Inspect clustering order\nwc -l .\/output\/clustering_order.csv\n```\n\n## Implementation Checklist\n\n- [x] CLI parsing with `optparse`\n- [x] `set.seed()` for reproducibility\n- [x] Input validation (file existence, emptiness, types, required columns)\n- [x] Try-catch based fatal error handling\n- [x] Standardized `SKILL_*` error classification\n- [x] Timeout control with `setTimeLimit()`\n- [x] Standardized console-only logging\n- [x] Base R clustering implementation\n- [x] Session info recording with `sink()`\n- [x] Temporary workspace cleanup with `on.exit()`\n- [x] Memory usage reporting with `gc()`\n- [x] File reading instructions in SKILL.md\n- [x] Modular script structure across `scripts\/`\n- [x] Test template added under `tests\/testthat\/`\n- [x] Test data provided\n- [x] Error handling with `SKILL_*` codes\n- [x] `get_script_dir()` defined before use\n- [x] Scripts in `scripts\/` directory\n- [x] References in `references\/` directory\n\n---\n\n*Last updated: 2026-04-16 | Version: 1.0.0*\n","use_cases":["Assess sample similarity across batches","Perform quality control on bulk expression data","Inspect clustering of annotated sample groups"],"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\/hierarchical-clustering-plot\/SKILL.md","source_commit":"686e09dfdb45d9fa1a08664f06bb93769b3c9d91","license":null,"version":null,"listing_approved_at":"2026-11-24","created_at":"2026-11-23T07:14:14.000000Z","updated_at":"2026-11-24T07:13:04.000000Z","seo_title":"Generate Hierarchical Clustering Dendrogram for Sample QC","seo_description":"Create a dendrogram for sample QC, batch inspection, and similarity assessment using expression matrix and sample annotation data.","seo_keywords":["hierarchical clustering dendrogram","sample QC analysis","batch inspection clustering","sample similarity assessment","expression matrix clustering"]}}