{"data":{"slug":"github-aipoch-medical-research-skills-scientific-skills-data-analysis-bio-causal-genomics-mediation-analysis-cd5864cbe082","title":"Genetic Mediation Analysis for Molecular Phenotypes","summary":"Decompose genetic effects into direct and indirect paths through molecular phenotypes such as gene expression or methylation using the mediation R package. Receive estimates of ACME, ADE, and proportion mediated with bootstrap confidence intervals.","url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-bio-causal-genomics-mediation-analysis-cd5864cbe082","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-bio-causal-genomics-mediation-analysis-cd5864cbe082","markdown_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-bio-causal-genomics-mediation-analysis-cd5864cbe082.md","download_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-bio-causal-genomics-mediation-analysis-cd5864cbe082\/download","category":{"slug":"data-research","name":"Data & Research"},"editor_note":"Before running mediation analysis, ensure that the required R packages (e.g., mediation, HIMA) are installed and that the data includes the necessary variables (genotype, mediator, outcome, and covariates). The user must specify the treatment, mediator, and outcome variables explicitly in the model formulas.","instructions":"---\nname: bio-causal-genomics-mediation-analysis\ndescription: Decompose genetic effects into direct and indirect paths through mediating variables using the mediation R package. Tests whether gene expression, methylation, or other molecular phenotypes mediate the effect of genetic variants on disease. Use when testing whether a molecular...\nlicense: MIT\nauthor: AIPOCH\n---\n> **Source**: [https:\/\/github.com\/aipoch\/medical-research-skills](https:\/\/github.com\/aipoch\/medical-research-skills)\n\n\n## Version Compatibility\n\nReference examples tested with: R stats (base), ggplot2 3.5+\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- R: `packageVersion('<pkg>')` then `?function_name` to verify parameters\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\n# Mediation Analysis\n\n**\"Test whether gene expression mediates the effect of this variant on disease\"** \u2192 Decompose the total genetic effect into direct and indirect (mediated) paths through a molecular phenotype, estimating ACME, ADE, and proportion mediated with bootstrap confidence intervals.\n- R: `mediation::mediate()` for causal mediation analysis\n\n## Framework\n\nCausal mediation decomposes the total effect of a treatment (genotype) on an outcome\n(phenotype) into:\n\n- **ACME** (Average Causal Mediation Effect) - Indirect effect through the mediator\n- **ADE** (Average Direct Effect) - Direct effect not through the mediator\n- **Total effect** = ACME + ADE\n- **Proportion mediated** = ACME \/ Total effect\n\nTypical genomic applications:\n- SNP -> gene expression (mediator) -> disease\n- SNP -> DNA methylation (mediator) -> gene expression\n- SNP -> protein levels (mediator) -> clinical outcome\n\n## Basic Mediation with the mediation Package\n\n**Goal:** Decompose a genetic effect into direct and indirect (mediated) paths through a molecular phenotype.\n\n**Approach:** Fit separate models for mediator and outcome, then run mediate() with bootstrap to estimate ACME (indirect), ADE (direct), and proportion mediated.\n\n```r\nlibrary(mediation)\n\n# --- Step 1: Fit mediator model ---\n# How does the treatment (genotype) affect the mediator (expression)?\nmediator_model <- lm(expression ~ genotype + age + sex + pc1 + pc2, data = dat)\n\n# --- Step 2: Fit outcome model ---\n# How do treatment and mediator jointly affect the outcome?\n# For binary outcome, use glm with family = binomial\noutcome_model <- glm(\n  disease ~ genotype + expression + age + sex + pc1 + pc2,\n  data = dat, family = binomial\n)\n\n# --- Step 3: Run mediation analysis ---\n# treat: name of treatment variable (genotype)\n# mediator: name of mediator variable (expression)\n# boot = TRUE: Use nonparametric bootstrap for CIs\n# sims: Number of bootstrap simulations (1000 minimum for publication)\nmed_result <- mediate(\n  mediator_model, outcome_model,\n  treat = 'genotype', mediator = 'expression',\n  boot = TRUE, sims = 1000\n)\n\nsummary(med_result)\n# Key outputs:\n# ACME: Indirect effect (through expression)\n# ADE: Direct effect (not through expression)\n# Total Effect: ACME + ADE\n# Prop. Mediated: ACME \/ Total\n```\n\n## Interpreting Results\n\n```r\n# Extract key quantities\nacme <- med_result$d0           # Indirect (mediated) effect\nacme_ci <- med_result$d0.ci     # 95% CI for ACME\nade <- med_result$z0            # Direct effect\ntotal <- med_result$tau.coef    # Total effect\nprop_med <- med_result$n0       # Proportion mediated\n\ncat('ACME (indirect):', round(acme, 4), '\\n')\ncat('ACME 95% CI:', round(acme_ci[1], 4), 'to', round(acme_ci[2], 4), '\\n')\ncat('ADE (direct):', round(ade, 4), '\\n')\ncat('Total effect:', round(total, 4), '\\n')\ncat('Proportion mediated:', round(prop_med, 3), '\\n')\n\n# Significant ACME (CI excludes 0): Evidence for mediation\n# Proportion mediated > 0.2: Meaningful mediation\n# Proportion mediated > 0.8: Mediator explains most of the effect\n```\n\n## eQTL Mediation\n\n**Goal:** Test whether gene expression mediates the effect of an eQTL on a disease outcome across multiple genes.\n\n**Approach:** Wrap the mediation workflow in a function, loop over candidate genes, and adjust p-values for multiple testing.\n\n```r\nlibrary(mediation)\n\nrun_eqtl_mediation <- function(dat, snp_col, expr_col, outcome_col, covariates) {\n  covar_formula <- paste(covariates, collapse = ' + ')\n\n  med_formula <- as.formula(paste(expr_col, '~', snp_col, '+', covar_formula))\n  out_formula <- as.formula(paste(outcome_col, '~', snp_col, '+', expr_col, '+', covar_formula))\n\n  med_model <- lm(med_formula, data = dat)\n\n  if (length(unique(dat[[outcome_col]])) == 2) {\n    out_model <- glm(out_formula, data = dat, family = binomial)\n  } else {\n    out_model <- lm(out_formula, data = dat)\n  }\n\n  result <- mediate(\n    med_model, out_model,\n    treat = snp_col, mediator = expr_col,\n    boot = TRUE, sims = 1000\n  )\n\n  data.frame(\n    snp = snp_col, gene = expr_col,\n    acme = result$d0, acme_p = result$d0.p,\n    ade = result$z0, ade_p = result$z0.p,\n    total = result$tau.coef, total_p = result$tau.p,\n    prop_mediated = result$n0\n  )\n}\n\n# Example: test mediation for multiple genes\ngenes <- c('GENE_A', 'GENE_B', 'GENE_C')\ncovars <- c('age', 'sex', 'pc1', 'pc2', 'pc3')\n\nmediation_results <- do.call(rbind, lapply(genes, function(g) {\n  run_eqtl_mediation(dat, 'rs12345', g, 'disease_status', covars)\n}))\n\n# Adjust for multiple testing\nmediation_results$acme_fdr <- p.adjust(mediation_results$acme_p, method = 'BH')\n```\n\n## Multi-Omics Mediation\n\n**Goal:** Test cascading mediation chains across multiple molecular layers (e.g., SNP -> methylation -> expression -> disease).\n\n**Approach:** Fit sequential models for each link in the chain and run separate mediation analyses for each mediator-outcome pair.\n\n```r\n# Test mediation chains: SNP -> methylation -> expression -> disease\nlibrary(mediation)\n\n# Step 1: SNP -> methylation\nmod_meth <- lm(methylation ~ genotype + age + sex, data = dat)\n\n# Step 2: methylation -> expression (controlling for genotype)\nmod_expr <- lm(expression ~ methylation + genotype + age + sex, data = dat)\n\n# Step 3: expression -> disease (controlling for methylation and genotype)\nmod_disease <- glm(\n  disease ~ expression + methylation + genotype + age + sex,\n  data = dat, family = binomial\n)\n\n# Test methylation as mediator of SNP -> expression\nmed_meth_expr <- mediate(mod_meth, mod_expr, treat = 'genotype', mediator = 'methylation',\n                         boot = TRUE, sims = 1000)\n\n# Test expression as mediator of methylation -> disease\nmed_expr_disease <- mediate(mod_expr, mod_disease, treat = 'methylation', mediator = 'expression',\n                            boot = TRUE, sims = 1000)\n```\n\n## High-Dimensional Mediation (HDMA)\n\n**Goal:** Test thousands of potential mediators simultaneously (e.g., all CpG sites) to identify which mediate a genetic effect.\n\n**Approach:** Use HIMA's penalized regression to jointly select significant mediators from a high-dimensional mediator matrix and estimate their indirect effects.\n\n```r\n# For testing many potential mediators simultaneously (e.g., all CpG sites)\n# install.packages('HIMA')\nlibrary(HIMA)\n\n# X: treatment (genotype), M: high-dimensional mediators, Y: outcome\n# HIMA uses penalized regression to select significant mediators\n\nresult <- hima(\n  X = dat$genotype,\n  Y = dat$disease,\n  M = as.matrix(dat[, mediator_cols]),\n  COV.XM = as.matrix(dat[, covariate_cols]),\n  Y.family = 'binomial',\n  M.family = 'gaussian',\n  penalty = 'MCP'    # Minimax concave penalty (default)\n)\n\n# Results: significant mediators with estimated indirect effects\nsignificant_mediators <- result[result$BH.FDR < 0.05, ]\n```\n\n## Assumptions and Diagnostics\n\n```r\n# --- Sequential ignorability assumption ---\n# 1. No unmeasured confounders between treatment and mediator\n# 2. No unmeasured confounders between mediator and outcome\n# 3. No unmeasured confounders between treatment and outcome\n# This assumption is UNTESTABLE but can be probed with sensitivity analysis\n\n# --- Sensitivity analysis ---\n# Tests how robust results are to unmeasured confounding\nsens <- medsens(med_result, rho.by = 0.1, effect.type = 'indirect', sims = 1000)\nsummary(sens)\n\n# rho: Correlation between residuals of mediator and outcome models\n# At what rho does ACME cross zero? (larger |rho| = more robust)\n# rho at which ACME = 0 is called the sensitivity parameter\n# |rho| > 0.3: Reasonably robust to unmeasured confounding\n\nplot(sens)\n```\n\n## Visualization\n\n```r\nlibrary(ggplot2)\n\nplot_mediation_diagram <- function(acme, ade, total, prop_med) {\n  cat('Mediation Path Diagram:\\n\\n')\n  cat('  Genotype ---[a]---> Mediator ---[b]---> Outcome\\n')\n  cat('      |                                     ^\\n')\n  cat('      +----------[c\\' (ADE)]----------------+\\n')\n  cat('\\n')\n  cat('  Indirect (a*b = ACME):', round(acme, 4), '\\n')\n  cat('  Direct (c\\' = ADE):', round(ade, 4), '\\n')\n  cat('  Total (c):', round(total, 4), '\\n')\n  cat('  Proportion mediated:', round(prop_med, 3), '\\n')\n}\n\nplot_mediation_results <- function(results_df) {\n  results_df$gene <- factor(results_df$gene, levels = results_df$gene[order(results_df$prop_mediated)])\n\n  ggplot(results_df, aes(x = gene, y = prop_mediated)) +\n    geom_col(fill = 'steelblue', alpha = 0.7) +\n    geom_hline(yintercept = 0.2, linetype = 'dashed', color = 'red', alpha = 0.5) +\n    coord_flip() +\n    labs(x = NULL, y = 'Proportion Mediated', title = 'Mediation by Gene Expression') +\n    theme_minimal()\n}\n```\n\n## Related Skills\n\n- mendelian-randomization - Causal inference using genetic instruments\n- colocalization-analysis - Test if signals share a causal variant\n- population-genetics\/association-testing - GWAS for treatment-outcome associations\n- multi-omics-integration\/mofa-integration - Multi-omics data for mediation chains\n\n## Input Validation\n\nThis skill accepts requests that match the documented purpose of `bio-causal-genomics-mediation-analysis` and include enough context to complete the workflow safely.\n\nDo not continue the workflow when the request is out of scope, missing a critical input, or would require unsupported assumptions. Instead respond:\n\n> `bio-causal-genomics-mediation-analysis` only handles its documented workflow. Please provide the missing required inputs or switch to a more suitable skill.\n","use_cases":["Test whether gene expression mediates the effect of a genetic variant on disease","Analyze if DNA methylation mediates the effect of a SNP on gene expression","Evaluate the role of protein levels as mediators in clinical outcomes"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/aipoch\/medical-research-skills\/blob\/686e09dfdb45d9fa1a08664f06bb93769b3c9d91\/scientific-skills\/Data%20Analysis\/bio-causal-genomics-mediation-analysis\/SKILL.md","source_commit":"686e09dfdb45d9fa1a08664f06bb93769b3c9d91","license":"MIT","version":null,"listing_approved_at":"2026-11-24","created_at":"2026-11-23T10:59:39.000000Z","updated_at":"2026-11-24T07:14:40.000000Z","seo_title":"Genetic Mediation Analysis for Molecular Phenotypes","seo_description":"Decompose genetic effects into direct and indirect paths through molecular phenotypes using mediation analysis in R.","seo_keywords":["genetic mediation analysis","causal mediation in R","gene expression mediation","SNP mediation analysis","mediation effect estimation"]}}