Skip to content

G-computation & Standardized Effects

A logistic regression of an outcome on a treatment and its confounders returns an odds ratio for patients who share the same covariate values. A decision about a treatment policy needs a different quantity: the risk in the whole population if everyone were treated, set against the risk if no one were. G-computation, also called model-based standardization, gets both risks from the same regression by predicting every patient twice and averaging. This page computes the standardized risks in a cohort where the true answer is known, attaches an interval, and shows what happens when a model is wrong.

Download pneumonia_cohort.csv into your working directory. The invented table has 3,000 rows, one per adult admitted to hospital with pneumonia, and eight columns: patient_id, age, oxygen (1 for a patient who needed supplemental oxygen at admission), crp_mg_l (C-reactive protein, a blood marker of inflammation), steroid (1 for a corticosteroid started on the day of admission), died_28d (1 for death within 28 days), risk_untreated and risk_treated. Treatment is decided once, at admission, and every patient is followed to day 28. The patient is the unit of analysis.

The values come from a simulation with known answers. Clinicians gave the steroid more often to older patients, to patients on oxygen and to patients with a higher CRP, and each of those three also raises the risk of death. The effect of the steroid depends on oxygen. It multiplies the odds of death by 1.105 in a patient who breathes room air, a small harm, and by 0.449 in a patient on oxygen. The seed of the simulation was chosen from 24 candidates as one whose treatment estimates lie within one standard error of their true values. One real study of this size can miss the truth by more than the estimates below.

The last two columns are an answer key. risk_untreated is the patient’s probability of death within 28 days without the steroid, risk_treated is the probability with it, and died_28d was drawn from the one that matches the treatment the patient received. Real data never has these columns, because each patient receives one treatment and shows one outcome. They are in the file so that every estimate on this page can be set beside the truth, and the code reads them only to compute true values.

State the target before the method. The average treatment effect compares two risks in the same 3,000 patients: the 28-day risk of death if every one of them had received the steroid, and the risk if none had. That sentence fixes the population, which is this cohort as admitted, the contrast and the outcome. Neither risk can be observed, and in the simulation each one is the mean of an answer-key column. The code computes the true values, then the crude comparison of the observed risks in the treated and the untreated, as on the risk measures page.

library(marginaleffects)
library(ggplot2)
cohort <- read.csv("pneumonia_cohort.csv")
dir.create("outputs", showWarnings = FALSE)
treated <- cohort$steroid == 1
#' Contrast two risks on three scales.
#'
#' @param risk_1 The risk when everyone is treated.
#' @param risk_0 The risk when no one is treated.
#' @return A named vector with both risks, the risk difference, the risk
#' ratio and the odds ratio.
ContrastRisks <- function(risk_1, risk_0) {
c(risk_1 = risk_1, risk_0 = risk_0, risk_diff = risk_1 - risk_0,
risk_ratio = risk_1 / risk_0,
odds_ratio = (risk_1 / (1 - risk_1)) / (risk_0 / (1 - risk_0)))
}
truth <- ContrastRisks(mean(cohort$risk_treated),
mean(cohort$risk_untreated))
crude <- ContrastRisks(mean(cohort$died_28d[treated]),
mean(cohort$died_28d[!treated]))
cat(sprintf("%d patients, %d on the steroid, %d deaths within 28 days\n",
nrow(cohort), sum(treated), sum(cohort$died_28d)))
print(round(rbind(Truth = truth, Crude = crude), 3))
baseline <- aggregate(cbind(age, oxygen, crp_mg_l) ~ steroid, data = cohort,
FUN = mean)
print(round(baseline, 2), row.names = FALSE)
3000 patients, 1130 on the steroid, 519 deaths within 28 days
risk_1 risk_0 risk_diff risk_ratio odds_ratio
Truth 0.158 0.218 -0.061 0.723 0.671
Crude 0.214 0.148 0.066 1.446 1.567
steroid age oxygen crp_mg_l
0 60.85 0.28 80.18
1 67.45 0.72 120.23

If all 3,000 patients were treated, 15.8% would die within 28 days, and if none were, 21.8% would. The true risk difference is −0.061, about six deaths prevented per 100 patients, and the true risk ratio is 0.723. The odds ratio of the same two risks, 0.671, returns in a later section. The crude comparison points the other way. The 1,130 treated patients died more often, 21.4% against 14.8%, a crude risk difference of +0.066. The second table shows why. The treated patients are 6.6 years older on average, 72% of them were on oxygen against 28% of the untreated, and their mean CRP is 120 mg/L against 80. Sicker patients received the drug, and the crude contrast credits their extra deaths to it.

G-computation replaces the two observed groups with two predictions for every patient.

  1. Fit a model for the outcome given the treatment and the confounders. Here it is a logistic regression with age, CRP, oxygen and the interaction of steroid with oxygen, so that the effect of the drug may differ between patients on oxygen and patients on room air.
  2. Predict each patient’s risk two times from that model, once with steroid set to 1 and once with steroid set to 0. The patient’s own age, oxygen status and CRP stay as they are.
  3. Average each set of predictions over the cohort. The two means are the standardized risks, and their difference and ratio are the effect estimates. The average runs over all 3,000 patients, treated or not, which makes the result an estimate for the population that the estimand names.
# Step 1: model the outcome given treatment and the confounders.
outcome_formula <- died_28d ~ steroid * oxygen + age + crp_mg_l
outcome_fit <- glm(outcome_formula, family = binomial, data = cohort)
# Step 2: predict every patient's risk under each strategy.
cohort$pred_treated <- predict(outcome_fit, transform(cohort, steroid = 1),
type = "response")
cohort$pred_untreated <- predict(outcome_fit, transform(cohort, steroid = 0),
type = "response")
shown <- c("patient_id", "oxygen", "steroid", "died_28d", "pred_treated",
"pred_untreated")
print(round(head(cohort[, shown], 4), 3), row.names = FALSE)
# Step 3: average each set of predictions and contrast the two means.
g_comp <- ContrastRisks(mean(cohort$pred_treated),
mean(cohort$pred_untreated))
print(round(rbind(Truth = truth, "G-computation" = g_comp), 3))
risk_long <- data.frame(
risk = c(cohort$pred_untreated, cohort$pred_treated),
strategy = rep(c("No one treated", "Everyone treated"),
each = nrow(cohort))
)
risk_plot <- ggplot(risk_long, aes(risk, fill = strategy)) +
geom_histogram(position = "identity", alpha = 0.55, bins = 40,
boundary = 0) +
geom_vline(xintercept = g_comp[c("risk_0", "risk_1")],
color = c("#c44e52", "#3a7d6b"), linetype = "dashed") +
scale_fill_manual(values = c("No one treated" = "#c44e52",
"Everyone treated" = "#69b3a2"),
name = NULL) +
labs(x = "Predicted 28-day risk of death (dashed lines at the means)",
y = "Patients") +
theme_classic(base_size = 12) +
theme(legend.position = "top")
ggsave("outputs/g_computation_risks_r.png", risk_plot, width = 6,
height = 3.5, dpi = 150)
patient_id oxygen steroid died_28d pred_treated pred_untreated
1 0 0 0 0.044 0.037
2 0 0 0 0.076 0.064
3 0 0 0 0.062 0.052
4 1 0 0 0.164 0.322
risk_1 risk_0 risk_diff risk_ratio odds_ratio
Truth 0.158 0.218 -0.061 0.723 0.671
G-computation 0.155 0.217 -0.062 0.714 0.662

Two overlaid histograms of predicted 28-day risk of death drawn with ggplot2. With no one treated, the risks have a long right tail that reaches 0.9. With everyone treated, the tail above 0.4 is much thinner and more patients lie between 0.05 and 0.25. Dashed lines mark the two means, near 0.22 and 0.16.

Step 2 gives each patient two risks. Patient 4 was on oxygen and did not receive the steroid, and the model predicts a risk of 0.322 without the drug and 0.164 with it. Patient 1 breathed room air, and the two predictions are 0.037 and 0.044, a little higher with the drug. One prediction in each pair describes a treatment that the patient did not receive, and the model supplies it from patients with similar covariates who did. Step 3 gives standardized risks of 0.155 with everyone treated and 0.217 with no one treated, the dashed lines of the histogram. The risk difference is −0.062 against a true −0.061, and the risk ratio is 0.714 against a true 0.723. With no one treated, a long tail of patients has a predicted risk above 0.4. With everyone treated that tail is much thinner, because most high-risk patients are on oxygen, where the drug works.

A standardized risk depends on every coefficient of the model and on the covariates of the cohort, so no line of the regression output is its standard error. The nonparametric bootstrap needs no formula. Draw 3,000 patients with replacement, run all three steps on the resample, and repeat. The standard deviation of the results is the standard error, and their 2.5th and 97.5th percentiles form a 95% interval.

Each resample below fits its own model, then averages its predictions twice: over all patients of the resample, and over its treated patients, for a section further down. The code draws 500 resamples to keep the run short; use a few thousand for an interval that you report. The last lines run the bootstrap the wrong way on purpose. They resample the predictions of the one model fitted to the full cohort, and they never refit it.

#' Average the predicted risks of a fitted outcome model.
#'
#' @param fit A fitted logistic model with the term steroid.
#' @param target The patients to average over.
#' @return The vector that ContrastRisks() returns.
StandardizeFit <- function(fit, target) {
risk_1 <- predict(fit, transform(target, steroid = 1), type = "response")
risk_0 <- predict(fit, transform(target, steroid = 0), type = "response")
ContrastRisks(mean(risk_1), mean(risk_0))
}
#' Summarize bootstrap draws beside the estimate and the truth.
#'
#' @param estimate The estimates from the full cohort.
#' @param draws A matrix with one row per resample.
#' @param truth The true values.
#' @return A data frame with the estimate, the bootstrap standard error,
#' the 2.5th and 97.5th percentiles of the draws, and the truth.
SummarizeBootstrap <- function(estimate, draws, truth) {
data.frame(estimate = estimate, se = apply(draws, 2, sd),
lower = apply(draws, 2, quantile, probs = 0.025),
upper = apply(draws, 2, quantile, probs = 0.975),
truth = truth)
}
n_boot <- 500
boot_ate <- matrix(NA_real_, n_boot, 5, dimnames = list(NULL, names(truth)))
boot_att <- boot_ate
set.seed(2026)
for (b in seq_len(n_boot)) {
resample <- cohort[sample(nrow(cohort), replace = TRUE), ]
fit <- glm(outcome_formula, family = binomial, data = resample)
boot_ate[b, ] <- StandardizeFit(fit, resample)
boot_att[b, ] <- StandardizeFit(fit, resample[resample$steroid == 1, ])
}
boot_summary <- SummarizeBootstrap(g_comp, boot_ate, truth)
print(round(boot_summary, 3))
set.seed(2026)
fixed_model <- numeric(n_boot)
for (b in seq_len(n_boot)) {
rows <- sample(nrow(cohort), replace = TRUE)
fixed_model[b] <- mean(cohort$pred_treated[rows] -
cohort$pred_untreated[rows])
}
cat(sprintf("SE of the risk difference, model refitted %.4f, not %.4f\n",
boot_summary["risk_diff", "se"], sd(fixed_model)))
estimate se lower upper truth
risk_1 0.155 0.010 0.134 0.176 0.158
risk_0 0.217 0.011 0.199 0.240 0.218
risk_diff -0.062 0.015 -0.090 -0.031 -0.061
risk_ratio 0.714 0.059 0.608 0.847 0.723
odds_ratio 0.662 0.066 0.547 0.816 0.671
SE of the risk difference, model refitted 0.0147, not 0.0017

In R the bootstrap standard error of the risk difference is 0.015, and the percentile interval runs from −0.090 to −0.031. Python draws other resamples from its own generator and prints −0.093 to −0.033. Both intervals exclude zero and contain the true −0.061. The risk ratio of 0.714 has limits of 0.608 and 0.847 in R and of 0.602 and 0.837 in Python. With 500 resamples, the third decimal of a limit depends on the seed. The last line shows what the refit is worth. When the model is fitted once and only its predictions are resampled, the standard error comes out at 0.0017, against 0.0147 in R and 0.0154 in Python for the full procedure. That shortcut treats the coefficients as known, while most of the uncertainty in a standardized risk comes from estimating them. Its interval would be about nine times too narrow.

The delta method gets a standard error from the covariance matrix of the coefficients and the derivative of the standardized risk with respect to each coefficient. In R, avg_comparisons() of the marginaleffects package performs steps 2 and 3 for a fitted model and returns the contrast with such a standard error. Its documentation describes the default, vcov = TRUE, as standard errors from the delta method with the covariance matrix of the model, which holds the covariates of the 3,000 patients fixed. The option vcov = "unconditional", marked as experimental in version 1.0.0, adds the sampling variation of the covariate distribution. This section is in R only.

me_rd <- avg_comparisons(outcome_fit, variables = "steroid")
me_rd_un <- avg_comparisons(outcome_fit, variables = "steroid",
vcov = "unconditional")
me_rr <- avg_comparisons(outcome_fit, variables = "steroid",
comparison = "lnratioavg", transform = "exp")
columns <- c("estimate", "std.error", "conf.low", "conf.high")
difference_table <- rbind(
"Delta method" = unlist(me_rd[, columns]),
"Delta method, unconditional" = unlist(me_rd_un[, columns]),
"Bootstrap" = unlist(boot_summary["risk_diff",
c("estimate", "se", "lower", "upper")])
)
colnames(difference_table) <- c("estimate", "se", "lower", "upper")
print(round(difference_table, 4))
cat(sprintf("Risk ratio %.3f, delta method [%.3f, %.3f], %s [%.3f, %.3f]\n",
me_rr$estimate, me_rr$conf.low, me_rr$conf.high, "bootstrap",
boot_summary["risk_ratio", "lower"],
boot_summary["risk_ratio", "upper"]))
estimate se lower upper
Delta method -0.0621 0.0150 -0.0916 -0.0326
Delta method, unconditional -0.0621 0.0153 -0.0920 -0.0322
Bootstrap -0.0621 0.0147 -0.0897 -0.0308
Risk ratio 0.714, delta method [0.605, 0.842], bootstrap [0.608, 0.847]

The delta-method standard error of the risk difference is 0.0150, with an interval from −0.0916 to −0.0326. The unconditional version gives 0.0153, and the bootstrap gave 0.0147 in R and 0.0154 in Python, so the methods agree to within 0.0007. The default answers a narrower question than the bootstrap. It describes the effect in patients with exactly these covariates, which is also how the truth on this page is defined, while the bootstrap and the unconditional variance add the variation between samples of patients. For the risk ratio, comparison = "lnratioavg" builds the interval on the log scale and returns 0.605 to 0.842, against 0.608 to 0.847 from the R bootstrap.

The logistic model already produced odds ratios, and they are not the number from step 3. The exponentiated coefficient of steroid is a conditional odds ratio. It compares a treated with an untreated patient at fixed values of age, CRP and oxygen, and with the interaction in the model there is one for room air and one for oxygen. The marginal odds ratio compares the odds of the two standardized risks in the whole cohort. The code prints each estimate beside its true value, then the single odds ratio of a model without the interaction.

The table that follows uses the answer key alone, so it holds no confounding and no estimation error. For each oxygen group it gives the odds ratio that the patients of the group share (patient_or, the median over the patients), the odds ratio of the group’s two mean risks (or_of_means), the mean of the patients’ risk differences (mean_of_rd) and the difference of the two mean risks (rd_of_means).

coefficients <- coef(outcome_fit)
conditional <- exp(c(coefficients[["steroid"]],
coefficients[["steroid"]] +
coefficients[["steroid:oxygen"]]))
individual_or <- (cohort$risk_treated / (1 - cohort$risk_treated)) /
(cohort$risk_untreated / (1 - cohort$risk_untreated))
true_conditional <- tapply(individual_or, cohort$oxygen, median)
cat(sprintf("Conditional odds ratio, %-8s: estimate %.3f, truth %.3f\n",
c("room air", "oxygen"), conditional, true_conditional),
sep = "")
cat(sprintf("Marginal odds ratio, everyone : estimate %.3f, truth %.3f\n",
g_comp[["odds_ratio"]], truth[["odds_ratio"]]))
no_interaction <- died_28d ~ steroid + oxygen + age + crp_mg_l
single_fit <- glm(no_interaction, family = binomial, data = cohort)
cat(sprintf("Odds ratio of a model without the interaction: %.3f\n",
exp(coef(single_fit)[["steroid"]])))
answer_key <- data.frame()
for (level in c(0, 1)) {
stratum <- cohort[cohort$oxygen == level, ]
marginal <- ContrastRisks(mean(stratum$risk_treated),
mean(stratum$risk_untreated))
answer_key <- rbind(answer_key, data.frame(
oxygen = level, patients = nrow(stratum),
patient_or = median(individual_or[cohort$oxygen == level]),
or_of_means = marginal[["odds_ratio"]],
mean_of_rd = mean(stratum$risk_treated - stratum$risk_untreated),
rd_of_means = marginal[["risk_diff"]]
))
}
print(round(answer_key, 3), row.names = FALSE)
Conditional odds ratio, room air: estimate 1.203, truth 1.105
Conditional odds ratio, oxygen : estimate 0.413, truth 0.449
Marginal odds ratio, everyone : estimate 0.662, truth 0.671
Odds ratio of a model without the interaction: 0.570
oxygen patients patient_or or_of_means mean_of_rd rd_of_means
0 1655 1.105 1.099 0.009 0.009
1 1345 0.449 0.490 -0.146 -0.146

The model estimates conditional odds ratios of 1.203 on room air and 0.413 on oxygen, against true values of 1.105 and 0.449. The marginal odds ratio is 0.662, against a true 0.671. The model without the interaction reports 0.570, which matches none of them, because it forces one conditional odds ratio onto two groups whose true values are 1.105 and 0.449.

The answer-key table shows a conditional and a marginal odds ratio that differ with no bias at all. The simulation multiplies the odds of death of every one of the 1,345 patients on oxygen by 0.449, and yet the odds ratio of that group’s two mean risks is 0.490, closer to 1. On room air the pair is 1.105 and 1.099. The odds ratio is non-collapsible: when the patients of a group start from different baseline risks, and age and CRP spread those risks widely here, the odds ratio of the averaged risks differs from the odds ratio that every patient shares. In a randomized trial, too, the odds ratio adjusted for a strong predictor of the outcome differs from the unadjusted one for this reason, although nothing is confounded. The risk difference does not behave this way. The mean of the individual differences equals the difference of the mean risks, −0.146 on oxygen and 0.009 on room air, and the cohort value of −0.061 is the average of the two, weighted by 1,345 and 1,655 patients. This is the reason to report standardized risks with their difference or ratio. When an odds ratio is required, say whether it is conditional or marginal, and conditional on what.

The average treatment effect is one estimand. A second one asks what the steroid did for the patients who received it: their risk as treated, against the risk that the same patients would have had without the drug. This is the average treatment effect in the treated. G-computation needs one change, which is that step 3 averages over the 1,130 treated patients only. The model is still fitted to the whole cohort, because the untreated patients are the source of information about the risk without the drug. The bootstrap above already stored these averages for each resample.

truth_att <- ContrastRisks(mean(cohort$risk_treated[treated]),
mean(cohort$risk_untreated[treated]))
g_comp_att <- StandardizeFit(outcome_fit, cohort[treated, ])
print(round(SummarizeBootstrap(g_comp_att, boot_att, truth_att), 3))
me_att <- avg_comparisons(outcome_fit, variables = "steroid",
newdata = subset(cohort, steroid == 1))
cat(sprintf("avg_comparisons on the treated: %.3f, 95%% CI [%.3f, %.3f]\n",
me_att$estimate, me_att$conf.low, me_att$conf.high))
cat(sprintf("Observed risk in the %d treated patients: %.3f\n",
sum(treated), mean(cohort$died_28d[treated])))
cat(sprintf("On oxygen: %.2f of the treated, %.2f of the cohort\n",
mean(cohort$oxygen[treated]), mean(cohort$oxygen)))
estimate se lower upper truth
risk_1 0.214 0.012 0.188 0.237 0.221
risk_0 0.331 0.017 0.299 0.366 0.331
risk_diff -0.117 0.020 -0.157 -0.078 -0.110
risk_ratio 0.646 0.047 0.558 0.739 0.668
odds_ratio 0.550 0.056 0.449 0.665 0.574
avg_comparisons on the treated: -0.117, 95% CI [-0.157, -0.077]
Observed risk in the 1130 treated patients: 0.214
On oxygen: 0.72 of the treated, 0.45 of the cohort

The estimated effect in the treated is −0.117, against a true value of −0.110. Its bootstrap interval runs from −0.157 to −0.078 in R and from −0.160 to −0.076 in Python, and avg_comparisons() gives the same estimate when newdata holds the treated patients. The effect in the treated is almost twice the effect in the whole cohort, −0.062, because the treated are a different mix of patients: 72% of them were on oxygen, where the drug works, against 45% of the cohort. Neither number corrects the other. A hospital that asks whether its past prescribing saved lives wants the effect in the treated, and a guideline that would give the drug to every admitted patient wants the average treatment effect. The standardized risk under treatment, 0.214, equals the observed risk of the treated patients. A logistic regression with a treatment term fits risks that add up to the observed deaths among the treated, so for this estimand the model supplies only the missing half, the risk of the treated patients without the drug, 0.331.

G-computation is only as good as its outcome model. This section breaks the model by dropping the interaction and by dropping age, a confounder, and brings in two estimators that use a model for the treatment. Inverse probability weighting, the subject of the propensity scores page, weights each patient by the inverse of the fitted probability of the treatment received and uses no outcome model. Augmented inverse probability weighting (AIPW) uses both models. It starts from the g-computation prediction of each patient and adds the observed outcome minus the prediction, divided by the probability of the treatment received, for the patients who received that treatment. When the outcome model is right, these corrections average to about zero. When the outcome model is wrong and the treatment model is right, they remove the error. This property is called double robustness. Apart from the model without the interaction, each wrong model in the table leaves out age. The error column is the risk difference of the row minus the true risk difference, both as printed.

#' Estimate the two risks by inverse probability weighting.
#'
#' @param data The cohort.
#' @param treatment_formula The model of the probability of treatment.
#' @return The vector that ContrastRisks() returns.
WeightRisks <- function(data, treatment_formula) {
score <- fitted(glm(treatment_formula, family = binomial, data = data))
weight_1 <- data$steroid / score
weight_0 <- (1 - data$steroid) / (1 - score)
ContrastRisks(sum(weight_1 * data$died_28d) / sum(weight_1),
sum(weight_0 * data$died_28d) / sum(weight_0))
}
#' Estimate the two risks by augmented inverse probability weighting.
#'
#' @param data The cohort.
#' @param outcome_formula The outcome model.
#' @param treatment_formula The model of the probability of treatment.
#' @return The vector that ContrastRisks() returns.
AugmentedRisks <- function(data, outcome_formula, treatment_formula) {
fit <- glm(outcome_formula, family = binomial, data = data)
pred_1 <- predict(fit, transform(data, steroid = 1), type = "response")
pred_0 <- predict(fit, transform(data, steroid = 0), type = "response")
score <- fitted(glm(treatment_formula, family = binomial, data = data))
correction_1 <- data$steroid * (data$died_28d - pred_1) / score
correction_0 <- (1 - data$steroid) * (data$died_28d - pred_0) /
(1 - score)
ContrastRisks(mean(pred_1 + correction_1), mean(pred_0 + correction_0))
}
outcome_no_age <- died_28d ~ steroid * oxygen + crp_mg_l
treatment_formula <- steroid ~ age + oxygen + crp_mg_l
treatment_no_age <- steroid ~ oxygen + crp_mg_l
score <- fitted(glm(treatment_formula, family = binomial, data = cohort))
cat(sprintf("Fitted probability of treatment: %.3f to %.3f\n", min(score),
max(score)))
no_age_fit <- glm(outcome_no_age, family = binomial, data = cohort)
estimates <- rbind(
"Truth" = truth,
"Crude" = crude,
"G-computation" = g_comp,
"G-computation, no interaction" = StandardizeFit(single_fit, cohort),
"G-computation, no age" = StandardizeFit(no_age_fit, cohort),
"Weighting" = WeightRisks(cohort, treatment_formula),
"Weighting, no age" = WeightRisks(cohort, treatment_no_age),
"AIPW" = AugmentedRisks(cohort, outcome_formula, treatment_formula),
"AIPW, outcome model no age" = AugmentedRisks(cohort, outcome_no_age,
treatment_formula),
"AIPW, treatment model no age" = AugmentedRisks(cohort, outcome_formula,
treatment_no_age),
"AIPW, both models no age" = AugmentedRisks(cohort, outcome_no_age,
treatment_no_age)
)
comparison <- round(
data.frame(estimates[, c("risk_1", "risk_0", "risk_diff")]), 3
)
comparison$error <- comparison$risk_diff - comparison["Truth", "risk_diff"]
print(comparison)
att_no_interaction <- StandardizeFit(single_fit, cohort[treated, ])
cat(sprintf("Effect in the treated: %.3f without the interaction, %.3f %s\n",
att_no_interaction[["risk_diff"]], g_comp_att[["risk_diff"]],
"with it"))
Fitted probability of treatment: 0.029 to 0.972
risk_1 risk_0 risk_diff error
Truth 0.158 0.218 -0.061 0.000
Crude 0.214 0.148 0.066 0.127
G-computation 0.155 0.217 -0.062 -0.001
G-computation, no interaction 0.140 0.208 -0.068 -0.007
G-computation, no age 0.179 0.194 -0.015 0.046
Weighting 0.158 0.228 -0.070 -0.009
Weighting, no age 0.181 0.198 -0.017 0.044
AIPW 0.161 0.224 -0.063 -0.002
AIPW, outcome model no age 0.159 0.224 -0.065 -0.004
AIPW, treatment model no age 0.158 0.219 -0.061 0.000
AIPW, both models no age 0.181 0.195 -0.014 0.047
Effect in the treated: -0.093 without the interaction, -0.117 with it

With both models right, the three methods agree. G-computation, weighting and AIPW give −0.062, −0.070 and −0.063, all within 0.009 of the true −0.061. Leaving age out of the outcome model moves g-computation to −0.015, an error of 0.046, three times its bootstrap standard error. Leaving age out of the treatment model does the same to weighting, which gives −0.017. Each method fails with its own model. AIPW gives −0.065 with that wrong outcome model and −0.061 with that wrong treatment model, so it needs only one of the two to be right. The last row shows the limit of the protection: with age missing from both models, AIPW returns −0.014, as far off as the others. Double robustness guards against one wrong model and does nothing about a confounder that nobody measured, because that variable is missing from both.

The model without the interaction fails in a less visible way. Its risk difference, −0.068, is within 0.007 of the truth, but its two standardized risks, 0.140 and 0.208, sit further from the true 0.158 and 0.218. Its effect in the treated is −0.093, where the model with the interaction gave −0.117 and the truth is −0.110. A model that is wrong about effect modification can come close for one estimand and miss another.

Each estimate above equals a causal effect only under conditions that no output on this page can confirm. No unmeasured confounding means that, among patients of the same age, oxygen status and CRP, the treated and the untreated would have had the same risk under the same treatment. The simulation was built that way. If clinicians had also judged frailty at the bedside and nobody had recorded it, no model of these columns could remove it, and the rows with age missing from both models show the size of error that one missing confounder can produce.

Positivity means that every kind of patient in the cohort could have received either treatment. The fitted probabilities of treatment run from 0.029 to 0.972, so no fitted probability is close to 0 or 1. The range alone does not show overlap within every covariate stratum, and a probability of 0.029 already gives an inverse probability weight above 30. Where a group is always treated, the outcome model still predicts its risk without treatment, from no observed patient, and g-computation prints no warning. Consistency means that steroid = 1 is one well-defined treatment. One drug at one dose, started on the day of admission, meets that. A column that mixes drugs, doses and start days does not, and “the risk if everyone were treated” then has no single meaning.

A correct outcome model is the fourth condition. A model can fit the observed outcomes well and still be wrong about the contrast between treatments. Set g-computation beside a weighting or AIPW estimate, as above, since a clear disagreement between methods that rely on different models means that one of the models is wrong.

Do not report the treatment coefficient of the logistic model as the effect in the population. The model without an interaction gives an odds ratio of 0.570, the marginal odds ratio is 0.662, and the risk ratio is 0.714. Standardize, and report the two risks with their difference.

Do not bootstrap after the model is fitted. Resampling the predictions of one fitted model gave a standard error of 0.0017 where the full procedure gave about 0.015. Every step that used the data, including any choice of variables, belongs inside the resampling loop.

Do not standardize to a population other than the one in the estimand. From one model, the average over the treated gave −0.117 and the average over everyone gave −0.062. A prediction for one patient with average covariates is a third quantity, and it is not the average of the patients’ risks.

Do not read agreement between g-computation and weighting as evidence against unmeasured confounding. Both use the same measured covariates, and a missing confounder biases both in the same direction.

Snowden, Rose, and Mortimer, 2011 give a step-by-step demonstration of g-computation on a simulated data set and contrast it with traditional regression.

Arel-Bundock, Greifer, and Heiss, 2024 describe how to interpret statistical models with the marginaleffects package for R and Python.

Greenland, Pearl, and Robins, 1999 review confounding and collapsibility under a counterfactual model and distinguish confounding from noncollapsibility.

Bang and Robins, 2005 construct doubly robust estimators for missing data and causal inference models.

Causal Inference: What If by Hernán and Robins is free to download. Its chapter on standardization and the parametric g-formula covers the method of this page, and its chapter on effect modification explains why an average effect depends on the population that it averages over.

The marginaleffects chapter on g-computation shows avg_predictions() and avg_comparisons() for the average treatment effect, the effect in the treated and the effect in the untreated.

The statsmodels treatment effects documentation describes TreatmentEffect, which offers regression adjustment, inverse probability weighting and doubly robust estimators with standard errors.

The propensity scores page covers balance checks, weights and matching for the treatment model that the weighting and AIPW rows use. The standardization page averages over strata in place of a model, and the confounding and causal diagrams page helps to decide which covariates belong in the outcome model. For a treatment that changes over time, continue with the marginal structural models page.