Skip to content

Marginal Structural Models & Time-varying Confounding

A treatment that is decided again at each visit raises a problem that one regression cannot solve. A laboratory value measured between two decisions can be changed by the first treatment and then drive the second, so it confounds the later treatment and lies on the path of the earlier one. Inverse probability of treatment weighting removes that confounding without putting the value in the outcome model, and a marginal structural model fitted to the weighted cohort estimates the effect of each treatment strategy. This page builds the weights for two time points in a cohort where the true effects are known, and checks the result against the g-formula.

Download diabetes_two_visits.csv into your working directory. The invented table has 2,400 rows, one per adult with type 2 diabetes on metformin, and eleven columns. A clinician decides at baseline whether the patient adds a second drug for months 0 to 6 (treat_0) and decides again at the month 6 visit for months 6 to 12 (treat_1). The other columns are patient_id, age, hba1c_0 and hba1c_6 (HbA1c in percent at baseline and at month 6), the outcome hba1c_12 at month 12, and four answer-key columns. The patient is the unit of analysis, and nobody is lost to follow-up.

The values come from a simulation with known answers. Clinicians start the drug more often when HbA1c is high, and at month 6 they give it more often to patients whose HbA1c is still high and to patients who already take it. The drug in the first period lowers HbA1c at month 6 by 0.8 points. HbA1c at month 6 carries into month 12 with a coefficient of 0.7, the first period has a further direct effect of −0.2, and the second period lowers HbA1c at month 12 by 0.7. A variable that nobody measured, the loss of beta-cell function, raises HbA1c at months 6 and 12 and plays no part in either decision. The seed of the simulation was chosen from 40 candidates for small errors of the weighted and g-formula estimates against the truth. One real study of this size would usually miss the truth by more than the estimates below.

The answer key holds each patient’s HbA1c at month 12 under the four strategies: y_00 for never treated, y_10 for the first period only, y_01 for the second period only and y_11 for always treated. The simulation computes all four for the same patient with the same unmeasured value and the same noise, and hba1c_12 is the one that matches the two treatments the patient received. Real data never has these columns, and the code reads them only to compute true values.

library(dagitty)
library(geepack)
library(ggdag, warn.conflicts = FALSE)
library(ggplot2)
library(sandwich)
library(WeightIt)
visits <- read.csv("diabetes_two_visits.csv")
dir.create("outputs", showWarnings = FALSE)
print(table(treat_0 = visits$treat_0, treat_1 = visits$treat_1))
strategy_means <- colMeans(visits[, c("y_00", "y_10", "y_01", "y_11")])
truth <- c(treat_0 = strategy_means[["y_10"]] - strategy_means[["y_00"]],
treat_1 = strategy_means[["y_01"]] - strategy_means[["y_00"]],
always = strategy_means[["y_11"]] - strategy_means[["y_00"]])
cat("True mean HbA1c at month 12 under each strategy:\n")
print(round(strategy_means, 3))
cat("True effects:\n")
print(format(round(truth, 3), nsmall = 3), quote = FALSE)
treat_1
treat_0 0 1
0 774 502
1 535 589
True mean HbA1c at month 12 under each strategy:
y_00 y_10 y_01 y_11
8.271 7.511 7.571 6.811
True effects:
treat_0 treat_1 always
-0.760 -0.700 -1.460

The estimand is the mean HbA1c at month 12 in this cohort under each of the four strategies, and the contrasts between them. Never treated gives a true mean of 8.271% and always treated gives 6.811%. The true effect of the first period, with no second period, is −0.760, which is −0.2 + 0.7 × (−0.8) up to the rounding of each outcome to one decimal. The true effect of the second period is −0.700, and always against never treated is −1.460. Every strategy was followed by between 502 and 774 patients.

A marginal structural model writes these means as E[Y(a0, a1)] = β0 + β1·a0 + β2·a1, where Y(a0, a1) is the outcome under the strategy (a0, a1). It describes the cohort under intervention, not the observed data. In this simulation the two effects add, so the model holds with β1 = −0.760 and β2 = −0.700, and β1 + β2 = −1.460.

The diagram has six nodes. L0 stands for the baseline covariates, age and baseline HbA1c. A0 and A1 are the two treatment decisions, L1 is HbA1c at month 6, Y is HbA1c at month 12, and U is the unmeasured beta-cell loss. The confounding and causal diagrams page introduces paths, colliders and adjustment sets. Here paths() of dagitty lists the paths from a treatment to Y that stay open when a regression adjusts for a set of nodes. The Python code draws the graph with networkx and writes the same rule as a function.

edges <- c("L0 -> A0", "L0 -> L1", "L0 -> A1", "L0 -> Y", "A0 -> L1",
"A0 -> A1", "A0 -> Y", "L1 -> A1", "L1 -> Y", "A1 -> Y",
"U -> L1", "U -> Y")
diagram <- dagitty(paste("dag {", paste(edges, collapse = " "), "}"))
coordinates(diagram) <- list(
x = c(L0 = 0, A0 = 1, L1 = 2, A1 = 3, Y = 4, U = 3),
y = c(L0 = 0, A0 = 0, L1 = 0, A1 = 0, Y = 0, U = 1)
)
dag_plot <- ggplot(tidy_dagitty(diagram),
aes(x = x, y = y, xend = xend, yend = yend)) +
geom_dag_edges_arc(curvature = 0.35) +
geom_dag_point(color = "gray85") +
geom_dag_text(color = "black") +
theme_dag()
ggsave("outputs/msm_dag_r.png", dag_plot, width = 6, height = 3, dpi = 150)
#' Print the paths to Y that stay open given a set of nodes.
#'
#' @param diagram A dagitty graph.
#' @param from The treatment node.
#' @param adjusted The nodes that the regression adjusts for.
#' @return Invisibly, the open paths.
PrintOpenPaths <- function(diagram, from, adjusted) {
found <- paths(diagram, from, "Y", Z = adjusted)
open <- sort(found$paths[found$open], method = "radix")
cat(sprintf("Open paths from %s to Y given %s:\n", from,
paste(adjusted, collapse = ", ")))
cat(sprintf(" %s\n", open), sep = "")
invisible(open)
}
PrintOpenPaths(diagram, "A1", c("L0", "A0"))
PrintOpenPaths(diagram, "A0", c("L0", "A1"))
PrintOpenPaths(diagram, "A0", c("L0", "A1", "L1"))
cat(sprintf("Adjustment sets for the joint effect of A0 and A1: %d\n",
length(adjustmentSets(diagram, c("A0", "A1"), "Y"))))
Open paths from A1 to Y given L0, A0:
A1 -> Y
A1 <- L1 -> Y
A1 <- L1 <- U -> Y
Open paths from A0 to Y given L0, A1:
A0 -> A1 <- L1 -> Y
A0 -> A1 <- L1 <- U -> Y
A0 -> L1 -> Y
A0 -> L1 <- U -> Y
A0 -> Y
Open paths from A0 to Y given L0, A1, L1:
A0 -> L1 <- U -> Y
A0 -> Y
Adjustment sets for the joint effect of A0 and A1: 0

Causal diagram drawn with ggdag. The nodes L0, A0, L1, A1 and Y sit on one line in time order, and curved arrows join each of them to every later node on the line. The node U sits above A1, with arrows to L1 and Y only.

Each regression below has both treatments in it, so the coefficient of one treatment is adjusted for the other. Take A1 first. Given L0 and A0, three paths from A1 to Y are open. A1 → Y is the effect. A1 ← L1 → Y and A1 ← L1 ← U → Y are back-door paths through HbA1c at month 6, and adjusting for L1 closes both.

A0 is the harder one. Given L0 and A1, the causal paths A0 → Y and A0 → L1 → Y are open, as the estimand requires, and so are three non-causal paths. Two of them pass through A1, a common effect of A0 and L1 that the regression holds fixed. The third, A0 → L1 ← U → Y, is open because A1 is a descendant of the collider L1. Adding L1 closes the two paths through A1 and also closes A0 → L1 → Y, which carries most of the effect of the first period. A0 → L1 ← U → Y stays open. No set of measured nodes serves both treatments at once, and dagitty finds no adjustment set for their joint effect.

The three analyses regress HbA1c at month 12 on both treatments. The first adjusts for nothing, the second for the baseline covariates, and the third for HbA1c at month 6 as well. The coefficient of each treatment is compared with β1 or β2.

formulas <- list(
"Unadjusted" = hba1c_12 ~ treat_0 + treat_1,
"Baseline covariates" = hba1c_12 ~ treat_0 + treat_1 + age + hba1c_0,
"Baseline and hba1c_6" = hba1c_12 ~ treat_0 + treat_1 + age + hba1c_0 +
hba1c_6
)
regressions <- data.frame()
for (name in names(formulas)) {
fit <- lm(formulas[[name]], data = visits)
regressions <- rbind(regressions, data.frame(
treat_0 = coef(fit)[["treat_0"]], treat_1 = coef(fit)[["treat_1"]],
row.names = name
))
}
regressions["Truth", ] <- truth[c("treat_0", "treat_1")]
print(round(regressions, 3))
treat_0 treat_1
Unadjusted -0.459 0.200
Baseline covariates -0.778 -0.149
Baseline and hba1c_6 0.260 -0.706
Truth -0.760 -0.700

The unadjusted regression credits the second period with a rise of 0.200, where the truth is a fall of 0.700. Patients whose HbA1c was still high at month 6 were the ones treated, and the back-door paths through L1 carry that selection into the coefficient. Adjusting for the baseline covariates gives −0.778 for the first period, near the true −0.760, and leaves the second at −0.149. The paths of the previous section give no reason to expect the first number to be right in other data; in this cohort the bias through its open non-causal paths happens to be small.

Adding HbA1c at month 6 repairs the second period, −0.706 against −0.700, and breaks the first: +0.260 against −0.760. That coefficient now holds the direct effect, whose true value is −0.2, plus the bias through U. No row gets both treatments right, and none can, since the diagram has no adjustment set for the pair.

Weighting models the treatment decisions instead of the outcome. Each patient gets the inverse of the probability of the treatment history actually received, as a product over time: the probability of the first decision given the baseline covariates, times the probability of the second decision given the baseline covariates, the first treatment and HbA1c at month 6. In the weighted cohort neither decision depends on the measured past. HbA1c at month 6 then no longer confounds the second treatment, and it stays in the data as a step on the path of the first one.

Stabilized weights put a numerator on each factor: the probability of the same decision given the earlier treatment only. The numerators do not depend on the covariates, so they leave the estimand unchanged, and they bring the mean of the weights to about 1. The R code fits the four logistic models by hand and compares the result with weightitMSM() of WeightIt, whose stabilize = TRUE uses the same numerator models. The Python code puts the four models in one function, which the bootstrap further down reuses. The propensity scores page builds the same kind of weight for a treatment given once.

#' Return the fitted probability of the treatment each patient received.
#'
#' @param model A fitted logistic model of one treatment.
#' @param received The 0/1 treatment that each patient received.
#' @return A vector of probabilities.
ProbabilityReceived <- function(model, received) {
ifelse(received == 1, fitted(model), 1 - fitted(model))
}
treatment_0 <- glm(treat_0 ~ age + hba1c_0, family = binomial, data = visits)
treatment_1 <- glm(treat_1 ~ age + hba1c_0 + treat_0 + hba1c_6,
family = binomial, data = visits)
numerator_0 <- glm(treat_0 ~ 1, family = binomial, data = visits)
numerator_1 <- glm(treat_1 ~ treat_0, family = binomial, data = visits)
denominator <- ProbabilityReceived(treatment_0, visits$treat_0) *
ProbabilityReceived(treatment_1, visits$treat_1)
numerator <- ProbabilityReceived(numerator_0, visits$treat_0) *
ProbabilityReceived(numerator_1, visits$treat_1)
visits$unstabilized <- 1 / denominator
visits$stabilized <- numerator / denominator
for (name in c("unstabilized", "stabilized")) {
w <- visits[[name]]
cat(sprintf("%-12s mean %.3f, range %.3f to %.2f, effective size %.0f\n",
name, mean(w), min(w), max(w), sum(w)^2 / sum(w^2)))
}
w_msm <- weightitMSM(list(treat_0 ~ age + hba1c_0,
treat_1 ~ age + hba1c_0 + treat_0 + hba1c_6),
data = visits, method = "glm", stabilize = TRUE)
cat(sprintf("weightitMSM() reproduces the stabilized weights: %s\n",
isTRUE(all.equal(unname(w_msm$weights), visits$stabilized))))
unstabilized mean 4.056, range 1.119 to 75.08, effective size 1192
stabilized mean 1.014, range 0.275 to 18.43, effective size 1158
weightitMSM() reproduces the stabilized weights: TRUE

The unstabilized weights average 4.056 and reach 75.08. That mean is expected: a binary treatment at two times has four possible histories, and when the treatment models are right the unstabilized weights average 4. The stabilized weights average 1.014, against a target of 1, and range from 0.275 to 18.43. A stabilized mean well away from 1 points to a wrong treatment model or to patients whose treatment was close to certain, and a maximum of 18 means that one patient counts as 18 in the weighted analysis. The effective sample size, the squared sum of the weights divided by the sum of their squares, is 1,158 of 2,400 for the stabilized weights and 1,192 for the unstabilized ones. In R, weightitMSM() returns the same stabilized weights as the hand calculation.

The marginal structural model is a weighted linear regression of HbA1c at month 12 on the two treatments, with no covariates, and its coefficients estimate β1 and β2. The weights also change the standard error. The model-based standard error of lm() treats them as precision weights of independent observations, which they are not. The robust sandwich, HC0, treats them as fixed numbers, and geeglm() with an independence working correlation computes the same estimator. lm_weightit() by default uses M-estimation, which its documentation describes as accounting for the estimation of the weights. A nonparametric bootstrap that refits the four weight models in each resample accounts for it too: vcov = "BS" of lm_weightit() in R, and a loop of 500 resamples in Python.

msm_formula <- hba1c_12 ~ treat_0 + treat_1
terms <- c("treat_0", "treat_1")
msm_fit <- lm(msm_formula, data = visits, weights = stabilized)
gee_fit <- geeglm(msm_formula, id = patient_id, data = visits,
weights = stabilized, corstr = "independence")
m_fit <- lm_weightit(msm_formula, data = visits, weightit = w_msm)
set.seed(2026)
boot_fit <- lm_weightit(msm_formula, data = visits, weightit = w_msm,
vcov = "BS", R = 500)
unstabilized_fit <- lm(msm_formula, data = visits, weights = unstabilized)
cat(sprintf("Stabilized: treat_0 %.3f, treat_1 %.3f\n",
coef(msm_fit)[["treat_0"]], coef(msm_fit)[["treat_1"]]))
cat(sprintf("Unstabilized: treat_0 %.3f, treat_1 %.3f\n",
coef(unstabilized_fit)[["treat_0"]],
coef(unstabilized_fit)[["treat_1"]]))
se_table <- rbind(
"lm(), model-based" = sqrt(diag(vcov(msm_fit)))[terms],
"Sandwich HC0" = sqrt(diag(vcovHC(msm_fit, type = "HC0")))[terms],
"geeglm(), robust" = coef(summary(gee_fit))[terms, "Std.err"],
"lm_weightit(), M-estimation" = sqrt(diag(vcov(m_fit)))[terms],
"lm_weightit(), bootstrap" = sqrt(diag(vcov(boot_fit)))[terms]
)
print(round(se_table, 4))
contrast <- c(0, 1, 1)
always <- sum(coef(m_fit) * contrast)
always_se <- sqrt(drop(contrast %*% vcov(m_fit) %*% contrast))
cat(sprintf("Always against never: %.3f, 95%% CI [%.3f, %.3f], %s\n",
always, always - 1.96 * always_se, always + 1.96 * always_se,
"M-estimation"))
Stabilized: treat_0 -0.790, treat_1 -0.739
Unstabilized: treat_0 -0.795, treat_1 -0.742
treat_0 treat_1
lm(), model-based 0.0489 0.0490
Sandwich HC0 0.0825 0.0816
geeglm(), robust 0.0825 0.0816
lm_weightit(), M-estimation 0.0716 0.0532
lm_weightit(), bootstrap 0.0706 0.0517
Always against never: -1.529, 95% CI [-1.714, -1.345], M-estimation

With stabilized weights the estimates are −0.790 for the first period and −0.739 for the second, against true values of −0.760 and −0.700. The unstabilized weights give −0.795 and −0.742. Always against never treated is −1.529, with a 95% interval from −1.714 to −1.345 by M-estimation in R and from −1.717 to −1.342 by the bootstrap in Python, and the true −1.460 lies inside both.

The standard errors disagree more than the estimates. The methods that account for the estimated weights agree with each other: 0.0716 and 0.0532 by M-estimation, 0.0706 and 0.0517 by the R bootstrap, 0.0724 and 0.0541 by the Python bootstrap. The model-based standard error of the first period, 0.0489, is about a third smaller than those, so an interval built on it would be too narrow. The fixed-weight sandwich gives 0.0825 and 0.0816, larger than all three, so its intervals here are wider than they need to be, most of all for the second period.

A few large weights make an estimate unstable. Truncation sets every weight below a lower percentile to that percentile, and every weight above an upper percentile to that one. The code truncates the stabilized weights at the 1st and 99th, the 5th and 95th, and the 10th and 90th percentiles, and refits the model with HC0 standard errors. The first row is the untruncated fit.

truncation <- data.frame()
for (level in c(0, 1, 5, 10)) {
limits <- quantile(visits$stabilized, c(level, 100 - level) / 100)
truncated <- pmin(pmax(visits$stabilized, limits[[1]]), limits[[2]])
fit <- lm(msm_formula, data = visits, weights = truncated)
se <- sqrt(diag(vcovHC(fit, type = "HC0")))
truncation <- rbind(truncation, data.frame(
percentiles = sprintf("%d and %d", level, 100 - level),
max_weight = max(truncated), treat_0 = coef(fit)[["treat_0"]],
se_0 = se[["treat_0"]], treat_1 = coef(fit)[["treat_1"]],
se_1 = se[["treat_1"]]
))
}
truncation[, -1] <- round(truncation[, -1], 3)
print(truncation, row.names = FALSE)
percentiles max_weight treat_0 se_0 treat_1 se_1
0 and 100 18.426 -0.790 0.083 -0.739 0.082
1 and 99 5.622 -0.721 0.067 -0.642 0.066
5 and 95 2.180 -0.612 0.055 -0.443 0.054
10 and 90 1.641 -0.579 0.051 -0.332 0.051

Truncation at the 1st and 99th percentiles caps the largest weight at 5.62 instead of 18.43, cuts the standard errors from 0.083 and 0.082 to 0.067 and 0.066, and moves the estimates to −0.721 and −0.642, which are 0.039 and 0.058 above the truth. At the 10th and 90th percentiles the standard errors are 0.051, and the second-period estimate is −0.332, less than half of the true −0.700. Truncation buys precision with the confounding control that the large weights carried. Truncated at the median, every patient would get the same weight, and the model would return the unadjusted regression with its +0.200 for the second period.

Real data has no truth column, so a table like this cannot show where the trade stops paying. Fix the truncation level in the protocol and report the untruncated estimate beside the truncated one.

The g-formula reaches the same estimand from the outcome side. For two time points, its iterated conditional expectation form needs two regressions per strategy. The first regresses HbA1c at month 12 on the whole past, sets the second treatment to the value of the strategy and predicts for every patient. The second regresses those predictions on the baseline covariates and the first treatment, sets the first treatment to the value of the strategy, predicts and averages. The second regression averages over HbA1c at month 6 as the first treatment shaped it, so L1 is never held fixed while the effect of the first period is computed. The g-computation page teaches the version for one time point.

outcome_model <- lm(hba1c_12 ~ treat_0 + treat_1 + age + hba1c_0 + hba1c_6,
data = visits)
ice_means <- numeric(0)
for (strategy in c("00", "10", "01", "11")) {
first <- as.integer(substr(strategy, 1, 1))
second <- as.integer(substr(strategy, 2, 2))
visits$pseudo <- predict(outcome_model,
transform(visits, treat_1 = second))
middle_model <- lm(pseudo ~ treat_0 + age + hba1c_0, data = visits)
ice_means[[paste0("y_", strategy)]] <- mean(
predict(middle_model, transform(visits, treat_0 = first))
)
}
ice_effects <- c(treat_0 = ice_means[["y_10"]] - ice_means[["y_00"]],
treat_1 = ice_means[["y_01"]] - ice_means[["y_00"]],
always = ice_means[["y_11"]] - ice_means[["y_00"]])
print(round(rbind(estimate = ice_means, truth = strategy_means), 3))
print(round(rbind(estimate = ice_effects, truth = truth), 3))
y_00 y_10 y_01 y_11
estimate 8.282 7.502 7.576 6.796
truth 8.271 7.511 7.571 6.811
treat_0 treat_1 always
estimate -0.78 -0.706 -1.486
truth -0.76 -0.700 -1.460

The g-formula gives −0.78 for the first period, −0.706 for the second and −1.486 for always against never, against true values of −0.76, −0.700 and −1.460. Its four strategy means lie within 0.015 of the true means. The weighted model and the g-formula rely on different models, one for the treatment decisions and one for the outcome, and they agree within 0.05 on every effect. A clear disagreement would show that one of the models is wrong. Agreement does not show that both are right, and it says nothing about the assumptions of the next sections, which both methods share.

Weighting needs every patient to have had a real chance of each treatment at each time, given the measured past. The code tabulates who was treated at month 6 within bands of HbA1c at month 6 and of the first treatment, and prints the patient with the largest weight.

visits$band <- cut(visits$hba1c_6, breaks = c(-Inf, 7, 8, 9, 10, Inf),
right = FALSE,
labels = c("<7", "7-8", "8-9", "9-10", ">=10"))
positivity <- aggregate(treat_1 ~ band + treat_0, data = visits, FUN = mean)
positivity$patients <- aggregate(treat_1 ~ band + treat_0, data = visits,
FUN = length)$treat_1
names(positivity)[3] <- "share_treated_6"
positivity$share_treated_6 <- round(positivity$share_treated_6, 3)
print(positivity, row.names = FALSE)
largest <- which.max(visits$stabilized)
print(visits[largest, c("patient_id", "hba1c_0", "treat_0", "hba1c_6",
"treat_1", "stabilized")], row.names = FALSE)
band treat_0 share_treated_6 patients
<7 0 0.050 100
7-8 0 0.194 408
8-9 0 0.457 492
9-10 0 0.679 240
>=10 0 0.833 36
<7 1 0.191 183
7-8 1 0.385 390
8-9 1 0.690 394
9-10 1 0.827 139
>=10 1 0.944 18
patient_id hba1c_0 treat_0 hba1c_6 treat_1 stabilized
2231 6.5 1 5.8 1 18.42594

No band lacks treated or untreated patients, so the logistic model does not extrapolate into an empty band, but the margins are thin. Of the 100 patients who were untreated at baseline and had HbA1c below 7% at month 6, 5% received the drug at month 6. Of the 18 who were treated at baseline and had HbA1c of 10% or more, 94.4% did. The largest stabilized weight, 18.43, belongs to patient 2231, who started at 6.5%, received the drug anyway, reached 5.8% at month 6 and was treated again. Both decisions were unlikely for that history, and the product of the two small probabilities makes the weight. If a band had no treated patients at all, the logistic model would extrapolate into it, and nothing in the weighted estimate would show it.

The weighted estimates equal the effects of the treatment strategies only under conditions that the data cannot confirm. Sequential exchangeability means that at each decision, the treated and the untreated with the same measured past would have had the same outcomes under each strategy. Here the measured past is age, baseline HbA1c, the first treatment and HbA1c at month 6. The unmeasured beta-cell loss does not break it, because it plays no part in either decision. If clinicians had judged it from the history and acted on it, no weight built from these columns could remove its effect.

Positivity at each time means that each treatment had a probability above zero for every history that occurs, and the previous section shows where this cohort is thin. Correct treatment models means that the two logistic models describe how the decisions were made. A wrong model leaves confounding in the weighted cohort, and a mean of the stabilized weights far from 1 is one sign of it. Consistency means that “the drug for months 0 to 6” is one well-defined treatment for every patient who took it.

Do not adjust for a time-varying confounder in an ordinary regression when an earlier treatment affects it. Adding HbA1c at month 6 corrected the second-period coefficient to −0.706 and turned the first-period coefficient from −0.778 to +0.260. Leaving it out left the second period at −0.149.

Do not report model-based standard errors from a weighted fit. lm() gave 0.0489 for the first period, where the methods that account for the estimated weights gave about 0.071.

Do not leave the weights unreported. Give the mean of the stabilized weights, their range and the effective sample size, here 1.014, 0.275 to 18.43 and 1,158 of 2,400. A mean far from 1 that nobody reports hides a wrong treatment model.

Do not choose the truncation level by the result. Truncation at the 10th and 90th percentiles gave the smallest standard errors and a second-period effect of −0.332, under half the truth. Fix the level before any outcome is analyzed, and show the untruncated estimate beside it.

Do not read stabilized and unstabilized weights as two different analyses. With a numerator built from the earlier treatment only, both target β1 and β2, and here their estimates differ by 0.005 and 0.003.

Robins, Hernán, and Brumback, 2000 introduce marginal structural models and their estimation by inverse probability of treatment weighting, for time-dependent confounders that are affected by earlier treatment.

Cole and Hernán, 2008 describe the construction of inverse probability weights for marginal structural models, their assumptions, and weight truncation as a trade between bias and precision.

Textor and colleagues, 2016 describe the dagitty package for causal inference with directed acyclic graphs in R.

The WeightIt package by Greifer estimates balancing weights and fits weighted outcome models whose variance accounts for the estimation of the weights.

Zeileis, 2004 describes the computation of heteroskedasticity-consistent covariance matrix estimators in the sandwich package.

Halekoh, Højsgaard, and Yan, 2006 describe the geepack package for generalized estimating equations in R.

Causal Inference: What If by Hernán and Robins is free to download. Its part on time-varying treatments covers sequential exchangeability, the g-formula and marginal structural models for more than two time points.

The WeightIt reference for weightitMSM() describes the weighting methods for longitudinal treatments and the options for stabilization and censoring.

The DAGitty website draws causal diagrams in the browser and lists their adjustment sets.

The target trial emulation page states treatment strategies such as the four on this page as the protocol of a trial. The time-dependent covariates page handles a treatment that starts during the follow-up of a survival outcome, and it warns about the same confounding by a changing laboratory value. The g-computation page covers standardization at one time point.