# G-computation and standardisation
# https://tidyecology.com/posts/g-computation-and-standardisation/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-10-14

## ---- setup ----
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", message = FALSE, warning = FALSE,
                      dev = "png", dpi = 110, fig.width = 8, fig.height = 4.4)
library(ggplot2)

te <- list(ink="#16241d", body="#2c3a31", forest="#275139", label="#46604a",
           sage="#93a87f", paper="#f5f4ee", line="#dad9ca", faint="#5d6b61",
           low="#c9b458", high="#1d5b4e", grazed="#cda23f", mown="#2f8f63", abandoned="#b5534e")
theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(plot.background = element_rect(fill = te$paper, colour = NA),
          panel.background = element_rect(fill = te$paper, colour = NA),
          panel.grid.major = element_line(colour = te$line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          axis.text = element_text(colour = te$faint), axis.title = element_text(colour = te$body),
          plot.title = element_text(colour = te$ink, face = "bold"),
          plot.subtitle = element_text(colour = te$body),
          legend.text = element_text(colour = te$body), legend.title = element_text(colour = te$body),
          strip.text = element_text(colour = te$ink, face = "bold"),
          plot.margin = margin(10, 12, 10, 10))
}
expit <- function(z) 1 / (1 + exp(-z))

## ---- dgp ----
b0 <- -0.5; bD <- log(2.5); b1 <- 1.0; b2 <- 0.8; b3 <- 0.7   # outcome model
a0 <- -0.4; a1 <- 0.8; a2 <- 0.5; a3 <- 0.6                    # treatment model (confounding)

gen <- function(n) {
  x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rbinom(n, 1, 0.5)
  d  <- rbinom(n, 1, expit(a0 + a1*x1 + a2*x2 + a3*x3))
  y  <- rbinom(n, 1, expit(b0 + bD*d + b1*x1 + b2*x2 + b3*x3))
  data.frame(y, d, x1, x2, x3)
}

# true SAMPLE-marginal effect (uses the known coefficients on this covariate set)
true_marg <- function(dat) {
  p1 <- expit(b0 + bD*1 + b1*dat$x1 + b2*dat$x2 + b3*dat$x3)
  p0 <- expit(b0 + bD*0 + b1*dat$x1 + b2*dat$x2 + b3*dat$x3)
  m1 <- mean(p1); m0 <- mean(p0)
  c(RD = m1 - m0, RR = m1 / m0, OR = (m1/(1-m1)) / (m0/(1-m0)))
}

set.seed(166)
n <- 2000
dat <- gen(n)
c(prev_D = mean(dat$d), prev_Y = mean(dat$y))

## ---- truth ----
tm <- true_marg(dat)
round(tm, 4)                # marginal risk difference, risk ratio, odds ratio

## ---- naive-adjusted ----
m_naive <- glm(y ~ d, family = binomial, data = dat)
OR_naive <- exp(coef(m_naive)["d"])
ci_naive <- exp(coef(m_naive)["d"] + c(-1, 1) * 1.96 * summary(m_naive)$coef["d", "Std. Error"])

m_adj <- glm(y ~ d + x1 + x2 + x3, family = binomial, data = dat)
OR_cond <- exp(coef(m_adj)["d"])
ci_cond <- exp(coef(m_adj)["d"] + c(-1, 1) * 1.96 * summary(m_adj)$coef["d", "Std. Error"])

c(OR_naive = OR_naive, OR_conditional = OR_cond)

## ---- gcomp ----
gcomp <- function(model, dat) {
  d1 <- transform(dat, d = 1); d0 <- transform(dat, d = 0)
  mu1 <- predict(model, d1, type = "response")
  mu0 <- predict(model, d0, type = "response")
  m1 <- mean(mu1); m0 <- mean(mu0)
  list(RD = m1 - m0, RR = m1 / m0, OR = (m1/(1-m1)) / (m0/(1-m0)),
       mu1 = mu1, mu0 = mu0, d1 = d1, d0 = d0)
}
g <- gcomp(m_adj, dat)
c(RD = g$RD, RR = g$RR, OR = g$OR)

## ---- fig-or ----
set.seed(1660)
B <- 1000; bs_or <- numeric(B)
for (b in 1:B) {
  idx <- sample.int(n, n, replace = TRUE); db <- dat[idx, ]
  mb <- glm(y ~ d + x1 + x2 + x3, family = binomial, data = db)
  bs_or[b] <- gcomp(mb, db)$OR
}
ci_OR_boot <- quantile(bs_or, c(.025, .975))

lev <- c("g-computation (marginal OR)", "adjusted (conditional OR)", "naive (unadjusted)")
est_df <- data.frame(
  label = factor(c("naive (unadjusted)", "adjusted (conditional OR)", "g-computation (marginal OR)"), levels = lev),
  or = c(OR_naive, OR_cond, g$OR),
  lo = c(ci_naive[1], ci_cond[1], ci_OR_boot[1]),
  hi = c(ci_naive[2], ci_cond[2], ci_OR_boot[2]),
  kind = c("naive", "conditional", "marginal"))

ggplot(est_df, aes(or, label, colour = kind)) +
  geom_vline(xintercept = exp(bD), linetype = "dashed", colour = te$label) +
  geom_vline(xintercept = tm["OR"], linetype = "dotted", colour = te$forest) +
  geom_pointrange(aes(xmin = lo, xmax = hi), linewidth = 0.9, size = 0.7) +
  annotate("text", x = exp(bD), y = 3.42, label = "true conditional OR 2.5", hjust = -0.05, size = 3, colour = te$label) +
  annotate("text", x = tm["OR"], y = 0.62, label = "true marginal OR 1.97", hjust = 1.05, size = 3, colour = te$forest) +
  scale_colour_manual(values = c(naive = te$abandoned, conditional = te$grazed, marginal = te$mown), guide = "none") +
  scale_x_log10(breaks = c(1.5, 2, 2.5, 3, 4, 5, 6)) +
  expand_limits(x = 1.5) +
  labs(x = "odds ratio (log scale)", y = NULL,
       title = "Adjusting removes confounding, not non-collapsibility",
       subtitle = "Naive is confounded; the conditional OR exceeds the marginal (population) OR") +
  theme_te() + theme(plot.title.position = "plot")

## ---- rd-se ----
gcomp_rd_se <- function(model, g) {
  X1 <- model.matrix(delete.response(terms(model)), g$d1)
  X0 <- model.matrix(delete.response(terms(model)), g$d0)
  grad <- colMeans(g$mu1*(1-g$mu1)*X1) - colMeans(g$mu0*(1-g$mu0)*X0)
  sqrt(as.numeric(t(grad) %*% vcov(model) %*% grad))
}
se_delta <- gcomp_rd_se(m_adj, g)
ci_delta <- g$RD + c(-1, 1) * 1.96 * se_delta

set.seed(1660)                    # same stream as the OR bootstrap above
bs_rd <- numeric(B)
for (b in 1:B) {
  idx <- sample.int(n, n, replace = TRUE); db <- dat[idx, ]
  mb <- glm(y ~ d + x1 + x2 + x3, family = binomial, data = db)
  bs_rd[b] <- gcomp(mb, db)$RD
}
c(delta_SE = se_delta, boot_SE = sd(bs_rd))
round(rbind(delta = ci_delta, bootstrap = quantile(bs_rd, c(.025, .975))), 4)

## ---- mc ----
set.seed(20260728)
nsim <- 1000
est_g <- est_naive <- tr_i <- numeric(nsim)
cov_g <- cov_naive <- 0L
for (s in 1:nsim) {
  ds <- gen(n)
  tms <- true_marg(ds)["RD"]; tr_i[s] <- tms
  ms <- glm(y ~ d + x1 + x2 + x3, family = binomial, data = ds)
  gs <- gcomp(ms, ds); est_g[s] <- gs$RD
  se <- gcomp_rd_se(ms, gs)
  if (tms >= gs$RD - 1.96*se && tms <= gs$RD + 1.96*se) cov_g <- cov_g + 1L
  p1 <- mean(ds$y[ds$d == 1]); p0 <- mean(ds$y[ds$d == 0])
  n1 <- sum(ds$d == 1); n0 <- sum(ds$d == 0)
  est_naive[s] <- p1 - p0
  sen <- sqrt(p1*(1-p1)/n1 + p0*(1-p0)/n0)
  if (tms >= (p1-p0) - 1.96*sen && tms <= (p1-p0) + 1.96*sen) cov_naive <- cov_naive + 1L
}
mtruth <- mean(tr_i)
data.frame(estimator = c("g-computation", "naive"),
           mean_RD = c(mean(est_g), mean(est_naive)),
           bias = c(mean(est_g) - mtruth, mean(est_naive) - mtruth),
           coverage = c(cov_g, cov_naive) / nsim)

## ---- fig-mc ----
ggplot(rbind(data.frame(rd = est_g, est = "g-computation"),
             data.frame(rd = est_naive, est = "naive (unadjusted)")),
       aes(rd, fill = est, colour = est)) +
  geom_density(alpha = 0.35, linewidth = 0.7) +
  geom_vline(xintercept = mtruth, linetype = "dashed", colour = te$ink) +
  annotate("text", x = mtruth, y = Inf, label = "true marginal risk difference",
           vjust = 1.6, hjust = -0.03, size = 3, colour = te$ink) +
  scale_fill_manual(values = c("g-computation" = te$mown, "naive (unadjusted)" = te$abandoned), name = NULL) +
  scale_colour_manual(values = c("g-computation" = te$forest, "naive (unadjusted)" = te$abandoned), name = NULL) +
  labs(x = "estimated risk difference", y = "density",
       title = "Standardisation is unbiased for the marginal risk difference",
       subtitle = "1000 datasets: g-computation centres on the truth, the naive difference does not") +
  theme_te() + theme(legend.position = "top")
