Causal Methods
CHAPTER 05
G-comp

G-computation

Estimates causal effects by modelling the outcome, predicting it for every unit under each treatment regime, and averaging over the covariate distribution. The standardization step is what converts a fitted regression into a marginal effect. The simplest of the g-methods.[2]

IDENTIFICATION SETUP

G-computation shares its identification assumptions with matching and IPW. It is not a different identification strategy, it is a different estimation route to the same estimand. Those methods model the treatment; g-computation models the outcome. That distinction is the whole point: the two fail for different reasons, which is the observation the doubly robust estimators are built on.

01: Fit

Regress the outcome on treatment and all confounders, using whatever link the outcome demands. This model is fit once, on the observed data, exactly as it stands.

02: Predict

Build two copies of the full sample, one with treatment set to 1 for everyone, one set to 0, and predict the outcome for every unit under both regimes. Nobody is dropped.

03: Standardize

Average the two predicted vectors and take the contrast. Averaging over the full covariate distribution gives the ATE; averaging over the treated only gives the ATT.

THE STANDARDIZATION PROCEDURE

OBSERVED1: FIT2-3: PREDICT4: STANDARDIZEY, A, Las observedE[Y|A,L]outcome modelset A = 1predict for allset A = 0predict for allE[Y¹] − E[Y⁰]marginal effectevery unit is predicted under both regimes, nobody is dropped
E[Ya] = Σl E[Y | A = a, L = l] · P(L = l)the g-formula for a point treatment
ASSUMPTIONS
Conditional exchangeabilityrequired

Treatment is as good as randomly assigned within levels of the measured confounders. Identical to the ignorability assumption behind matching and IPW, and equally untestable.

HOW TO CHECK

Argue it from a DAG, not from the data. Report a sensitivity analysis quantifying how strong an unmeasured confounder would have to be to overturn the result.

Positivityrequired

Every covariate stratum must contain both treated and untreated units. G-computation does not need this to compute an answer, which is precisely the danger, it will extrapolate into empty strata without complaint.

HOW TO CHECK

Fit a propensity score purely as a diagnostic and inspect its support in both arms. Cross-tabulate treatment against every categorical confounder and look for empty cells.

Consistency / well-defined interventionrequired

The counterfactual Yᵃ must correspond to a real intervention that sets A = a. If 'treatment' bundles several distinct versions with different effects, the predicted quantity has no single interpretation.

HOW TO CHECK

State the intervention in protocol terms. If you cannot describe the trial you are emulating, the estimand is ambiguous before any modelling begins.

Correct outcome modelmodelling choice

This is where g-computation carries its risk, in place of IPW's dependence on a correct propensity model. Misspecification biases the standardized contrast directly, and the model is being asked to predict in regions it may not have seen.

HOW TO CHECK

Compare specifications, including flexible ones with treatment-covariate interactions. Substantial movement in the standardized estimate signals dependence on functional form.

DATA REQUIREMENTS

Measured confounders

Every common cause of treatment and outcome must be observed and included in the outcome model. No amount of modelling flexibility substitutes for a confounder you did not collect.

Support in both arms

Both treated and untreated units at every level of the confounders. Sparse or empty strata are where the outcome model quietly switches from interpolating to extrapolating.

Any outcome type

Binary, continuous, count, or time-to-event, whatever the outcome model can represent. Binary outcomes are the common case in health research, and the one where non-collapsibility matters most.

ESTIMATION

The estimator is the four steps above, implemented directly. Note what is absent: no propensity score, no weights, no units discarded. Every observation contributes a prediction under both regimes.[1]

01_g_computation.R
# Expects: data with outcome, treated, and all confounders in covars

library(tidyverse)

# ── G-computation (standardization) for a point treatment ──

# Step 1: fit an outcome model conditioning on treatment AND confounders
fit_out <- glm(
  outcome ~ treated + age + income + education + covar_4,
  data = data,
  family = binomial  # use gaussian() for a continuous outcome
)

# Step 2: build two counterfactual copies of the FULL sample,
#         one with everyone treated, one with everyone untreated
data_1 <- mutate(data, treated = 1)
data_0 <- mutate(data, treated = 0)

# Step 3: predict the outcome for every unit under each regime
mu1 <- predict(fit_out, newdata = data_1, type = "response")
mu0 <- predict(fit_out, newdata = data_0, type = "response")

# Step 4: standardize, average over the covariate distribution
ate <- mean(mu1) - mean(mu0)
cat("ATE (risk difference):", round(ate, 4), "\n")
cat("Marginal risk ratio: ", round(mean(mu1) / mean(mu0), 4), "\n")

# ATT: average over the covariate distribution of the TREATED only
att <- mean(mu1[data$treated == 1]) - mean(mu0[data$treated == 1])
cat("ATT:", round(att, 4), "\n")

Marginal, not conditional

The treatment coefficient in a logistic outcome model is a conditional odds ratio, and because the OR is non-collapsible it does not equal the marginal OR even with no confounding whatsoever. Standardizing is what converts the fitted model into the marginal contrast you actually want to report. Reading the coefficient off the regression is the mistake this procedure exists to prevent.[3]

Interactions come free

Because the effect is computed by prediction rather than read off a coefficient, treatment-covariate interactions in the outcome model need no special handling. Add them and the standardized contrast is still a valid marginal effect, no reparameterization required.

INTERACTIONS & SUBGROUP EFFECTS

02_interactions.R
# Because the effect is computed by PREDICTION rather than read off a
# coefficient, treatment-covariate interactions need no special handling.
# Add them and the standardized contrast is still a valid marginal effect.

fit_int <- glm(
  outcome ~ treated * (age + income + education) + covar_4,
  data = data,
  family = binomial
)

mu1 <- predict(fit_int, newdata = mutate(data, treated = 1), type = "response")
mu0 <- predict(fit_int, newdata = mutate(data, treated = 0), type = "response")

cat("ATE with interactions:", round(mean(mu1) - mean(mu0), 4), "\n")

# Subgroup effects fall out of the same predicted vectors, no refit needed
data |>
  mutate(ite = mu1 - mu0) |>
  group_by(education) |>
  summarise(effect = mean(ite), n = n())
DIAGNOSTICS & INFERENCE

Bootstrap, not model SEs

The standard error on the treatment coefficient is not the standard error of the standardized estimate, it ignores the averaging step entirely. Bootstrap the whole procedure, refitting the outcome model inside every replicate, and report percentile intervals.

It extrapolates silently

The failure mode to know. Where positivity is violated, IPW announces the problem through explosive weights; g-computation simply predicts into the empty region and returns a confident-looking number. Check propensity score support even though you never use the propensity score to estimate.

Specification sensitivity

Re-estimate under several outcome models, including one with treatment-covariate interactions and one more flexible than your primary specification. Large movement in the standardized estimate means the result is being driven by functional form rather than by the data.

Compare against IPW

Run the weighted estimator on the same data. Agreement is reassuring because the two rely on different models being correct; divergence tells you at least one of them is misspecified, and is worth reporting rather than hiding.

BOOTSTRAP INFERENCE & POSITIVITY CHECK

03_bootstrap.R
library(boot)

# Model-based SEs are wrong here: they ignore the standardization step.
# Bootstrap the ENTIRE procedure, refitting the outcome model each time.
gcomp_est <- function(d, i) {
  b <- d[i, ]
  f <- glm(outcome ~ treated + age + income + education + covar_4,
            data = b, family = binomial)
  m1 <- predict(f, newdata = mutate(b, treated = 1), type = "response")
  m0 <- predict(f, newdata = mutate(b, treated = 0), type = "response")
  mean(m1) - mean(m0)
}

bs <- boot(data, gcomp_est, R = 1000)
boot.ci(bs, type = "perc")  # percentile CI

# Positivity check: g-computation extrapolates silently where IPW
# would warn you with explosive weights, so inspect PS support.

ps <- fitted(glm(treated ~ age + income + education + covar_4,
                 data = data, family = binomial))

cat("PS range, treated:", range(ps[data$treated == 1]), "\n")
cat("PS range, control:", range(ps[data$treated == 0]), "\n")

# Any region of covariate space with only one arm present is a region
# where the outcome model is extrapolating rather than interpolating.
tibble(ps = ps, treated = data$treated) |>
  mutate(bin = cut(ps, breaks = seq(0, 1, 0.1))) |>
  count(bin, treated) |>
  pivot_wider(names_from = treated, values_from = n, values_fill = 0)
OUTPUT INTERPRETATION

Why not just report the treatment coefficient from the outcome model?

Because for a non-linear link that coefficient is a conditional effect, and the odds ratio is non-collapsible: the conditional and marginal ORs differ even when there is no confounding at all. Adding a covariate to a logistic model moves the treatment OR for reasons that have nothing to do with bias. Standardization is what produces the marginal quantity a policy audience can actually use.[3]

My g-computation and IPW estimates disagree, which do I report?

Report both and treat the gap as evidence rather than an inconvenience. IPW is consistent if the treatment model is right; g-computation if the outcome model is right. Divergence means at least one is misspecified. This is the situation the doubly robust estimators were designed for, so the disciplined response is to run AIPW or TMLE and lead with that.[2]

Can I use machine learning for the outcome model?

You can fit it, but naive plug-in ML breaks the inference: regularization bias enters the standardized estimate and the bootstrap will not repair it. Using flexible learners for the nuisance model is exactly what TMLE and the cross-fitted DR estimators are constructed to handle, so route through those rather than swapping a GLM for a black box here.

Does this handle time-varying treatments?

Not in the form on this page. Everything above is the point-treatment case. When treatment and confounders both evolve over follow-up, so that a confounder is simultaneously a mediator of earlier treatment, standard adjustment breaks down and the procedure generalizes to the longitudinal g-formula. That extension is beyond the scope of this page.[2][2]

WHERE THIS LEADS

IPW is consistent when the treatment model is right. G-computation is consistent when the outcome model is right. Neither protects you if you picked the wrong one. Combining both scores yields an estimator consistent if either model is correct, which is the idea behind AIPW, and behind TMLE, which reaches the same efficient score from the targeted-learning side. This page and matching & IPW are the two halves of the setup those pages assume.

REFERENCES
[1]

Implementation of G-computation on a simulated data set: demonstration of a causal inference technique

Snowden, J. M., Rose, S. & Mortimer, K. M. (2011)

American Journal of Epidemiology, 173(7), 731–738

doi →
[2]

An introduction to g methods

Naimi, A. I., Cole, S. R. & Kennedy, E. H. (2017)

International Journal of Epidemiology, 46(2), 756–762

doi →
[3]

Making apples from oranges: comparing noncollapsible effect estimators and their standard errors after adjustment for different covariate sets

Daniel, R., Zhang, J. & Farewell, D. (2021)

Biometrical Journal, 63(3), 528–557

doi →

Built as a learning tool and working reference for developing knowledge and coding practices across causal inference and causal ML. The author is actively building expertise, and therefore this should not be taken as an authoritative source. Drafted with assistance from Claude (Anthropic) for prose and code scaffolding; method selection, technical claims, and every citation above were reviewed by the author.