A hands-on R package for teaching time-varying confounding, IPTW, and marginal structural models (MSM) — built around one clean, simulated example.
📖 Read the lesson online (no install needed): https://nopkhongthon.github.io/msmworkshop/articles/walkthrough.html
Standard covariate adjustment quietly breaks when a time-varying confounder is also affected by prior treatment. This package walks a learner from the most naive analysis to a marginal structural model, and shows on a single forest plot which methods land on the truth and which don’t.
The running example: does a heart-rate-lowering agent, started after a severe heart attack, cut one-year mortality? Resting heart rate is at once a confounder (fast heart rate → treated and → death) and a mediator (drug → lowers heart rate → survival). Adjust for it and you block the drug’s benefit; don’t and you stay confounded. Only IPTW escapes the trap.
The causal structure

Follow-up heart rate HR1 is caused by the baseline dose (drug1 → HR1, the drug lowers heart rate) and is itself a confounder of the follow-up dose (HR1 → drug2, HR1 → death). So the one variable you must adjust for to de-confound drug2 is a variable you must not adjust for when estimating drug1. hr_dag() returns this as a dagitty object; plot_dag() draws it.
Variables
| Variable | Role | Meaning |
|---|---|---|
id |
identifier | Patient id (repeats across intervals) |
t_start, t_stop
|
time | The (t_start, t_stop] risk interval |
on_drug |
exposure | On the drug this interval — the weight model’s outcome |
drug1, drug2
|
exposure | Baseline and follow-up doses |
prev_drug |
exposure history | Dose in the previous interval |
baseline_hr |
confounder | Resting heart rate at baseline (bpm) |
HR1 / heart_rate
|
confounder + mediator | Follow-up heart rate — lowered by drug1, confounds drug2
|
death |
outcome | Died during this interval |
Get the dictionary in R with hr_variables().
Install
This is a public repository — you do not need a GitHub token. Use whichever installer you have:
# Option A — pak (recommended: resolves dependencies cleanly)
install.packages("pak")
pak::pak("Nopkhongthon/msmworkshop")
# Option B — remotes / devtools
install.packages("remotes")
remotes::install_github("Nopkhongthon/msmworkshop", build_vignettes = TRUE)Seeing
HTTP 401 Bad credentials? That’s a staleGITHUB_PATon your machine, not a problem with this repo. Because the repo is public you don’t need a token — clear it for the session and retry:Sys.unsetenv("GITHUB_PAT")To remove it for good, run
usethis::edit_r_environ()and delete theGITHUB_PATline.
Start here
library(msmworkshop)
# 1. Simulate the confounded cohort (counting-process / long form)
dat <- simulate_hr_agent()
# 2. The randomised "oracle" ground truth (what a perfect RCT would find)
truth <- oracle_hr()
# 3. Fit M1-M7, assemble the comparison, and plot it
fits <- fit_all_models(dat)
forest <- build_forest(fits)
plot_forest(forest, truth = truth)Or reproduce everything end to end:
The teaching walkthrough
The vignette is the lesson — read it first:
vignette("walkthrough", package = "msmworkshop")It goes step by step: simulate → ground truth → crude → adjusted → propensity score → marginal model (unweighted vs IPT-weighted) → forest plot, explaining at each step why the number moves.
The seven models
| Model | What it does | Verdict |
|---|---|---|
| M1 | Crude, baseline dose (~ drug1) |
biased |
| M2 | Crude, follow-up dose (~ drug2) |
biased (opposite direction!) |
| M3 | Adjust baseline HR (~ drug1 + baseline_hr) |
biased |
| M4 | Adjust baseline HR + prior dose (~ drug2 + drug1 + baseline_hr) |
biased (conditions on the mediator) |
| M5 | Propensity-score adjusted (~ drug2 + ps) |
biased |
| M6 | Marginal model, both doses, unweighted | still confounded |
| M7 | IPTW / MSM — same model, IPT-weighted | ✅ recovers the truth |
M6 and M7 differ only by the weights, which isolates exactly what the weighting buys you.
Exported functions
| Function | Role |
|---|---|
hr_dag(), plot_dag()
|
the causal DAG as a dagitty object / house-style plot |
hr_variables() |
the data dictionary |
simulate_hr_agent() |
generate the counting-process cohort (the data-generating trap) |
oracle_hr() |
ground-truth HR from a large randomised run |
fit_propensity() |
the treatment (propensity) model |
add_iptw() |
attach propensity scores and IPT weights |
hr_term(), hr_msm()
|
extract a single-coefficient HR / the marginal always-vs-never HR |
fit_all_models() |
fit M1–M7 in one call |
build_forest() |
assemble the plottable comparison table |
plot_forest() |
the forest plot vs the ground truth |
forest_labels(), msm_palette()
|
labels and the teaching colour palette |
