{"data":{"slug":"github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-umap-tsne-analysis-f5bf6154fec3","title":"UMAP and t-SNE Dimensionality Reduction for Group Analysis","summary":"Generate UMAP and t-SNE visualizations from OTU matrices with group files to assess sample separation and group clustering in microbiome studies. Requires at least two groups with two samples each and compatible input formats.","url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-umap-tsne-analysis-f5bf6154fec3","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-umap-tsne-analysis-f5bf6154fec3","markdown_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-umap-tsne-analysis-f5bf6154fec3.md","download_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-umap-tsne-analysis-f5bf6154fec3\/download","category":{"slug":"data-research","name":"Data & Research"},"editor_note":"Install required R packages first using `Rscript scripts\/install_dependencies.R`. Ensure the group file contains valid sample IDs matching the OTU matrix columns. The skill cannot run without these prerequisites.","instructions":"---\nname: umap-tsne-analysis\ndescription: \"Use when performing sample-level dimensionality reduction and visualization on abundance or OTU-style matrices with a companion group file, generating UMAP and\/or t-SNE coordinates and plots for group separation assessment. NOT for: differential expression testing, single-cell workflows requiring dedicated embeddings pipelines, or analyses without a sample grouping file.\"\nlicense: MIT\nskill-author: AIPOCH\n---\n\n# UMAP and t-SNE Analysis\n\n## Prerequisites\n\nRun the following before the first analysis to install all required R packages:\n\n```bash\nRscript scripts\/install_dependencies.R\n```\n\nAlternative manual installation:\n\n```bash\nRscript -e \"install.packages(c('optparse','data.table','Rtsne','umap','ggplot2','vegan','R.utils'), repos='https:\/\/cloud.r-project.org')\"\n```\n\n> Note: `R.utils` is only required when `--timeout > 0`, but pre-installing it avoids environment drift across runs. `testthat` is installed by `scripts\/install_dependencies.R` as the development test dependency.\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` | Dimensionality reduction methods, assumptions, parameter interpretation |\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 test data** | `tests\/data\/` | Sample input files for testing |\n\n---\n\n## Usage\n\n```bash\nRscript scripts\/main.R \\\n  --input_file .\/otu_table.csv \\\n  --group_file .\/group_info.csv \\\n  --output_dir .\/output\/ \\\n  --method both \\\n  --seed 42\n```\n\n---\n\n## Arguments\n\n| Short | Long | Type | Default | Description |\n|-------|------|------|---------|-------------|\n| `-i` | `--input_file` | character | **required** | Abundance \/ OTU matrix file |\n| `-g` | `--group_file` | character | **required** | Group information file |\n| `-o` | `--output_dir` | character | `.\/output\/` | Output directory |\n| `-m` | `--method` | character | `both` | Method: `tsne`, `umap`, or `both` |\n|  | `--sample_id_col` | character | first column | Sample ID column in group file |\n|  | `--group_col` | character | second column | Group column in group file |\n|  | `--perplexity` | numeric | `25` | t-SNE perplexity |\n|  | `--theta` | numeric | `0.0` | t-SNE theta |\n|  | `--pca` | logical | `FALSE` | Whether to use PCA before t-SNE |\n|  | `--check_duplicates` | logical | `FALSE` | Whether t-SNE should check duplicated rows |\n|  | `--normalize` | logical | `TRUE` | Whether to normalize data before UMAP |\n|  | `--norm_method` | character | `hellinger` | Normalization method for `vegan::decostand()` |\n|  | `--n_neighbors` | integer | `10` | UMAP neighborhood size |\n| `-s` | `--seed` | integer | `42` | Random seed for reproducibility |\n| `-t` | `--timeout` | integer | `0` | Timeout in seconds; `0` disables timeout |\n\n---\n\n## Dependency Baseline\n\nThe skill was validated with the exact package baseline recorded in `dependencies.lock.tsv`.\n\n| Package | Tested Version |\n|---------|----------------|\n| `optparse` | `1.7.5` |\n| `data.table` | `1.15.4` |\n| `Rtsne` | `0.17` |\n| `umap` | `0.2.10.0` |\n| `ggplot2` | `3.4.0` |\n| `vegan` | `2.7.3` |\n| `R.utils` | `2.13.0` |\n| `testthat` | `3.1.2` |\n\nUse this file as the reproducibility baseline when validating a new environment.\n\n---\n\n## Input Format\n\n### Abundance \/ OTU Matrix (`input_file`)\n\nFeatures as rows, samples as columns, CSV\/TSV-like tabular file with feature ID in the first column.\n\n```csv\nOTU_ID,S1,S2,S3,S4\nOTU_1,10,3,0,5\nOTU_2,2,8,1,0\nOTU_3,0,0,6,9\n```\n\n### Group File (`group_file`)\n\nTabular file with at least two columns: sample ID and group label.\n\n```csv\nSampleID,Group\nS1,Control\nS2,Control\nS3,Treatment\nS4,Treatment\n```\n\nRequirements:\n\n- At least 2 groups with at least 2 samples per group are required.\n- All sample IDs in the group file must exist in the matrix columns.\n- Single-group inputs will produce a `SKILL_INVALID_PARAMETER` error because dimensionality reduction without group contrast produces uninterpretable plots.\n\n---\n\n## Output Files\n\n| File | Description |\n|------|-------------|\n| `table\/tsne_coordinates.csv` | t-SNE coordinates with sample and group annotations |\n| `table\/umap_coordinates.csv` | UMAP coordinates with sample and group annotations |\n| `plot\/tsne_plot.pdf` | t-SNE scatter plot with group colors and ellipses |\n| `plot\/umap_plot.pdf` | UMAP scatter plot with group colors and ellipses |\n| `data\/session_info.txt` | R session and package version info |\n| `data\/analysis_data.rda` | Saved analysis object with aligned matrix, metadata, colors, and runtime parameters |\n\n---\n\n## Workflow\n\n### Step 1: Validate Input\n- Check that matrix file and group file exist\n- Resolve sample ID and group columns\n- Validate at least 2 groups and at least 2 samples per group\n- Ensure all group-file sample IDs exist in the matrix\n- Remove samples with zero total abundance after alignment if needed\n\n### Step 2: Prepare Matrix\n- Convert input table into numeric matrix\n- Align matrix columns to sample order from the group file\n- Transpose matrix so rows become samples and columns become features\n\n### Step 3: Run Dimensionality Reduction\n- Run t-SNE if `--method tsne` or `--method both`\n- Run UMAP if `--method umap` or `--method both`\n- Apply fixed random seed for reproducibility\n\n### Step 4: Generate Visualizations\n- Plot sample embeddings\n- Color points by group\n- Draw group ellipses when enabled\n- Save PDF outputs\n\n---\n\n## Methods\n\n### t-SNE\nt-SNE is a non-linear dimensionality reduction method that preserves local neighborhood structure. It is useful for identifying local sample clustering patterns.\n\n### UMAP\nUMAP is a manifold learning method that aims to preserve both local and some global structure. It is often faster than t-SNE and can produce stable low-dimensional embeddings when parameters are chosen appropriately.\n\n### Normalization\nWhen `--normalize TRUE`, the script uses `vegan::decostand()` with the selected `--norm_method` before UMAP. This is helpful for abundance-style ecological matrices.\n\n---\n\n## Agent Response Contract\n\nAfter a successful run, report:\n\n1. **Method(s) run** (tsne, umap, or both)\n2. **Sample count** and **group count** processed\n3. **Key parameters** used (perplexity for t-SNE, n_neighbors for UMAP)\n4. **Group separation quality** (describe visible clustering from coordinate ranges if accessible)\n5. **Artifact paths**: coordinate CSV(s) and plot PDF(s) produced\n\n---\n\n## Examples\n\n### Basic Usage\n```bash\nRscript scripts\/main.R \\\n  -i otu_table.csv \\\n  -g group_info.csv \\\n  -o .\/output \\\n  -m both\n```\n\n### Only t-SNE\n```bash\nRscript scripts\/main.R \\\n  -i otu_table.csv \\\n  -g group_info.csv \\\n  -o .\/output \\\n  -m tsne \\\n  --perplexity 10\n```\n\n### Only UMAP with Custom Group Column\n```bash\nRscript scripts\/main.R \\\n  -i otu_table.csv \\\n  -g metadata.csv \\\n  -o .\/output \\\n  -m umap \\\n  --sample_id_col SampleID \\\n  --group_col Treatment \\\n  --n_neighbors 15\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_MISSING_COLUMNS` | Group or matrix file lacks required columns | Verify file format |\n| `SKILL_SAMPLE_MISMATCH` | Sample IDs in group file do not match matrix columns | Check sample naming consistency |\n| `SKILL_EMPTY_DATA` | Matrix becomes empty after preprocessing | Check input values and filtering |\n| `SKILL_INVALID_PARAMETER` | Invalid method, invalid parameter value, or single-group input | Adjust CLI arguments; ensure at least 2 groups are present |\n| `SKILL_PACKAGE_NOT_FOUND` | Required R package is missing | Run `Rscript scripts\/install_dependencies.R`; note that file errors will only surface after packages are installed |\n| `SKILL_TIMEOUT` | Analysis exceeded the configured timeout | Increase `--timeout` or set `--timeout 0` |\n\n**IF error persists**, READ: `references\/troubleshooting.md`\n\n**Troubleshooting note:** In environments where packages are not yet installed, `SKILL_PACKAGE_NOT_FOUND` will fire before file-validation errors. Install dependencies first, then re-run to expose any file-related errors.\n\n---\n\n## Input Validation\n\nThis skill accepts:\n1. An abundance or OTU-style feature matrix (CSV\/TSV, features as rows, samples as columns)\n2. A group file with at least two groups (CSV\/TSV, sample IDs and group labels)\n\nIf the user's request does not involve UMAP or t-SNE dimensionality reduction for group separation visualization \u2014 for example, asking to run differential expression testing, process single-cell RNA-seq with specialized pipelines, perform clustering without a group file, or impute missing values \u2014 do not proceed with the workflow. Instead respond:\n\n> \"UMAP and t-SNE Analysis is designed to perform sample-level dimensionality reduction and visualization on abundance or OTU-style matrices. Your request appears to be outside this scope. Please provide a feature matrix and group file for UMAP\/t-SNE, or use a more appropriate tool for differential expression testing, single-cell analysis, or clustering.\"\n\n---\n\n## Testing\n\n### Test with Sample Data\n\n```bash\nRscript scripts\/install_dependencies.R\n\nRscript scripts\/main.R --help\n\nRscript scripts\/main.R \\\n  -i tests\/data\/otu_table.csv \\\n  -g tests\/data\/group_info.csv \\\n  -o tests\/output\/ \\\n  -m both\n\nRscript tests\/test_skill.R\n\nRscript tests\/run_smoke_test.R\n```\n\n### Validation Commands\n\n```bash\nls -la tests\/output\/\nls -la tests\/output\/table\nls -la tests\/output\/plot\nls -la tests\/output\/data\nwc -l tests\/output\/table\/tsne_coordinates.csv\nwc -l tests\/output\/table\/umap_coordinates.csv\n```\n\nThe canonical sample data live in `tests\/data\/`. Use those files for examples, smoke tests, and regression checks. The canonical output layout is `output_dir\/table`, `output_dir\/plot`, and `output_dir\/data`.\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] Dependency bootstrap script\n- [x] Session info recording\n- [x] File reading instructions in SKILL.md\n- [x] Modular script structure\n- [x] Error handling with SKILL_* codes\n- [x] Test data provided in `tests\/data\/`\n- [x] Version-pinned dependency baseline in `dependencies.lock.tsv`\n- [x] Automated `testthat` coverage for validation and plotting edge cases\n- [x] Scripts in `scripts\/` directory\n- [x] References in `references\/` directory\n\n---\n\n*Last updated: 2026-04-27 | Version: 1.1.0*\n","use_cases":["Visualize sample separation in OTU matrices using UMAP and t-SNE","Assess group clustering in microbiome studies","Generate plots for publication-ready group comparison"],"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\/umap-tsne-analysis\/SKILL.md","source_commit":"686e09dfdb45d9fa1a08664f06bb93769b3c9d91","license":"MIT","version":null,"listing_approved_at":"2026-11-24","created_at":"2026-11-23T07:38:00.000000Z","updated_at":"2026-11-24T07:13:22.000000Z","seo_title":"UMAP t-SNE Analysis for Grouped OTU Data","seo_description":"Perform UMAP and t-SNE analysis on OTU matrices with group files for visualization and group separation assessment.","seo_keywords":["UMAP analysis","t-SNE visualization","OTU matrix grouping","microbiome data analysis","sample clustering"]}}