Applied Health Economics, RWE & HTA
Overview / Module 2 / Day 18
Module 2 · Biostatistics & econometrics · Day 18 of 100

Missing Data and Multiple Imputation

Every trial and every cohort has gaps. A fifth of the Renavex questionnaires at 24 months are missing, and Day 17 showed that the people who skipped them were sicker. Today you classify the missingness, show how much complete-case analysis is off, and fix most of it with multiple imputation by chained equations. Rubin's rules carry the uncertainty about the imputed values into the standard errors. A delta-adjustment analysis then asks how wrong the imputation's assumption would have to be to change the conclusion. The truth file grades every step.

▶
Video for Day 18 coming soon

By the end of today you can

  • describe missingness by variable and pattern, and test whether it depends on observed data
  • explain MCAR, MAR and MNAR, and what complete-case analysis and MI assume
  • run MICE with predictive mean matching within each arm, with all predictors of missingness, and pool with Rubin's rules
  • never use mean imputation or LOCF for a primary analysis
  • report a delta-adjustment (tipping-point) analysis for MNAR

Today's 5.5-hour plan

LessonProjectBreakCommitFrançais
0:00–0:40
18.1 What is missing, and for whom?
0:40–1:10
18.2 Complete-case analysis
1:10–1:25
Break
1:25–2:20
18.3 Multiple imputation by chained equations
2:20–2:45
18.4 Truth check: what MI fixes and what it cannot
2:45–3:00
Break
3:00–3:15
18.5 Filling the gaps with the mean
3:15–3:50
18.6 Sensitivity analysis: delta adjustment
3:50–4:50
18.7 Mini-project: two-year QALYs and costs
4:50–5:00
18.8 Save your work
5:00–5:30
Bloc français

In this lesson

18.1 What is missing, and for whom? (40 min)

Rubin's three mechanisms:

MechanismMissingness depends onComplete-case analysisMultiple imputation
MCAR: missing completely at randomnothing related to the dataunbiased, less preciseunbiased
MAR: missing at randomvalues we observed (e.g. last visit's utility)biasedunbiased if the imputation model uses those values
MNAR: missing not at randomthe missing value itselfbiasedbiased: needs a sensitivity analysis

The data can tell MCAR from MAR. Nothing in the data can rule out MNAR.

The analysis population is the 1,735 patients whose 24-month visit took place. One row per patient:

def wide(v):
    """Visits (from corridor.trial.visits) -> one row per patient with a 24-month visit."""
    w = v.pivot_table(index="patient_id", columns="visit_month", values=["utility", "cost_12m"], dropna=False)
    out = pd.DataFrame({"u0": w[("utility", 0)], "u12": w[("utility", 12)], "u24": w[("utility", 24)],
                        "c12": w[("cost_12m", 12)], "c24": w[("cost_12m", 24)]})
    had24 = v[v.visit_month == 24].patient_id
    base = v[v.visit_month == 0].set_index("patient_id")[["arm", "renavex", "age", "egfr"]]
    kf = v[v.visit_month == 24].set_index("patient_id").kf_now.rename("kf24")
    out = out.loc[out.index.isin(had24)].join(base).join(kf)
    return out.reset_index()

def pattern(df, cols=WIDE_COLS):
    """Missing-data pattern per row, e.g. 'u0 u12 . c12 .' with '.' for missing."""
    return df[cols].isna().apply(lambda r: " ".join("." if m else c for c, m in zip(cols, r)), axis=1)
"""Day 18.1-18.2: what is missing, for whom, and does it depend on what we saw before?"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np  # noqa: E402
import statsmodels.formula.api as smf  # noqa: E402

from corridor.missing import WIDE_COLS, pattern, wide  # noqa: E402
from corridor.trial import visits  # noqa: E402

v = visits()
w = wide(v)
print(f"{len(w):,} patients had their 24-month visit")
print("\nMissing, by variable (%):")
print((100 * w[WIDE_COLS].isna().mean()).round(1).to_string())
print("\nMissing-data patterns ('.' = missing):")
print(pattern(w).value_counts().head(8).to_string())
print(f"complete on all five: {(pattern(w) == ' '.join(WIDE_COLS)).mean():.1%}")

print("\nIs the 24-month questionnaire missing at random? Compare what we DID see earlier:")
w["m24"] = w.u24.isna().astype(int)
print(w.groupby("m24")[["u0", "u12", "kf24", "age"]].mean().round(3).rename(index={0: "answered", 1: "missing"}).to_string())
fit = smf.logit("m24 ~ u12 + renavex + age + kf24", w.dropna(subset=["u12"])).fit(disp=0)
print(f"\nlogit(missing at 24 months): OR per 0.1 higher utility at 12 months = {np.exp(0.1 * fit.params['u12']):.2f} "
      f"(p = {fit.pvalues['u12']:.1e}); OR for kidney failure = {np.exp(fit.params['kf24']):.2f}")
1,735 patients had their 24-month visit

Missing, by variable (%):
u0      0.0
u12    18.2
u24    20.6
c12     8.3
c24     9.9

Missing-data patterns ('.' = missing):
u0 u12 u24 c12 c24    991
u0 u12 . c12 c24      200
u0 . u24 c12 c24      166
u0 u12 u24 c12 .       88
u0 . . c12 c24         77
u0 u12 u24 . c24       72
u0 u12 . . c24         30
u0 u12 . c12 .         29
complete on all five: 57.1%

Is the 24-month questionnaire missing at random? Compare what we DID see earlier:
             u0    u12   kf24     age
m24                                  
answered  0.841  0.840  0.047  64.784
missing   0.701  0.679  0.154  67.824

logit(missing at 24 months): OR per 0.1 higher utility at 12 months = 0.67 (p = 3.1e-23); OR for kidney failure = 2.45

Only 57% of patients have everything. The ones who skipped the 24-month questionnaire had a mean utility of 0.68 at 12 months, against 0.84 for those who answered. Each 0.1 of utility at 12 months cuts the odds of skipping by a third. Kidney failure more than doubles them. Missingness depends on observed data, so it is not MCAR. Whether it is MAR or MNAR, the data cannot say.


18.2 Complete-case analysis (30 min)

The default in most software: drop anyone with a missing value.

"""Day 18.3: the complete-case analysis - analyse only the people who answered."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np  # noqa: E402

from corridor.missing import wide  # noqa: E402
from corridor.trial import visits  # noqa: E402

w = wide(visits())
w["cost"] = w.c12 + w.c24
for var, label in (("u24", "utility at 24 months"), ("cost", "two-year cost")):
    g = {a: d[var].dropna() for a, d in w.groupby("arm")}
    diff = g["renavex"].mean() - g["placebo"].mean()
    se = np.sqrt(sum(x.var() / len(x) for x in g.values()))
    f = (lambda x: f"{x:.4f}") if var == "u24" else (lambda x: f"{x:,.0f}")
    print(f"{label:<22} placebo {f(g['placebo'].mean()):>7} (n={len(g['placebo'])})  renavex {f(g['renavex'].mean()):>7} "
          f"(n={len(g['renavex'])})  difference {f(diff):>6} (SE {f(se)})")
utility at 24 months   placebo  0.7788 (n=644)  renavex  0.8179 (n=733)  difference 0.0391 (SE 0.0100)
two-year cost          placebo  12,385 (n=702)  renavex  14,629 (n=732)  difference  2,243 (SE 1,115)

The complete-case utilities are high in both arms because the sickest patients are missing. The Renavex benefit is 0.039. Each analysis also uses a different set of patients (644 placebo patients for utility, 702 for costs), so utility and cost results don't describe the same people.


18.3 Multiple imputation by chained equations (55 min)

MICE fills each incomplete variable from a regression on all the others, cycling through the variables until the imputations settle. To carry the uncertainty, it does this $m$ times, drawing the regression coefficients from their posterior each time. Predictive mean matching (PMM) then gives each missing value the observed value of a patient with a similar prediction. That keeps imputed costs positive and skewed, and utilities within the value set's range.

def _pmm_draw(rng, X_obs, y_obs, X_mis, k=5):
    """One Bayesian-regression draw, then predictive mean matching: each missing value takes the
    observed value of one of the k observed cases with the closest predicted mean."""
    n, p = X_obs.shape
    beta, *_ = np.linalg.lstsq(X_obs, y_obs, rcond=None)
    resid = y_obs - X_obs @ beta
    sigma2 = resid @ resid / rng.chisquare(n - p)
    cov = sigma2 * np.linalg.inv(X_obs.T @ X_obs)
    beta_star = rng.multivariate_normal(beta, cov)
    pred_obs, pred_mis = X_obs @ beta, X_mis @ beta_star
    order = np.argsort(np.abs(pred_mis[:, None] - pred_obs[None, :]), axis=1)[:, :k]
    pick = order[np.arange(len(X_mis)), rng.integers(0, k, len(X_mis))]
    return y_obs[pick]

def mice_pmm(df, cols=WIDE_COLS, covariates=("age", "egfr", "kf24"), m=20, iterations=10, seed=2026):
    """m completed copies of df. Each incomplete column is imputed from all the others plus covariates,
    cycling `iterations` times. Run it separately for each trial arm."""
    rng = np.random.default_rng(seed)
    miss = {c: df[c].isna().to_numpy() for c in cols}
    out = []
    for _ in range(m):
        d = df.copy()
        for c in cols:                         # start from random observed values
            obs = d.loc[~miss[c], c].to_numpy()
            d.loc[miss[c], c] = rng.choice(obs, miss[c].sum())
        for _ in range(iterations):
            for c in cols:
                if not miss[c].any():
                    continue
                others = [x for x in cols if x != c] + list(covariates)
                X = np.column_stack([np.ones(len(d)), d[others].to_numpy(float)])
                d.loc[miss[c], c] = _pmm_draw(rng, X[~miss[c]], d.loc[~miss[c], c].to_numpy(float), X[miss[c]])
        out.append(d)
    return out

Analyse each completed dataset, then combine with Rubin's rules. The pooled estimate is the average. The variance adds the average within-imputation variance $\bar U$ and the between-imputation variance $B$:

T=Uˉ+(1+1m)BT = \bar U + \left(1 + \tfrac{1}{m}\right) B
def rubin(estimates, variances):
    """Rubin's rules: pooled estimate, total variance, and the share of variance due to missing data."""
    q, u = np.asarray(estimates), np.asarray(variances)
    m = len(q)
    qbar, ubar, b = q.mean(), u.mean(), q.var(ddof=1)
    t = ubar + (1 + 1 / m) * b
    return float(qbar), float(t), float((1 + 1 / m) * b / t)

In a trial, impute each arm separately, so the imputation model allows every relationship to differ by treatment.

"""Day 18.4: multiple imputation by chained equations (predictive mean matching), within each arm."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.missing import arm_contrast, mice_pmm, wide  # noqa: E402
from corridor.trial import visits  # noqa: E402

w = wide(visits())
imps = {arm: mice_pmm(g.reset_index(drop=True), m=20, seed=2026 + k) for k, (arm, g) in enumerate(w.groupby("arm"))}
for label, stat in (("utility at 24 months", lambda d: d.u24), ("two-year cost", lambda d: d.c12 + d.c24)):
    r = arm_contrast(imps, stat)
    f = (lambda x: f"{x:.4f}") if "utility" in label else (lambda x: f"{x:,.0f}")
    print(f"--- {label} (20 imputations, Rubin's rules)")
    for k in ("placebo", "renavex", "difference"):
        est, var, fmi = r[k]
        print(f"  {k:<11} {f(est):>8}  SE {f(var ** 0.5):>6}  95% CI {f(est - 1.96 * var ** 0.5)} to "
              f"{f(est + 1.96 * var ** 0.5)}  fraction of missing information {fmi:.2f}")
--- utility at 24 months (20 imputations, Rubin's rules)
  placebo       0.7404  SE 0.0095  95% CI 0.7219 to 0.7590  fraction of missing information 0.25
  renavex       0.7885  SE 0.0070  95% CI 0.7747 to 0.8023  fraction of missing information 0.15
  difference    0.0480  SE 0.0117  95% CI 0.0252 to 0.0709  fraction of missing information 0.20
--- two-year cost (20 imputations, Rubin's rules)
  placebo       12,346  SE    784  95% CI 10,810 to 13,882  fraction of missing information 0.03
  renavex       14,798  SE    679  95% CI 13,468 to 16,128  fraction of missing information 0.07
  difference     2,452  SE  1,036  95% CI 421 to 4,484  fraction of missing information 0.05

The imputed utilities are lower than the complete-case ones in both arms (0.740 and 0.789), and the benefit is larger: 0.048. The fraction of missing information says how much of the uncertainty comes from the gaps. It is 0.20 for the utility difference: a fifth of the variance is due to missing data. For costs it is only 0.05, because costs are less often missing and easy to predict from the other year's cost.

Check it in R with mice, the reference implementation:

# Day 18: the same imputation with the mice package (predictive mean matching), within each arm.
suppressPackageStartupMessages(library(mice))
v <- read.csv("data/renavex_trial_visits.csv")
tr <- read.csv("data/renavex_trial.csv")
eq5d_ca <- function(mo, sc, ua, pd, ad) {
  lv <- cbind(mo, sc, ua, pd, ad); s45 <- lv >= 4
  1.1351 - drop(lv %*% c(0.0389, 0.0458, 0.0195, 0.0444, 0.0376)) -
    drop(s45 %*% c(0.0510, 0.0584, 0.1103, 0.1409, 0.1277)) + 0.0085 * pmax(rowSums(s45) - 1, 0)^2
}
v$u <- with(v, eq5d_ca(mo, sc, ua, pd, ad))
tr$kf_date <- as.Date(ifelse(tr$kidney_failure_date == "", NA, tr$kidney_failure_date))
w <- reshape(v[, c("patient_id", "visit_month", "u", "cost_12m")], idvar = "patient_id", timevar = "visit_month",
             direction = "wide")
w <- w[w$patient_id %in% v$patient_id[v$visit_month == 24], ]
names(w) <- c("patient_id", "u0", "c0", "u12", "c12", "u24", "c24")
w <- merge(w[, c("patient_id", "u0", "u12", "u24", "c12", "c24")], tr[, c("patient_id", "arm", "age", "egfr", "kf_date")])
d24 <- v[v$visit_month == 24, c("patient_id", "visit_date")]
w <- merge(w, d24)
w$kf24 <- as.integer(!is.na(w$kf_date) & w$kf_date <= as.Date(w$visit_date))
res <- list()
for (a in c("placebo", "renavex")) {
  d <- w[w$arm == a, c("u0", "u12", "u24", "c12", "c24", "age", "egfr", "kf24")]
  imp <- mice(d, m = 20, method = "pmm", maxit = 10, seed = 2026, printFlag = FALSE)
  est <- sapply(1:20, function(i) mean(complete(imp, i)$u24))
  vr <- sapply(1:20, function(i) var(complete(imp, i)$u24) / nrow(d))
  res[[a]] <- list(est = est, var = vr)
  cat(sprintf("%-8s complete case %.4f   MI %.4f\n", a, mean(d$u24, na.rm = TRUE), mean(est)))
}
q <- res$renavex$est - res$placebo$est
u <- res$renavex$var + res$placebo$var
t <- mean(u) + (1 + 1 / 20) * var(q)
cat(sprintf("difference (Rubin): %.4f, SE %.4f\n", mean(q), sqrt(t)))
placebo  complete case 0.7788   MI 0.7409
renavex  complete case 0.8179   MI 0.7897
difference (Rubin): 0.0488, SE 0.0111

mice gives a difference of 0.0488 against Python's 0.0480: the same method, with different random draws.


18.4 Truth check: what MI fixes and what it cannot (25 min)

The generator made people skip questionnaires partly because of their utility at the previous visit (MAR) and partly because of their utility at that visit (MNAR). Compare both analyses with the answers nobody gave:

"""Day 18.5 (truth check): complete case vs multiple imputation vs the answers nobody gave.

The generator made people skip questionnaires partly because of their utility at the PREVIOUS visit
(missing at random given the data) and partly because of their utility at THIS visit (missing not at
random). Multiple imputation can fix the first part, not the second.
"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import duckdb  # noqa: E402

from corridor.missing import arm_contrast, mice_pmm, truth_wide, wide  # noqa: E402
from corridor.trial import visits  # noqa: E402
from corridor.truth import TRUTH  # noqa: E402

w = wide(visits())
full = duckdb.sql(f"SELECT * FROM read_csv('{TRUTH}/trial_visits_complete.csv')").df()
w = truth_wide(full, w)
imps = {arm: mice_pmm(g.reset_index(drop=True), m=20, seed=2026 + k) for k, (arm, g) in enumerate(w.groupby("arm"))}
mi = arm_contrast(imps, lambda d: d.u24)
print("Mean utility at 24 months")
print(f"{'':<11}{'complete case':>14}{'MI':>8}{'truth':>8}")
for arm in ("placebo", "renavex"):
    g = w[w.arm == arm]
    print(f"{arm:<11}{g.u24.mean():>14.4f}{mi[arm][0]:>8.4f}{g.true_u24.mean():>8.4f}")
cc = w[w.arm == "renavex"].u24.mean() - w[w.arm == "placebo"].u24.mean()
tr = w[w.arm == "renavex"].true_u24.mean() - w[w.arm == "placebo"].true_u24.mean()
print(f"{'difference':<11}{cc:>14.4f}{mi['difference'][0]:>8.4f}{tr:>8.4f}")
Mean utility at 24 months
            complete case      MI   truth
placebo            0.7788  0.7404  0.7328
renavex            0.8179  0.7885  0.7800
difference         0.0391  0.0480  0.0472

Complete-case analysis overstates utility by 0.046 (placebo) and 0.038 (Renavex), and understates the benefit by 17%. MI removes about 80% of the bias in each arm and gets the difference within 0.001. The rest is the MNAR part: no model of the observed data can see it.

Try it (15 min). Impute the 24-month utility from baseline covariates only (age, eGFR, kidney failure), without the earlier utilities. How much bias comes back?

Solution
"""Day 18 try it: impute the 24-month utility from baseline covariates only (no earlier utilities)."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.missing import arm_contrast, mice_pmm, wide  # noqa: E402
from corridor.trial import visits  # noqa: E402

w = wide(visits())
for cols, label in ((["u0", "u12", "u24", "c12", "c24"], "all visits as predictors"),
                    (["u24"], "covariates only (age, eGFR, kidney failure)")):
    imps = {arm: mice_pmm(g.reset_index(drop=True), cols=cols, m=20, seed=2026 + k)
            for k, (arm, g) in enumerate(w.groupby("arm"))}
    r = arm_contrast(imps, lambda d: d.u24)
    print(f"{label:<45} placebo {r['placebo'][0]:.4f}  renavex {r['renavex'][0]:.4f}  difference {r['difference'][0]:.4f}")
all visits as predictors                      placebo 0.7404  renavex 0.7885  difference 0.0480
covariates only (age, eGFR, kidney failure)   placebo 0.7696  renavex 0.8124  difference 0.0428

Without the earlier utilities, the imputed means (0.770 and 0.812) fall back most of the way to the complete-case values. MI is only as good as its predictors: missingness depended on last year's utility, so last year's utility must be in the model. Include every variable that predicts the missing value or its missingness, even if it is not in the analysis model.


18.5 Filling the gaps with the mean (15 min)

Bug of the day. An analyst replaces each missing 24-month utility with the arm's mean, and analyses 1,735 "observations":

"""Day 18 bug of the day: fill the gaps with the mean and carry on."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np  # noqa: E402

from corridor.missing import wide  # noqa: E402
from corridor.trial import visits  # noqa: E402

w = wide(visits())
w["u24_filled"] = w.groupby("arm").u24.transform(lambda s: s.fillna(s.mean()))
g = {a: d.u24_filled for a, d in w.groupby("arm")}
diff = g["renavex"].mean() - g["placebo"].mean()
se = np.sqrt(sum(x.var() / len(x) for x in g.values()))
print(f"mean-imputed: difference {diff:.4f}, SE {se:.4f}, n = {len(w):,} 'observations'")
print(f"the filled-in values have SD {w.u24_filled.std():.3f}; the observed values have SD {w.u24.std():.3f}")
mean-imputed: difference 0.0391, SE 0.0079, n = 1,735 'observations'
the filled-in values have SD 0.164; the observed values have SD 0.183

The difference is exactly the complete-case one (0.039), so all the bias stays. The SE falls from 0.0100 to 0.0079, because 358 invented values are treated as data and the spread shrinks (SD 0.164 against 0.183). Mean imputation (and last observation carried forward) is biased and overconfident. Use multiple imputation, and say so in the methods.


18.6 Sensitivity analysis: delta adjustment (35 min)

If the data are MNAR, the patients who skipped were worse off than MI assumes. Delta adjustment asks how much worse it would take to change the conclusion. Subtract δ from every imputed utility, re-estimate, and find the tipping point.

"""Day 18.6: MNAR sensitivity analysis - what if the people who skipped were worse off than MI assumes?

Delta adjustment: after imputing under MAR, subtract delta from every IMPUTED 24-month utility, then
re-estimate. Scenario A: the same delta in both arms. Scenario B: only in the Renavex arm (the
benefit could be an artefact of who answered). Find the delta at which the conclusion changes.
"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.missing import arm_contrast, mice_pmm, wide  # noqa: E402
from corridor.trial import visits  # noqa: E402

w = wide(visits())
miss = {arm: g.u24.isna().to_numpy() for arm, g in w.groupby("arm")}
imps = {arm: mice_pmm(g.reset_index(drop=True), m=20, seed=2026 + k) for k, (arm, g) in enumerate(w.groupby("arm"))}
print(f"{'delta':>6}{'both arms: difference (95% CI)':>34}{'Renavex arm only: difference (95% CI)':>42}")
for delta in (0.0, 0.02, 0.05, 0.10, 0.15, 0.20):
    out = []
    for arms in (("placebo", "renavex"), ("renavex",)):
        adj = {a: [d.assign(u24=d.u24 - delta * (miss[a] if a in arms else 0)) for d in imps[a]] for a in imps}
        est, var, _ = arm_contrast(adj, lambda d: d.u24)["difference"]
        out.append(f"{est:.4f} ({est - 1.96 * var ** 0.5:.4f} to {est + 1.96 * var ** 0.5:.4f})")
    print(f"{delta:>6.2f}{out[0]:>34}{out[1]:>42}")
 delta    both arms: difference (95% CI)     Renavex arm only: difference (95% CI)
  0.00         0.0480 (0.0252 to 0.0709)                 0.0480 (0.0252 to 0.0709)
  0.02         0.0491 (0.0261 to 0.0722)                 0.0444 (0.0215 to 0.0674)
  0.05         0.0508 (0.0273 to 0.0742)                 0.0390 (0.0159 to 0.0622)
  0.10         0.0535 (0.0293 to 0.0776)                 0.0300 (0.0066 to 0.0535)
  0.15         0.0562 (0.0311 to 0.0812)                0.0210 (-0.0028 to 0.0449)
  0.20         0.0589 (0.0329 to 0.0849)                0.0120 (-0.0122 to 0.0363)

If the non-responders are worse off by the same amount in both arms, the benefit grows (placebo has more missing values). If only Renavex's non-responders are worse off, the benefit's confidence interval reaches zero between δ = 0.10 and 0.15. That is a large shift: 0.15 is more than the gap between full health and a moderate problem on one dimension. Report it as "the conclusion holds unless Renavex patients who skipped the questionnaire were about 0.14 worse than similar patients who answered". The truth check (18.4) suggests the real shift here is much smaller: MI was within 0.01 of the truth in each arm.

Why it matters at work: Missing utilities and costs are routine in trial-based CEAs. CDA-AMC and NICE reviewers expect multiple imputation, a description of the imputation model, and an MNAR sensitivity analysis; a complete-case CEA is usually questioned.

Where you'll meet this: trial-based CEA (Days 53–55) · RWE studies with missing lab values or BMI · the "missing data" section of every statistical analysis plan


18.7 Mini-project: two-year QALYs and costs (60 min)

QALYs over two years by the trapezoid rule, $\frac{u_0+u_{12}}{2} + \frac{u_{12}+u_{24}}{2}$, and two-year costs, by arm and as increments, three ways:

"""Day 18 mini-project: two-year QALYs and costs by arm - complete case, multiple imputation, truth.

Population: patients whose 24-month visit took place. (Module 5 handles deaths and censoring properly.)
"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import duckdb  # noqa: E402

from corridor.missing import arm_contrast, mice_pmm, qaly, truth_wide, wide  # noqa: E402
from corridor.trial import visits  # noqa: E402
from corridor.truth import TRUTH  # noqa: E402

w = wide(visits())
w = truth_wide(duckdb.sql(f"SELECT * FROM read_csv('{TRUTH}/trial_visits_complete.csv')").df(), w)
w["qaly"] = qaly(w.u0, w.u12, w.u24)
w["cost"] = w.c12 + w.c24
imps = {arm: mice_pmm(g.reset_index(drop=True), m=20, seed=2026 + k) for k, (arm, g) in enumerate(w.groupby("arm"))}
rows = {"QALYs": (lambda d: qaly(d.u0, d.u12, d.u24), "qaly", "true_qaly", "{:.4f}"),
        "costs": (lambda d: d.c12 + d.c24, "cost", "true_cost", "{:,.0f}")}
print(f"{'':<8}{'':<12}{'complete case':>15}{'n':>6}{'MI (Rubin)':>12}{'truth':>10}")
for label, (stat, col, true_col, fmt) in rows.items():
    mi = arm_contrast(imps, stat)
    for arm in ("placebo", "renavex"):
        g = w[w.arm == arm]
        print(f"{label:<8}{arm:<12}{fmt.format(g[col].mean()):>15}{g[col].notna().sum():>6}"
              f"{fmt.format(mi[arm][0]):>12}{fmt.format(g[true_col].mean()):>10}")
    cc = w[w.arm == "renavex"][col].mean() - w[w.arm == "placebo"][col].mean()
    tr = w[w.arm == "renavex"][true_col].mean() - w[w.arm == "placebo"][true_col].mean()
    est, var, _ = mi["difference"]
    print(f"{label:<8}{'increment':<12}{fmt.format(cc):>15}{'':>6}{fmt.format(est):>12}{fmt.format(tr):>10}"
          f"   (MI 95% CI {fmt.format(est - 1.96 * var ** 0.5)} to {fmt.format(est + 1.96 * var ** 0.5)})")
                      complete case     n  MI (Rubin)     truth
QALYs   placebo              1.6582   525      1.5525    1.5461
QALYs   renavex              1.6934   632      1.6034    1.5913
QALYs   increment            0.0352            0.0509    0.0451   (MI 95% CI 0.0171 to 0.0847)
costs   placebo              12,385   702      12,346    12,156
costs   renavex              14,629   732      14,798    14,729
costs   increment             2,243             2,452     2,573   (MI 95% CI 421 to 4,484)

Complete case keeps only 525 placebo patients for QALYs (all three questionnaires answered). It overstates QALYs by about 0.1 in each arm and understates the QALY gain (0.035 against a true 0.045). MI gets QALYs within 0.012 and the gain within 0.006, and its interval contains the truth. For costs, the differences are smaller and all three methods give similar increments: costs were less often missing, and their missingness was only weakly related to health.

Write two sentences for the CEA's methods: the imputation model and the sensitivity analysis.

18.8 Save your work

python -m pytest -q
git add .
git commit -m "Day 18: missing data patterns, MICE with PMM, Rubin's rules, delta adjustment"

Day 18 checklist

  • I describe missingness by variable and pattern, and test whether it depends on observed data
  • I can explain MCAR, MAR and MNAR, and what complete-case analysis and MI assume
  • I run MICE with predictive mean matching within each arm, with all predictors of missingness, and pool with Rubin's rules
  • I never use mean imputation or LOCF for a primary analysis
  • I report a delta-adjustment (tipping-point) analysis for MNAR