科研 Skill
因果推断方法设计
causal-inference
Runs DAG-based, instrumental-variable, difference-in-differences or RD analyses. Use when an association in observational data must support a causal claim.
SKILL.md
Causal Inference Skill
Observational clinical and public-health data cannot answer a causal question with adjusted
regression alone. This skill helps choose and execute the right causal-identification strategy —
directed acyclic graph (DAG)-based confounder selection, instrumental variables (IV),
difference-in-differences (DiD), regression discontinuity (RD), or target trial emulation — before
running the code, and audits an existing analysis's identification assumptions. It complements
design-study (which flags that a causal claim needs a design, generally) and analyze-stats
(which runs standard regression, propensity-score, and survival models) by owning the
identification-strategy layer in between: which variables to adjust for and why, and which
quasi-experimental method fits the available data-generating process.
When to use
- A research question asks "does X cause Y" from non-randomized data, and simple adjustment for "the usual covariates" is not defensible.
- A natural experiment, policy change, eligibility cutoff, or instrument is available and the team wants to exploit it instead of (or in addition to) regression adjustment.
- A finished manuscript's causal claim needs an identification-assumptions audit before submission or peer review.
- Planning a target trial emulation from routinely collected data (claims, EHR, registry).
When NOT to use
- Pure prediction / forecasting with no causal claim →
analyze-statsormodel-selection. - Standard propensity-score matching/weighting with no instrument or natural experiment available →
analyze-stats'sreferences/analysis_guides/propensity_score.mdalready covers this. - Pooling causal effect estimates across multiple published studies →
meta-analysis. - Sample size for a planned causal analysis →
calc-sample-size.
Prerequisites
- Python 3.10+ with
pandas,numpy,statsmodels,linearmodels(IV/panel estimators),scipy; R users may preferAER,ivreg,did,rdrobust,rddensity,dagitty/ggdag. - A clearly stated causal question in exposure → outcome form, with the hypothesized time-ordering (what happened first).
- Enough domain knowledge of the data-generating mechanism to draw a credible DAG — this skill elicits that knowledge from the user and literature; it does not infer causal structure from the data alone, because correlation-based structure learning cannot distinguish a confounder from a collider or a mediator without substantive assumptions.
Workflow
Phase 1 — Frame the causal question
State, explicitly:
- Exposure (the variable whose causal effect is of interest) and its hypothetical intervention ("what would changing this mean in practice?").
- Outcome, with its measurement window relative to the exposure.
- Target population and time zero (index date) — the same target-trial discipline
design-studyalready asks for. - Candidate identification strategy — ask the user which of these is plausible for their data,
or infer candidates from what is available:
- Rich covariate data + no natural experiment → DAG-based confounder adjustment (Phase 2).
- A variable that affects the outcome only through the exposure (an instrument) → IV (Phase 3).
- A policy, guideline, or eligibility change with a before/after and a comparison group → DiD (Phase 4).
- A continuous assignment variable with a hard cutoff (age, score, date) → RD (Phase 5).
- Routinely collected longitudinal data mimicking a hypothetical RCT → target trial emulation (Phase 6).
If no strategy fits (e.g., single cross-section, no instrument, no cutoff, no natural experiment), say so plainly: the data may only support an association claim, and the manuscript language should reflect that rather than overclaim causality.
Phase 2 — DAG-based confounder, mediator, and collider identification
- Elicit every variable the user believes is on a causal pathway between exposure and outcome, including ones measured only as covariates in the dataset.
- Draw the DAG as text-based edges (
exposure -> outcome,age -> exposure,age -> outcome, etc.) and render it, e.g. withdagitty(R) ornetworkx(Python) for a quick visual. - Apply the backdoor criterion: the adjustment set must block every backdoor (confounding) path
from exposure to outcome while not including:
- Mediators (on the causal pathway from exposure to outcome) — adjusting for these induces mediation bias and removes the very effect being estimated.
- Colliders (caused by both exposure and outcome, or by their causes) — adjusting for a collider, or for a variable downstream of one, induces collider-stratification (selection) bias even though the collider "looks like" a confounder in a naive covariate table.
- Variables measured after the exposure that are affected by it, unless the analysis is
explicitly a mediation analysis (route that to
analyze-stats's mediation guide).
- If the minimal sufficient adjustment set is not fully measured, say which confounder is missing and how that limits the conclusion — do not substitute a proxy without flagging it as a proxy.
- Output: the DAG diagram, the adjustment set with a one-line justification per variable, and the excluded mediators/colliders with the reason each was excluded.
Phase 3 — Instrumental variables (IV)
An instrument Z must satisfy three conditions — state the evidence for each, do not assume them:
- Relevance:
Zis associated with the exposure (testable — report the first-stage F statistic; F < 10 flags a weak instrument and unreliable IV estimates). - Exclusion restriction:
Zaffects the outcome only through the exposure (not testable from data alone — argue it from substantive knowledge, and report competing explanations). - Independence (no confounding of
Zand the outcome, e.g. from unmeasured common causes).
from linearmodels.iv import IV2SLS
# dependent, exog (controls), endog (exposure), instruments
model = IV2SLS.from_formula("outcome ~ 1 + age + sex + [exposure ~ instrument]", data=df)
result = model.fit(cov_type="robust")
print(result.summary)
print(result.first_stage) # check first-stage F for weak-instrument diagnostics
Report the first-stage F, the Sargan/Hansen over-identification test when more than one instrument is used, and the IV estimate alongside the naive OLS estimate so the reader sees how much the instrument changes the conclusion.
Phase 4 — Difference-in-differences (DiD)
For a policy or guideline change affecting one group (treated) and not another (control), with pre/post measurements on both:
import statsmodels.formula.api as smf
# post: 0/1 before/after the policy; treated: 0/1 treated group
model = smf.ols("outcome ~ treated * post + age + sex", data=panel_df).fit(
cov_type="cluster", cov_kwds={"groups": panel_df["cluster_id"]}
)
print(model.summary()) # the treated:post interaction is the DiD estimate
- Test and report the parallel-trends assumption using pre-policy periods (event-study plot of period-specific treatment effects, or a pre-trend interaction test) before trusting the point estimate — DiD without a parallel-trends check is not a credible causal estimate.
- Cluster standard errors at the level treatment varies (e.g., state, clinic, hospital), not at the individual level, or the confidence intervals will be too narrow.
- For more than two periods or staggered treatment timing, use a staggered-DiD estimator
(
didpackage in R: Callaway & Sant'Anna 2021) rather than naive two-way fixed effects, which is now known to be biased under staggered rollout with heterogeneous treatment effects.
Phase 5 — Regression discontinuity (RD)
For a hard cutoff on a continuous assignment variable (age-based eligibility, a risk score threshold for treatment, a policy effective date):
library(rdrobust)
rdrobust(y = df$outcome, x = df$running_variable, c = cutoff_value)
rdplot(y = df$outcome, x = df$running_variable, c = cutoff_value)
- Check for manipulation of the running variable near the cutoff with a density test
(
rddensity) — bunching just on the favorable side suggests gaming, which invalidates RD. - Report the bandwidth-sensitivity of the estimate (several bandwidths, not just the MSE-optimal one) and the local-linear vs local-quadratic specification.
- The RD estimate is a local average treatment effect at the cutoff — state this scope limitation explicitly; it does not generalize to patients far from the threshold.
Phase 6 — Target trial emulation
- Write the target trial protocol the observational data is emulating: eligibility criteria,
treatment strategies being compared, assignment procedure, follow-up start/end, outcome,
causal contrast (per-protocol vs intention-to-treat), and analysis plan — before touching the
data.
write-protocolcan host this document; this skill supplies the causal-design content. - Apply the clone-censor-weight approach (or equivalent) to avoid immortal-time bias: clone each eligible patient into both strategy arms at time zero, censor each clone when it deviates from its assigned strategy, and use inverse-probability-of-censoring weights to correct for the artificial censoring.
- Flag immortal-time bias explicitly whenever treatment status is assigned using information from after time zero (e.g., "treated" defined by a prescription filled during follow-up) — this is the single most common fatal flaw in emulated-trial designs.
Standard Output
## Causal Inference Design/Audit
Research question: exposure -> outcome, target population, time zero
Identification strategy: DAG adjustment | IV | DiD | RD | target trial emulation
### DAG / adjustment set (Phase 2, when used)
- Confounders adjusted for: ...
- Mediators / colliders excluded (and why): ...
- Unmeasured confounders / limitation: ...
### Identification-assumption checks
- [strategy-specific: first-stage F / parallel trends / density test / clone-censor-weight] : PASS/FAIL/NOT ASSESSED
### Effect estimate
- Naive (adjusted regression) estimate: ...
- Causal estimate (chosen strategy): ... [95% CI]
### Threats to validity
1. ...
### Minimal fixes
- ...
Quality checks
- Never report a causal point estimate without its identification-assumption diagnostics (first-stage F for IV; pre-trend plot for DiD; density test for RD; clone-censor-weight audit for target trial emulation) sitting next to it.
- Never adjust for a variable the DAG marks as a mediator or collider without flagging the bias this introduces.
- Every identification strategy's untestable assumption (exclusion restriction, parallel trends in the counterfactual world, continuity of potential outcomes at the cutoff, no unmeasured confounding) must be stated in words, not just asserted by running the code.
- Route the written-up Methods/Results text to
write-paper; route a pre-submission causal-claim audit toself-review'sobservational_confounding.mddomain probe.
Limitations
- This skill helps choose and execute an identification strategy; it cannot verify an untestable assumption (no unmeasured confounding, exclusion restriction, parallel trends) from data alone — these remain substantive, contestable claims that a reviewer may reasonably dispute.
- DAGs encode the user's or the literature's beliefs about causal structure; an incomplete or wrong DAG produces a wrong adjustment set with no warning from the software.
- Weak instruments, few pre-policy periods, or few observations near an RD cutoff all degrade estimate reliability even when the diagnostics nominally pass — report precision (confidence interval width), not just the point estimate.
- Not a replacement for an actual randomized trial when one is feasible; present causal estimates from observational data with the hedging a non-randomized design requires.
示例提示词
帮我用双重差分法评估这项医保政策对住院率的因果影响。
所属插件
安装该插件会一并获得同领域的 58 个 Skill / MCP。
同插件的其他科研 Skill
- 医学AI论文检索优化Optimizes a medical AI paper’s title, abstract and metadata for AI search engines. Use when a paper should be findable and citable by RAG tools and AI search.
- 临床数据统计分析与建模Generates reproducible Python or R code for clinical statistics and tables. Use when collected data needs Table 1, regression, survival or agreement analysis.
- 作者发表记录与策略分析Analyzes a PubMed author record to classify study types and authorship patterns. Use when planning a publication strategy from a researcher’s track record.
- 批量队列暴露结局分析Generates one cohort-analysis script per exposure-outcome pair from one template. Use when a validated method must run across many variable combinations at once.
- 样本量估算与检验效能Walks a decision tree to the right test and computes sample size with IRB text. Use when planning how many patients a study needs before data collection.
- 报告规范逐条核查Audits a manuscript item by item against 49 reporting and risk-of-bias checklists. Use when checking a draft against STROBE, CONSORT, TRIPOD or similar guidelines.
- 临床数据清洗与画像Profiles a clinical dataset and generates cleaning code in staged, approved steps. Use when a CSV or Excel dataset needs missing-value and outlier checks before analysis.
- 跨国队列数据协调对比Harmonizes variables and runs parallel weighted analyses across national surveys like KNHANES and NHANES. Use when comparing one exposure-outcome link across countries.
- 变量定义与截断值溯源Maps exposure, outcome and covariate definitions to a cited guideline and DB columns. Use when variable cutoffs need a citable basis before the study protocol.
- 本地化临床数据脱敏Runs a local, network-free script that detects and removes identifiers from clinical data. Use when data may contain PHI and must be de-identified before LLM analysis.
- AI对标专家基准研究设计Plans the arms, rubrics, calibration probes and reviewer panel for an AI-vs-expert benchmark. Use before data collection when designing an AI-vs-human rating study.
- 放射影像AI研究设计审查Reviews a study’s analysis unit, cohort logic, leakage risk and reporting-guideline fit. Use when checking a clinical or medical-AI study design before drafting.
- 传染病仓室模型拟合Builds and fits SIR, SEIR and SEIHR compartmental models with Rt estimation. Use when an outbreak or epidemic’s spread needs mathematical modeling in Python.
- ICMJE利益冲突声明填写Clones a pre-filled synthetic ICMJE COI form, replacing only date, name and title. Use when each author on a submission needs a disclosure form filled quickly.
- 机构Word表单内容填充Fills an institutional Word form, such as an IRB protocol, without breaking its layout. Use when drafted content must be rendered into a CJK-aware .docx template.
- 队列数据库选题挖掘Profiles a longitudinal cohort database and ranks research-topic proposals with gap evidence. Use when looking for a question an available cohort or registry can answer.
- 投稿期刊匹配推荐Matches a manuscript abstract against curated journal profiles and ranks candidates. Use when choosing where to submit, or re-targeting after a rejection.
- DOI全文批量获取Batch-downloads open-access PDFs for a list of DOIs via Unpaywall, PMC and OpenAlex. Use when full texts are needed for a screening set such as a meta-analysis.
- 数据集编码本自动生成Profiles every variable in a tabular dataset into a structured, citable codebook. Use when a CSV, Excel or Stata dataset needs a data dictionary before analysis.
- 全球卫生数据获取分析Accesses and analyzes global health data from WHO GHO, IHME GBD and Our World in Data. Use when DALYs, age-standardized rates or choropleth maps are needed.
- 医学AI项目基金申请书撰写Structures a grant proposal’s significance, innovation, approach, aims and milestones. Use when drafting a research funding proposal, including a Korean grant plan.
- 卫生经济学评价建模Builds Markov cohort models with QALYs, PSA and cost-effectiveness planes. Use when a health intervention needs a formal cost-effectiveness evaluation.
- AI写作痕迹识别改写Scans a manuscript for AI writing patterns and rewrites flagged passages carefully. Use when a draft or response letter reads as obviously AI-written.
- 医学影像数据集画像与预处理Profiles a DICOM or NIfTI dataset’s spacing, intensity and label integrity before modeling. Use when preparing an imaging dataset and auditing it for leakage.
常见问题
因果推断方法设计能做什么?
Runs DAG-based, instrumental-variable, difference-in-differences or RD analyses. Use when an association in observational data must support a causal claim。
如何安装因果推断方法设计?
在科搭 Codar 左侧点击「插件」,在「组件」页签搜索「因果推断方法设计」并安装;在 Claude Code 或 Codex 中可以发送本页的安装提示词,或下载 Skill 包后解压到 ~/.claude/skills 或 ~/.codex/skills。
因果推断方法设计需要哪些权限?
该科研 Skill没有声明额外权限;执行具体操作时仍由 Agent 按自身规则请求确认。
因果推断方法设计经过官方审核吗?
是。SpeedSkills 收录的每个版本都会记录内容摘要与权限声明,当前版本已通过安全审核。