---
title: "Different learners, the same estimate?"
subtitle: "An R companion to Susan’s Causal Roadmap tutorial"
output:
  html_document:
    self_contained: true
    mathjax: null
    toc: true
---

Susan asks how five-year mortality would change under a shorter radiation schedule for older or frailer patients eligible for either schedule. A negative risk difference means fewer deaths under the shorter schedule. The main roadmap’s primary outcome is restricted mean survival time through five years, the average time alive during that window. This exercise uses a fully ascertained binary outcome so every step can be checked by hand.

Open this file in RStudio and select **Knit**, or run `rmarkdown::render("analysis.Rmd")` in its directory. All data are synthetic. The estimators use base R. The tables use **knitr**.

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, collapse = FALSE, error = FALSE, comment = "#>")
options(knitr.kable.NA = "")
```

## Terms used in the calculations

| Term | Meaning in this example |
| --- | --- |
| Estimand, estimator, estimate | The estimand specifies the schedules, outcome, time horizon, population and contrast Susan wants to compare. The estimator is the rule for combining the records. The estimate is the resulting number. |
| Base learner and meta-learner | A base learner fits a prediction, such as a regression for mortality. A meta-learner arranges prediction fits to estimate how a treatment effect varies. |
| Outcome model and propensity | The outcome model predicts mortality for a given schedule and frailty. The propensity is the chance of receiving the short schedule at that frailty. Both help estimate the causal contrast. |
| Standardization | Average predicted risks for both schedules using the same patients and the same frailty mix. |
| Cross-fitting | Fit the prediction models on other folds and predict for the held-out records. Rotate until each record has predictions from models trained without it. |

## The records Susan has

The 5,000 training records contain baseline frailty (`L`, 1 for higher), received schedule (`A`, 1 for short), and death by five years (`Y`, 1 for death). The causal interpretation assumes consistent treatment definitions, exchangeability given baseline frailty, and both schedules available in each target stratum. These are features of the teaching example. Applying it to clinical records would require clinical justification.

```{r counts}
cells <- data.frame(
  L = c(0L, 0L, 1L, 1L), A = c(0L, 1L, 0L, 1L),
  patients = c(900L, 2100L, 1500L, 500L),
  deaths = c(180L, 462L, 600L, 125L)
)
expand_records <- function(cells) {
  data.frame(
    L = rep(cells$L, cells$patients),
    A = rep(cells$A, cells$patients),
    Y = as.integer(sequence(cells$patients) <= rep(cells$deaths, cells$patients))
  )
}
train <- expand_records(cells)
profiles <- data.frame(L = 0:1)
profile_names <- c("Lower frailty", "Higher frailty")
stopifnot(nrow(train) == 5000L)
knitr::kable(cells)
```

The crude comparison uses the two groups as observed. More higher-frailty people received the standard schedule.

```{r observed}
arm_risk <- tapply(train$Y, train$A, mean)
round(100 * c(standard = unname(arm_risk["0"]), short = unname(arm_risk["1"]),
              difference = unname(arm_risk["1"] - arm_risk["0"])), 2)
```

## S and T ask for the same two risks

The S-learner fits one logistic regression. The schedule-by-frailty interaction gives each arm its own intercept and slope. The T-learner fits a separate regression in each arm. Both predict each baseline profile under each schedule. The difference between those conditional mean risks estimates the **conditional average treatment effect** (CATE).

```{r two-risks}
s_full <- glm(Y ~ A * L, data = train, family = binomial())
s_shared <- glm(Y ~ A + L, data = train, family = binomial())
t_standard <- glm(Y ~ L, data = train, subset = A == 0L, family = binomial())
t_short <- glm(Y ~ L, data = train, subset = A == 1L, family = binomial())

risk <- function(fit, rows) unname(predict(fit, newdata = rows, type = "response"))
standard <- transform(profiles, A = 0L)
short <- transform(profiles, A = 1L)
s0 <- risk(s_full, standard)
s1 <- risk(s_full, short)
t0 <- risk(t_standard, profiles)
t1 <- risk(t_short, profiles)
shared0 <- risk(s_shared, standard)
shared1 <- risk(s_shared, short)

knitr::kable(data.frame(profile = profile_names,
  standard_pct = 100*t0, short_pct = 100*t1,
  S_difference_pp = 100*(s1 - s0), T_difference_pp = 100*(t1 - t0),
  shared_S_difference_pp = 100*(shared1 - shared0)), digits = 2)
stopifnot(max(abs(s0 - t0), abs(s1 - t1)) < 1e-6)
```

Under the unpenalized, fully interacted fit, the likelihood separates into the two arm-specific fits, so S and T agree. Removing the interaction gives both frailty groups a common schedule odds ratio. Read the lower-frailty row again. The estimated risk difference changes sign.

## One outcome per patient

The six display patients are held out of model fitting. Consistency tells Susan which potential outcome she observed. The paired outcome under the other schedule stays blank. The two predicted risks apply to people with that baseline profile.

```{r display-patients}
display <- data.frame(
  id = sprintf("P%02d", 1:6), L = c(0, 0, 0, 1, 1, 1),
  A = c(0, 1, 1, 1, 0, 0), Y = c(0, 0, 1, 1, 1, 0)
)
display$observed_under_standard <- ifelse(display$A == 0L, display$Y, NA_integer_)
display$observed_under_short <- ifelse(display$A == 1L, display$Y, NA_integer_)
display$risk_standard <- risk(t_standard, display)
display$risk_short <- risk(t_short, display)
knitr::kable(display, digits = 2)
```

## X brings the observed outcome back

Künzel and colleagues call each **signed pseudo-outcome** an “imputed treatment effect.” In the short arm, subtract fitted standard risk from the observed outcome. In the standard arm, subtract the observed outcome from fitted short risk. The displays for higher-frailty deaths give +0.60 (P04) and −0.75 (P05). In the higher-frailty short training arm, 125 deaths contribute +0.60 each and 375 survivors contribute −0.40 each. Their mean is −0.15, or −15 percentage points for this group.

```{r x-learner}
signed_pseudo_outcome <- function(rows) {
  observed <- rows[["Y"]]
  ifelse(rows[["A"]] == 1L, observed - risk(t_standard, rows),
                           risk(t_short, rows) - observed)
}
train$D <- signed_pseudo_outcome(train)
display$D <- signed_pseudo_outcome(display)
stopifnot(abs(display$D[4] - 0.60) < 1e-6,
          abs(display$D[5] + 0.75) < 1e-6)

x_standard <- lm(D ~ L, data = train, subset = A == 0L)
x_short <- lm(D ~ L, data = train, subset = A == 1L)
tau0 <- unname(predict(x_standard, profiles))
tau1 <- unname(predict(x_short, profiles))
e <- risk(glm(A ~ L, data = train, family = binomial()), profiles)
tau_x <- e*tau0 + (1 - e)*tau1
knitr::kable(data.frame(profile = profile_names, probability_short = e,
  from_standard_pp = 100*tau0, from_short_pp = 100*tau1,
  X_difference_pp = 100*tau_x), digits = 2)
stopifnot(max(abs(tau_x - (t1 - t0))) < 1e-6)
```

Here each stage fits a separate mean in each frailty stratum, so both second-stage fits reproduce the same conditional difference. Try the blend with two *hypothetical* second-stage predictions that disagree. At a probability of short of 0.25, the standard-arm fit gets weight 0.25. The short-arm fit uses the opposite arm’s prediction of standard risk.

```{r unequal-blend}
example_blend <- 0.25*(-0.02) + (1 - 0.25)*(-0.06)
stopifnot(abs(example_blend + 0.05) < 1e-8)
100*example_blend
```

## Whose average?

First standardize to all 5,000 eligible patients (ATE). Then use the baseline distribution of the 2,600 short-schedule recipients (ATT). Both sets of weights use the training cohort. Changing which six display patients are shown leaves these weights intact.

```{r standardization}
weights <- rbind(
  ATE = as.numeric(prop.table(table(train$L))),
  ATT = as.numeric(prop.table(table(train$L[train$A == 1L])))
)
risk_columns <- cbind(standard = t0, short = t1, S = s1 - s0,
  T = t1 - t0, X = tau_x, shared_S = shared1 - shared0)
estimates <- weights %*% risk_columns
knitr::kable(100*estimates, digits = 2,
  caption = "Two arm risks in percent, followed by four risk differences in percentage points.")
stopifnot(max(abs(estimates["ATE", c("S", "T", "X")] + 0.048)) < 1e-6,
          max(abs(estimates["ATT", c("S", "T", "X")] + 33/2600)) < 1e-6,
          abs(unname(arm_risk["1"] - arm_risk["0"]) + 0.0992307692) < 1e-6)
```

The fully interacted S, T and X fits each recover the observed risk contrast within each frailty group, **+2 points** at lower frailty and **−15 points** at higher frailty. For the all-eligible ATE, weighting those contrasts by 3,000/5,000 and 2,000/5,000 gives **−4.80 percentage points**. For the ATT, weighting them by the 2,100 lower- and 500 higher-frailty short recipients gives **−1.27 points**. The shared-log-odds S fit gives **−4.38 points** and **−4.12 points**, respectively.

## TMLE and double machine learning across the cohort

Targeted maximum likelihood estimation (TMLE) and cross-fitted augmented inverse probability weighting (AIPW) both estimate Susan’s all-eligible ATE. The AIPW calculation illustrates double machine learning (DML) for an interactive regression model (IRM), which allows separate risks by schedule. A partially linear DML comparison uses the same 5,000 records to estimate a residual slope.

### Target the difference with TMLE

The lower-frailty group contributes 3,000 records and the higher-frailty group contributes 2,000. Pool the schedules within each group to get a starting risk under either schedule. The starting cohort difference is zero. Estimate the probability of short, `e`, within each group. Construct the **clever covariate** `H`, equal to `1/e` on short and `-1/(1-e)` on standard. Use `H` as the single predictor in a logistic regression across all 5,000 records, with the initial log odds as an offset and no intercept. Its fitted coefficient is `epsilon`. Apply that update under both schedules in each group.

```{r targeting}
group <- train[["L"]] + 1L
arm <- train[["A"]]
observed <- train[["Y"]]
q_initial <- as.numeric(tapply(observed, group, mean))
g_full <- as.numeric(tapply(arm, group, mean))
h0 <- -1 / (1 - g_full)
h1 <- 1 / g_full
H <- ifelse(arm == 1L, h1[group], h0[group])
initial_log_odds <- qlogis(q_initial[group])
fluctuation <- glm(observed ~ 0 + H + offset(initial_log_odds),
                   family = binomial(), control = glm.control(epsilon = 1e-12))
epsilon <- unname(coef(fluctuation)[1])
qstar0 <- plogis(qlogis(q_initial) + epsilon * h0)
qstar1 <- plogis(qlogis(q_initial) + epsilon * h1)
qstar_obs <- ifelse(arm == 1L, qstar1[group], qstar0[group])
tmle_ate <- mean(qstar1[group] - qstar0[group])
score_before <- mean(H * (observed - q_initial[group]))
score_after <- mean(H * (observed - qstar_obs))
cohort_n <- as.numeric(table(group))
working_difference <- qstar1 - qstar0
group_error <- as.numeric(tapply(H * (observed - qstar_obs), group, mean))
knitr::kable(data.frame(profile_names, cohort_n, 100*g_full, 100*q_initial,
                       100*qstar0, 100*qstar1, 100*working_difference), digits = 2,
             col.names = c("Frailty", "Patients", "Received short (%)", "Starting risk (%)",
                           "Updated standard (%)", "Updated short (%)", "Difference (pp)"))
stopifnot(abs(epsilon + 0.049149193627) < 1e-9, abs(score_before + 0.048) < 1e-9,
          abs(score_after) < 1e-9, abs(tmle_ate + 0.048) < 1e-9,
          max(abs((t1 - t0) - working_difference - group_error)) < 1e-8)
```

The fitted coefficient is −0.049149. Across the cohort, the mean weighted prediction error `H × (Y − fitted risk)` under the received schedule moves from **−4.80 to 0.00 percentage points**. Within the two frailty groups the remaining errors are +6.04 and −9.06 points. They cancel with the cohort’s 60% and 40% weights.

```{r targeting-summary}
starting_risk <- weighted.mean(q_initial, cohort_n)
tmle_standard <- weighted.mean(qstar0, cohort_n)
tmle_short <- weighted.mean(qstar1, cohort_n)
knitr::kable(data.frame(step = c("Before update", "After update"),
                       standard = 100*c(starting_risk, tmle_standard),
                       short = 100*c(starting_risk, tmle_short),
                       difference = 100*c(0, tmle_short - tmle_standard),
                       score = 100*c(score_before, score_after)), digits = c(0, 5, 5, 2, 2),
             col.names = c("Cohort fit", "Standard mortality (%)", "Short mortality (%)",
                           "Difference (pp)", "Mean H × residual (pp)"))
stopifnot(abs(starting_risk - 0.2734) < 1e-9,
          abs(tmle_short - tmle_standard - tmle_ate) < 1e-9)
```

Averaging the updated risks gives **24.88169% on short and 29.68169% on standard**, a difference of **−4.80 points**. S and T reach the same difference from 23.20% on short and 28.00% on standard. This TMLE targets the cohort ATE alone. Its working risk differences are −4.04 points at lower frailty and −5.94 at higher frailty. The observed cell risks give +2 and −15 points, respectively. At lower frailty, even the sign differs. [Schuler and Rose on TMLE for observational data](https://doi.org/10.1093/aje/kww165) · [Balzer, Petersen and van der Laan on targeting a difference](https://doi.org/10.1002/sim.6965)

### Cross-fitted AIPW for the all-eligible ATE

Split every frailty-by-schedule cell into five equal parts. Within a cell of size `n`, label the synthetic rows `j = 0, ..., n-1`. The generator lists deaths first in each cell. A fixed permutation, `(37*j + 17) %% n`, assigns rows to folds by taking successive fifths of its ranks. This deterministic split reproduces the drawings. Each training set has 4,000 patients and its held-out fold contains the other 1,000. In practice, assign patients to folds randomly, keeping a patient’s records together.

```{r honest-folds}
make_folds <- function(n) {
  j <- seq_len(n) - 1L
  rank <- (37L * j + 17L) %% n
  stopifnot(length(unique(rank)) == n)
  1L + (5L * rank) %/% n
}
fold <- unlist(lapply(cells[["patients"]], make_folds), use.names = FALSE)
stopifnot(all(table(fold) == 1000L))
fit_profiles <- function(rows) {
  frailty <- rows[["L"]]
  a <- rows[["A"]]
  y <- rows[["Y"]]
  data.frame(e = as.numeric(tapply(a, frailty, mean)),
             q0 = as.numeric(tapply(y[a == 0L], frailty[a == 0L], mean)),
             q1 = as.numeric(tapply(y[a == 1L], frailty[a == 1L], mean)),
             m = as.numeric(tapply(y, frailty, mean)))
}
fits <- vector("list", 5)
out_of_fold <- data.frame(e = rep(NA_real_, nrow(train)), q0 = NA_real_,
                          q1 = NA_real_, m = NA_real_)
for (k in seq_along(fits)) {
  held <- fold == k
  fits[[k]] <- fit_profiles(train[!held, ])
  out_of_fold[held, ] <- fits[[k]][group[held], ]
}
stopifnot(!anyNA(out_of_fold), abs(fits[[1]]$q0[2] - 479/1200) < 1e-12)
```

In each rotation, use four training folds to estimate the two mortality risks and the probability of short at each frailty level. Predict both risks for the 1,000 held-out patients. Their mean short-minus-standard difference is the **starting contrast**. For each observed outcome, subtract the predicted risk under the received schedule, then multiply by the signed inverse-probability weight `H`. The mean of those terms is the fold’s **correction**.

Call each patient’s corrected AIPW contribution `Γ = Q1 − Q0 + H × (Y − Q_received)`. Its estimating score at a proposed risk difference `θ` is `Γ − θ`. Choosing the average of all 5,000 contributions for `θ` makes the cohort’s mean score zero.

```{r dml-ate}
q_received <- ifelse(arm == 1L, out_of_fold[["q1"]], out_of_fold[["q0"]])
h_held <- ifelse(arm == 1L, 1 / out_of_fold[["e"]], -1 / (1 - out_of_fold[["e"]]))
initial_difference <- out_of_fold[["q1"]] - out_of_fold[["q0"]]
correction <- h_held * (observed - q_received)
contribution <- initial_difference + correction
irm_ate <- mean(contribution)
irm_score <- contribution - irm_ate
fold_n <- as.integer(table(fold))
mean_by_fold <- function(x) as.numeric(tapply(x, fold, mean))
fold_results <- data.frame(held = as.character(seq_along(fold_n)),
                           trained = nrow(train) - fold_n, scored = fold_n,
                           start = mean_by_fold(initial_difference),
                           correction = mean_by_fold(correction), result = mean_by_fold(contribution))
pooled <- data.frame(held = "All folds", trained = NA_integer_, scored = sum(fold_n),
                     start = weighted.mean(fold_results$start, fold_n),
                     correction = weighted.mean(fold_results$correction, fold_n),
                     result = weighted.mean(fold_results$result, fold_n))
report <- rbind(fold_results, pooled)
knitr::kable(transform(report, start = 100*start, correction = 100*correction,
                      result = 100*result), digits = c(0, 0, 0, 3, 3, 3),
             col.names = c("Scored fold", "Trained on", "Scored", "Starting contrast (pp)",
                           "Mean correction (pp)", "Fold or cohort estimate (pp)"))
stopifnot(sum(fold_n) == nrow(train), abs(mean(irm_score)) < 1e-12,
          max(abs(report$start + report$correction - report$result)) < 1e-12,
          abs(pooled$start + 0.048) < 1e-9, abs(pooled$correction) < 1e-9,
          abs(pooled$result - irm_ate) < 1e-9, abs(irm_ate + 0.048) < 1e-9)
```

In fold 1 the initial difference is −4.633 points, the correction is −0.833 points and the resulting estimate is −5.467 points (rounded). The final row weights each fold by its number of scored records. Every record is scored once. The nonzero fold corrections cancel in this balanced synthetic design, giving **−4.80 points** for all 5,000 patients. Other datasets and nuisance fits can yield a nonzero overall correction and different finite-sample estimates from TMLE. [Chernozhukov et al., sections 3–5](https://doi.org/10.1111/ectj.12097) · [DoubleML score equations](https://docs.doubleml.org/stable/guide/scores.html)

#### How much would the AIPW estimate vary across samples?

Imagine repeatedly sampling 5,000 independent patients from the same eligible population, with the frailty mix free to vary. For this sampling question, estimate the AIPW standard error from the spread of the 5,000 held-out contributions. A normal approximation gives a 95% confidence interval for the population ATE. The synthetic counts in the worksheet itself are fixed.

```{r aipw-uncertainty}
n_patients <- length(contribution)
iid_se <- sd(contribution) / sqrt(n_patients)
iid_interval <- irm_ate + c(-1, 1) * qnorm(0.975) * iid_se

# Independent check using the four observed death risks.
cell_counts <- xtabs(patients ~ L + A, data = cells)
cell_risks <- xtabs(deaths ~ L + A, data = cells) / cell_counts
q0 <- cell_risks[, "0"]
q1 <- cell_risks[, "1"]
profile_n <- rowSums(cell_counts)
prop_short <- cell_counts[, "1"] / profile_n
cell_ate <- weighted.mean(q1 - q0, profile_n)
within_group <- q1*(1 - q1)/prop_short + q0*(1 - q0)/(1 - prop_short)
between_groups <- (q1 - q0 - cell_ate)^2
# Use the same sample-variance convention as sd() above.
cell_se <- sqrt(weighted.mean(within_group + between_groups, profile_n) / (sum(profile_n) - 1))

round(100 * c(AIPW_SE = iid_se, lower_95 = iid_interval[1],
              upper_95 = iid_interval[2], four_cell_SE = cell_se), 4)
stopifnot(abs(cell_ate - irm_ate) < 1e-12,
          abs(iid_se - 0.0134352252592) < 1e-10, abs(cell_se - 0.0134328117289) < 1e-10)
```

For AIPW the SE is **1.34 percentage points**, giving **−4.80 points (95% CI −7.43 to −2.17)**. The four-cell check combines variation in outcomes within frailty groups and variation in the effect across groups. Using the same sample-variance convention, it gives 1.34328 points, close to 1.34352 from the held-out fits. [DoubleML on score-based confidence intervals](https://docs.doubleml.org/stable/guide/se_confint.html)

### Partially linear DML for a residual slope

Partially linear regression (PLR) predicts schedule and mortality from frailty alone. From the held-out predictions, compute a treatment residual `V = A − e` and an outcome residual `U = Y − m`. The PLR score for a proposed slope `θ` is `V × (U − θV)`. Its mean is zero when `θ` equals the sum of the residual cross-products divided by the sum of squared treatment residuals. Pool the two sums across all five folds before dividing.

```{r dml-plr}
treatment_residual <- arm - out_of_fold[["e"]]
outcome_residual <- observed - out_of_fold[["m"]]
cross_products <- tapply(treatment_residual * outcome_residual, fold, sum)
squared_treatment <- tapply(treatment_residual^2, fold, sum)
num <- sum(cross_products)
den <- sum(squared_treatment)
plr <- num / den
plr_score <- treatment_residual * (outcome_residual - plr * treatment_residual)
full_a_residual <- resid(lm(A ~ factor(L), data = train))
full_y_residual <- resid(lm(Y ~ factor(L), data = train))
full_residual_slope <- sum(full_a_residual * full_y_residual) / sum(full_a_residual^2)
fwl <- unname(coef(lm(Y ~ A + factor(L), data = train))["A"])
overlap_mass <- cohort_n * g_full * (1 - g_full)
overlap_weight <- overlap_mass / sum(overlap_mass)
overlap_target <- sum(overlap_weight * (t1 - t0))
knitr::kable(data.frame(scored = nrow(train), cross_product = num, squared_treatment = den,
                       plr = 100*plr, fwl = 100*fwl), digits = c(0, 2, 0, 5, 5),
             col.names = c("Scored records", "Sum of residual cross-products",
                           "Sum of squared treatment residuals", "PLR slope (pp)", "OLS / FWL (pp)"))
stopifnot(abs(num + 43.65) < 1e-9, abs(den - 1005) < 1e-9,
          abs(mean(plr_score)) < 1e-12, abs(fwl - full_residual_slope) < 1e-9,
          abs(plr - fwl) < 1e-9, abs(plr - overlap_target) < 1e-9,
          abs(plr - irm_ate) > 0.004)
```

The cross-fitted slope is −43.65 / 1,005 = −0.0434328, or **−4.34328 percentage points**. With a binary schedule and varying frailty-specific effects, PLR weights each group in proportion to its size times `e × (1 − e)`. The resulting group weights are 630/1,005 and 375/1,005. Lower frailty gets 62.69% of the weight in this slope and 60% in Susan’s all-eligible ATE. [Why a partially linear model weights overlap](https://docs.doubleml.org/stable/examples/py_double_ml_plm_irm_hetfx.html)

The **Frisch–Waugh–Lovell (FWL) theorem** gives an exact identity for ordinary least squares. Using the same full sample, residualize both `A` and `Y` on frailty. Their residual slope equals the schedule coefficient in the regression of `Y` on schedule and frailty. Our cross-fitted slope happens to agree because every fold preserves the treatment proportion within each frailty group. Different splits or prediction models can give different slopes in a finite sample. [Ding on FWL](https://doi.org/10.1016/j.spl.2020.108945)

## What if one schedule is unavailable?

In another synthetic clinic, a clinical rule makes the short schedule unavailable to every higher-frailty patient. Hold the lower-frailty data fixed. Keep the unavailable risk and full-target contrast unresolved. If Susan asks a new question about the 3,000 lower-frailty patients, those patients contribute evidence for both schedules.

```{r support}
second_clinic <- cells
high <- second_clinic$L == 1L
second_clinic$patients[high] <- c(2000L, 0L)
second_clinic$deaths[high] <- c(800L, 0L)

counts <- xtabs(patients ~ L + A, data = second_clinic)
deaths <- xtabs(deaths ~ L + A, data = second_clinic)
risks <- deaths / counts
risks[counts == 0] <- NA_real_
supported <- counts[, "0"] > 0 & counts[, "1"] > 0
difference <- risks[, "1"] - risks[, "0"]
target_n <- rowSums(counts)
full_target <- weighted.mean(difference, target_n)
shared_target <- weighted.mean(difference[supported], target_n[supported])
stopifnot(is.na(full_target), sum(target_n[supported]) == 3000L,
          abs(shared_target - 0.02) < 1e-8)
knitr::kable(data.frame(profile = profile_names,
  standard_n = as.integer(counts[, "0"]), short_n = as.integer(counts[, "1"]),
  difference_pp = as.numeric(100*difference)), digits = 2)
```

The revised target has a **+2 percentage-point** estimated risk difference. In real data, an empty sample cell can also arise by chance. Susan would ask the clinicians whether both schedules were realistic options before redefining whom her conclusion covers.

## Read the worksheet alongside the paper

Künzel and colleagues write $W$ for the schedule (`A` in this notebook) and $X$ for the baseline covariates (`L` for frailty here). Their $\tau(x)$ is the mean difference in outcomes for patients with baseline profile $x$. For this binary outcome it is a five-year mortality risk difference, short minus standard.

| In the notebook | On printed page 4158 |
| --- | --- |
| T fits one risk model in each arm. S fits one model and predicts twice. | Equation 3 (T) and equation 4 (S) |
| X fits risks, forms a signed pseudo-outcome for each training record, then fits those values within each arm. | Equations 5–6 (risks) and 7–8 (signed pseudo-outcomes for the short and standard arms) |
| X averages the two fitted effects at the same frailty profile. | Equation 9, with the estimated propensity as the blending weight here |

The final ATE and ATT calculation in this notebook averages the profile effects over the chosen patients. Open the [paper at the equations](https://ishuryak.github.io/causal-roadmap-primer/preview/estimators/kunzel-2019.pdf#page=3) or read the [accessible full-text article](https://pmc.ncbi.nlm.nih.gov/articles/PMC6410831/).
