Time-varying confounding: why adjustment fails and IPTW works
Source:vignettes/walkthrough.Rmd
walkthrough.RmdThe question
Does a new heart-rate-lowering agent, started after a severe heart attack, reduce one-year mortality?
We follow each patient across two intervals and record, at baseline and at a follow-up visit, their resting heart rate and whether they are on the drug. The trap is hiding in the heart rate.
The trap, in one diagram
plot_dag()
Resting heart rate plays two roles at once:
- a confounder — a faster heart rate makes a patient both more likely to be treated (indication) and more likely to die (risk); and
- a mediator — the drug lowers the
heart rate at follow-up (
drug1 → HR1), and a lower heart rate then means fewer deaths.
That double role is the whole problem:
- Don’t adjust for follow-up heart rate → the follow-up dose stays confounded.
- Do adjust for it → you block part of the drug’s benefit (you have conditioned on a mediator), biasing the baseline dose.
No single conventional model can be right. We need a method that removes confounding without conditioning on the mediator. That method is inverse probability of treatment weighting (IPTW), giving a marginal structural model (MSM).
The DAG is also available as a dagitty object, so you
can read the tell off the graph itself. To de-confound the
follow-up dose you must adjust for HR1
—
dagitty::adjustmentSets(hr_dag(), exposure = "drug2", outcome = "death")
#> { HR1, baseline_hr, drug1 }— but HR1 is on the causal path out of the
baseline dose (drug1 → HR1), so the very variable you must
condition on for drug2 is one you must not
condition on for drug1. That contradiction is the trap,
stated formally.
Step 1 — Simulate the cohort
The package generates its own data, so everything here is reproducible with no external file. The result is in counting-process (“long”) form: one row per patient per interval at risk.
dat <- simulate_hr_agent()
dat |> filter(id %in% c(1, 2)) |> select(id, t_start, t_stop, on_drug,
drug1, drug2, heart_rate, death)
#> # A tibble: 4 × 8
#> id t_start t_stop on_drug drug1 drug2 heart_rate death
#> <int> <dbl> <dbl> <int> <int> <int> <dbl> <int>
#> 1 1 0 1 0 0 0 72.5 0
#> 2 1 1 2 0 0 0 87.7 0
#> 3 2 0 1 0 0 0 82.2 0
#> 4 2 1 2 1 0 1 86.6 0drug1 / drug2 are the baseline and
follow-up doses; on_drug is the dose in the current
interval; heart_rate is the heart rate in the current
interval. The full data dictionary is one call away:
hr_variables()
#> # A tibble: 11 × 3
#> variable role description
#> <chr> <chr> <chr>
#> 1 id identifier Patient identifier (repeats across interva…
#> 2 t_start time Start of the (t_start, t_stop] risk interv…
#> 3 t_stop time End of the risk interval (1 or 2).
#> 4 on_drug exposure On the drug during this interval; the outc…
#> 5 drug1 exposure Baseline dose (interval 1). A component of…
#> 6 drug2 exposure Follow-up dose (interval 2); 0 until the f…
#> 7 prev_drug exposure history Dose in the previous interval; a predictor…
#> 8 heart_rate confounder Heart rate in the current interval (baseli…
#> 9 baseline_hr confounder Resting heart rate at baseline (bpm). Conf…
#> 10 HR1 confounder + mediator Follow-up heart rate (bpm). Lowered by dru…
#> 11 death outcome Died during this interval (1 = yes).Step 2 — The ground truth (a randomised “oracle”)
The causal truth is a property of the data-generating machine, not of any one confounded data set. To read it off, we turn confounding off — randomise treatment — and run the trial at a huge sample size so there is no sampling noise. Everything below will be judged against this number.
The drug is genuinely, clearly protective (hazard ratio well below 1). Keep this number in mind.
Step 3 — Naive analyses (and why they disagree)
Crude
m1 <- coxph(Surv(t_start, t_stop, death) ~ drug1, data = dat) # baseline dose
m2 <- coxph(Surv(t_start, t_stop, death) ~ drug2, data = dat) # follow-up dose
tidy(m1, exponentiate = TRUE, conf.int = TRUE)
#> # A tibble: 1 × 7
#> term estimate std.error statistic p.value conf.low conf.high
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 drug1 0.774 0.0898 -2.85 0.00438 0.649 0.923
tidy(m2, exponentiate = TRUE, conf.int = TRUE)
#> # A tibble: 1 × 7
#> term estimate std.error statistic p.value conf.low conf.high
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 drug2 1.25 0.130 1.70 0.0893 0.967 1.61The two crude analyses already contradict each other — the baseline dose looks protective, the follow-up dose looks harmful. That contradiction is the tell that confounding is at work.
Adjusting for heart rate
m3 <- coxph(Surv(t_start, t_stop, death) ~ drug1 + baseline_hr, data = dat)
m4 <- coxph(Surv(t_start, t_stop, death) ~ drug2 + drug1 + baseline_hr, data = dat)
tidy(m3, exponentiate = TRUE, conf.int = TRUE)
#> # A tibble: 2 × 7
#> term estimate std.error statistic p.value conf.low conf.high
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 drug1 0.528 0.0972 -6.58 4.81e-11 0.436 0.638
#> 2 baseline_hr 1.04 0.00393 10.2 2.24e-24 1.03 1.05
tidy(m4, exponentiate = TRUE, conf.int = TRUE)
#> # A tibble: 3 × 7
#> term estimate std.error statistic p.value conf.low conf.high
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 drug2 0.957 0.133 -0.333 7.39e- 1 0.738 1.24
#> 2 drug1 0.527 0.0974 -6.58 4.55e-11 0.435 0.637
#> 3 baseline_hr 1.04 0.00402 10.0 1.06e-23 1.03 1.05Adjusting moves the numbers around but does not rescue them:
m4 conditions on the prior dose and heart rate — part of
the drug’s own mechanism — and washes the follow-up dose’s effect toward
the null.
Step 4 — The propensity score
The propensity score is the probability of being on the drug given the confounders. We will use it two ways: first to adjust (M5, still not enough), then to weight (M7, the fix).
ps_fit <- fit_propensity(dat)
tidy(ps_fit, exponentiate = TRUE)
#> # A tibble: 4 × 5
#> term estimate std.error statistic p.value
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 (Intercept) 0.000621 0.144 -51.4 0
#> 2 baseline_hr 1.02 0.00208 10.6 2.56e- 26
#> 3 heart_rate 1.07 0.00205 32.9 6.47e-237
#> 4 prev_drug 1.89 0.0517 12.3 1.10e- 34
dat_w <- add_iptw(dat, ps_fit) # adds `ps` and the IPT `weight`
m5 <- coxph(Surv(t_start, t_stop, death) ~ drug2 + ps, data = dat_w)
tidy(m5, exponentiate = TRUE, conf.int = TRUE)
#> # A tibble: 2 × 7
#> term estimate std.error statistic p.value conf.low conf.high
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 drug2 0.779 0.137 -1.83 6.69e- 2 0.596 1.02
#> 2 ps 10.8 0.216 11.0 3.34e-28 7.09 16.6Step 5 — The marginal model, with and without weights
Here is the key comparison. Both models below fit the
same structural model — both doses together, with the
always-treat-vs-never-treat effect exp(b_drug1 + b_drug2).
They differ in one thing only: the IPT weights.
# M6: marginal model, UNWEIGHTED -- still confounded
m6 <- coxph(Surv(t_start, t_stop, death) ~ drug1 + drug2, cluster = id, data = dat)
# M7: the MSM -- same model, now IPT-weighted
m7 <- coxph(Surv(t_start, t_stop, death) ~ drug1 + drug2,
weights = weight, cluster = id, data = dat_w)
hr_msm(m6, "M6 unweighted")
#> Warning: The default delta method standard errors for `coxph` models only take
#> into account uncertainty in the regression coefficients. Standard errors may be
#> too small. Use the `inferences()` function or set `vcov` to "rsample", "boot"
#> or "fwb" to compute confidence intervals by bootstrapping. Set `vcov` to
#> `FALSE` or `options(marginaleffects_safe=FALSE)` to silence this warning.
#> # A tibble: 1 × 4
#> method hr lo hi
#> <chr> <dbl> <dbl> <dbl>
#> 1 M6 unweighted 0.971 0.711 1.33
hr_msm(m7, "M7 IPTW / MSM")
#> Warning: The default delta method standard errors for `coxph` models only take
#> into account uncertainty in the regression coefficients. Standard errors may be
#> too small. Use the `inferences()` function or set `vcov` to "rsample", "boot"
#> or "fwb" to compute confidence intervals by bootstrapping. Set `vcov` to
#> `FALSE` or `options(marginaleffects_safe=FALSE)` to silence this warning.
#> # A tibble: 1 × 4
#> method hr lo hi
#> <chr> <dbl> <dbl> <dbl>
#> 1 M7 IPTW / MSM 0.428 0.305 0.599Without the weights the marginal contrast sits near the null. Add the weights and it drops onto the truth. The weighting is what fixes it — that is the lesson.
Step 6 — Put every method on one forest plot
fit_all_models() and build_forest() package
up all seven fits; plot_forest() draws them against the
ground truth.
fits <- fit_all_models(dat)
forest <- build_forest(fits)
#> Warning: The default delta method standard errors for `coxph` models only take
#> into account uncertainty in the regression coefficients. Standard errors may be
#> too small. Use the `inferences()` function or set `vcov` to "rsample", "boot"
#> or "fwb" to compute confidence intervals by bootstrapping. Set `vcov` to
#> `FALSE` or `options(marginaleffects_safe=FALSE)` to silence this warning.
#> Warning: The default delta method standard errors for `coxph` models only take
#> into account uncertainty in the regression coefficients. Standard errors may be
#> too small. Use the `inferences()` function or set `vcov` to "rsample", "boot"
#> or "fwb" to compute confidence intervals by bootstrapping. Set `vcov` to
#> `FALSE` or `options(marginaleffects_safe=FALSE)` to silence this warning.
forest
#> # A tibble: 7 × 5
#> method hr lo hi correct
#> <fct> <dbl> <dbl> <dbl> <lgl>
#> 1 M1 Crude (baseline dose) 0.774 0.649 0.923 FALSE
#> 2 M2 Crude (follow-up dose) 1.25 0.967 1.61 FALSE
#> 3 M3 Adjust baseline HR (baseline dose) 0.528 0.436 0.638 FALSE
#> 4 M4 Adjust baseline HR + prior dose (follow-up dose) 0.957 0.738 1.24 FALSE
#> 5 M5 PS-adjusted (follow-up dose) 0.779 0.596 1.02 FALSE
#> 6 M6 Marginal model, both doses (unweighted) 0.971 0.711 1.33 FALSE
#> 7 M7 IPTW / MSM (always vs never) 0.428 0.305 0.599 TRUE
plot_forest(forest, truth = truth)
Read it left to right: the conventional analyses (orange) scatter on both sides of the truth and even disagree about the direction of the effect. Only the IPTW / MSM (purple, M7) lands on the dashed truth line.
Takeaways for your first MSM
- Spot the trap. A time-varying covariate that is both a confounder of later treatment and affected by earlier treatment cannot be handled by ordinary adjustment — adjust and you block the mechanism, don’t and you stay confounded.
- Weight, don’t condition. IPTW rebuilds a pseudo-population where treatment no longer depends on the confounders, so a weighted model estimates the marginal effect without touching the mediator.
-
Use treatment history. The estimand is always
treat vs never treat, so the model carries both doses and you
report
exp(b_drug1 + b_drug2). -
Cluster your standard errors. Patients contribute
several person-intervals and are weighted, so use a robust
(
cluster = id) sandwich SE. - Know your target. Here we could check the answer against a randomised oracle. In real data you cannot — which is exactly why getting the method right matters.