科研 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.

发布者 Codar安全审核通过v0.1.0更新于 2026-11-18

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-stats or model-selection.
  • Standard propensity-score matching/weighting with no instrument or natural experiment available → analyze-stats's references/analysis_guides/propensity_score.md already 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 prefer AER, 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:

  1. Exposure (the variable whose causal effect is of interest) and its hypothetical intervention ("what would changing this mean in practice?").
  2. Outcome, with its measurement window relative to the exposure.
  3. Target population and time zero (index date) — the same target-trial discipline design-study already asks for.
  4. 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

  1. Elicit every variable the user believes is on a causal pathway between exposure and outcome, including ones measured only as covariates in the dataset.
  2. Draw the DAG as text-based edges (exposure -> outcome, age -> exposure, age -> outcome, etc.) and render it, e.g. with dagitty (R) or networkx (Python) for a quick visual.
  3. 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).
  4. 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.
  5. 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:

  1. Relevance: Z is associated with the exposure (testable — report the first-stage F statistic; F < 10 flags a weak instrument and unreliable IV estimates).
  2. Exclusion restriction: Z affects the outcome only through the exposure (not testable from data alone — argue it from substantive knowledge, and report competing explanations).
  3. Independence (no confounding of Z and 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
  1. 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.
  2. 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.
  3. For more than two periods or staggered treatment timing, use a staggered-DiD estimator (did package 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)
  1. 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.
  2. Report the bandwidth-sensitivity of the estimate (several bandwidths, not just the MSE-optimal one) and the local-linear vs local-quadratic specification.
  3. 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

  1. 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-protocol can host this document; this skill supplies the causal-design content.
  2. 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.
  3. 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 to self-review's observational_confounding.md domain 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.

示例提示词

帮我用双重差分法评估这项医保政策对住院率的因果影响。

所属插件

临床医学与公共卫生面向临床与公卫研究:研究设计与方案、样本量、队列与 Meta 分析、报告规范核查、医学影像 AI 评估、流行病建模与卫生经济学评价、医学论文写作投稿。

安装该插件会一并获得同领域的 58 个 Skill / MCP。

同插件的其他科研 Skill

常见问题

因果推断方法设计能做什么?

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 收录的每个版本都会记录内容摘要与权限声明,当前版本已通过安全审核。