Skip to content

Multiple imputation and sensitivity

Fill gaps many plausible ways, combine the results with Rubin's rules, and test how much your conclusion depends on the assumption.

Advanced ~13 min8 steps

What runs in CodeSplash

You will be able to

  • Explain why several imputations keep uncertainty that one loses
  • Read the fraction of missing information on a pooled result
  • Run a sensitivity check against MNAR

Read first

01

Many plausible fills

Read

One fill pretends you know the missing value. Multiple imputationMultiple imputationFills each gap several plausible ways, analyses every completed dataset and pools the results, so the uncertainty from the gaps stays in. makes several completed datasets, each with different plausible values drawn from what the other columns suggest.

You run the analysis on each and combine the results. Where the imputations disagree, you're uncertain, and that disagreement ends up in your standard errors.

It's valid when the data are MARMissing at randomMissingness explained by observed variables; imputation that uses them can remove the bias., given the variables in the imputation model.

02

Rubin's rules

Predict

Predict first

Compared with a single imputation of the same data, how do the pooled intervals from multiple imputation look?

NarrowerAbout the sameWider
Reveal

The answer: Wider

Wider, and more honest. The pooled variance adds the disagreement between imputations:

T=Uˉ+(1+1m)BT = \bar U + \left(1 + \frac{1}{m}\right) B

Uˉ\bar U is the average within-imputation variance, BB is the between-imputation variance, and mm is the number of imputations.

03

Read a pooled result

In the app

This survey has 25 people, and 48.0% of them have at least one gap. CodeSplash made 5 imputations.

Multiple imputation (MICE)Recorded · Python and R agreeRecorded 2026-11-17 · 66 values compared
R

12 of 25 rows had missing values; 5 imputations × 5 iterations; gaussian model pooled with Rubin's rules (largest FMI 0.48).

Largest fraction of missing information
0.4822

Plots

Pooled estimatesHow large are several estimates, how precise, and which exclude the null?
View data
estimatehightermlow
45.82494.122age[40-59]−2.474
52.228102.50age[60-99]1.955
6.17910.291bmi2.068

Assumptions

  • Missing at random — Valid when missingness depends on observed values only; under MNAR consider a δ-adjusted sensitivity analysis.
  • Fraction of missing information — Largest FMI 0.48 (> 0.3: results lean on the imputation model; use more imputations).
  • Enough iterations — 5 iterations per imputation, 5 imputations.

Pooled estimates (Rubin's rules)

TermEstimateSEdfpLowerUpperFMIComplete cases
(Intercept)−0.383158.82017.0390.9949−124.46123.690.1772−28.948
age[40-59]45.82421.1588.4970.0603−2.47494.1220.482255.810
age[60-99]52.22822.3309.2910.04331.955102.500.4474104.72
bmi6.1791.96018.3990.00542.06810.2910.12786.921

Imputed variables

VariableMissingMethodObserved meanImputed mean
hypertensive8logreg0.23530.4000
cholesterol10pmm191.40191.58
bmi9pmm26.56327.636
  • 48% of rows are incomplete: consider at least 48 imputations.
  • Seed 42; the 5 completed data sets are saved as imputed.parquet (long format with .imp and .id).
The exact R script · R R version 4.5.1 (2025-06-13)
# Multiple imputation by chained equations (MICE) with pooled analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method missing.mice 1.0.1 · spec add129afc9850239
# Dataset: s4_nhanes (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_mice_impute (chained equations on the shared random stream), cs_pool (mice::pool), cs_sel_coef_names

# %% Data (no rows are dropped: the missing values are imputed)
outcome <- "cholesterol"
predictors <- c("age", "bmi")
names_ <- unique(c(c("age", "hypertensive"), outcome, predictors))
kinds <- "{\"age\":\"categorical\",\"bmi\":\"numeric\",\"cholesterol\":\"numeric\",\"hypertensive\":\"boolean\"}"
kinds <- jsonlite::fromJSON(kinds)
stored <- jsonlite::fromJSON("{\"age\":[\"20-39\",\"40-59\",\"60-99\"],\"bmi\":null,\"cholesterol\":null,\"hypertensive\":[\"false\",\"true\"]}", simplifyVector = TRUE)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s4_nhanes.parquet", col_select = names_))
n <- nrow(df)
warnings <- list()
levels_ <- list()
cols <- list()
for (v in names_) {
  if (kinds[[v]] %in% c("categorical", "boolean")) {
    lv <- stored[[v]]
    if (is.null(lv)) lv <- sort(unique(stats::na.omit(as.character(df[[v]]))), method = "radix")
    levels_[[v]] <- as.character(lv)
    cols[[v]] <- match(as.character(df[[v]]), levels_[[v]]) - 1  # codes 0…, NA = missing
  } else {
    levels_[v] <- list(NULL)
    cols[[v]] <- as.numeric(df[[v]])
  }
}
miss_any <- Reduce(`|`, lapply(cols[names_], is.na))

# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
cs_check_finite_columns(df, names_)  # infinite values stop the run (registry/errors.yaml)
n_coef <- 1 + sum(vapply(predictors, function(p) if (is.null(levels_[[p]])) 1 else length(levels_[[p]]) - 1, numeric(1)))  # analysis-model coefficients
cs_check_rows(n, n_coef + 1, "The MICE analysis model")  # more rows than coefficients
for (v in names_) {
  if (all(is.na(cols[[v]]))) cs_error("CS_E_ALL_MISSING", column = v)  # nothing observed to impute from
}
cs_check_not_constant(cols[[outcome]], outcome)
for (p in predictors) cs_check_not_constant(cols[[p]], p)  # one value (or one level with data) is no variation

# %% Imputation (mice::mice(df, m, maxit, method = pmm / norm / logreg / polyreg) is the classic equivalent)
m <- as.integer(5)
maxit <- as.integer(5)
seed <- 42  # shared Wichmann–Hill stream: the same imputations in Python and R
imp <- tryCatch(
  cs_mice_impute(cols, kinds, levels_, names_, m, maxit, seed, "pmm", as.integer(5)),
  error = function(e) {
    # an imputation model is singular (e.g. a category with no observed rows)
    if (grepl("singular", conditionMessage(e), fixed = TRUE)) cs_error("CS_E_COLLINEAR")
    stop(e)
  }
)
completed <- imp$data

# %% Analysis model on every completed data set, pooled with Rubin's rules
family <- "auto"
binary_y <- kinds[[outcome]] != "numeric"
if (family == "auto") family <- if (binary_y) "binomial" else "gaussian"
if (family == "binomial" && (!binary_y || length(levels_[[outcome]]) != 2)) stop(sprintf("Logistic regression needs a yes/no outcome; %s is not", outcome))
if (family == "gaussian" && binary_y) stop(sprintf("Linear regression needs a numeric outcome; %s is categorical", outcome))
frame_of <- function(c) {
  d <- data.frame(.y = as.numeric(c[[outcome]]))
  for (p in predictors) d[[p]] <- if (is.null(levels_[[p]])) c[[p]] else factor(levels_[[p]][c[[p]] + 1], levels = levels_[[p]])
  d
}
fml <- stats::as.formula(paste(".y ~", paste(sprintf("`%s`", predictors), collapse = " + ")))
analyze <- function(c) {
  d <- frame_of(c)
  fit <- if (family == "gaussian") stats::lm(fml, data = d) else {
    ctrl <- stats::glm.control(epsilon = 1e-14, maxit = 100)
    g <- stats::glm(fml, family = stats::binomial(), data = d, control = ctrl)
    # one more IRLS pass from the converged coefficients, so vcov() uses their working weights
    stats::glm(fml, family = stats::binomial(), data = d, control = ctrl, start = stats::coef(g))
  }
  list(names = cs_sel_coef_names(fit), coef = unname(stats::coef(fit)), se = unname(sqrt(diag(stats::vcov(fit)))), dfres = stats::df.residual(fit))
}
results <- lapply(completed, analyze)
terms <- results[[1]]$names
conf <- 0.95
pooled <- cs_pool(do.call(rbind, lapply(results, `[[`, "coef")), do.call(rbind, lapply(results, `[[`, "se")), dfcom = results[[1]]$dfres, conf = conf)
ok <- Reduce(`&`, lapply(cols[c(outcome, predictors)], function(x) !is.na(x)))
cc_data <- lapply(cols, function(x) x[ok])
x_cc <- cs_sel_design(frame_of(cc_data), predictors)
# The complete-case fit needs more complete rows than coefficients and no empty category; otherwise it is left empty.
cc_ok <- nrow(x_cc) > ncol(x_cc) && qr(x_cc)$rank == ncol(x_cc)
if (cc_ok) {
  cc <- analyze(cc_data)
} else {
  cc <- list(names = terms, coef = rep(NA_real_, length(terms)), se = rep(NA_real_, length(terms)))
  warnings <- c(warnings, "The complete cases can't support the analysis model (too few rows or an empty category); that column is left empty.")
}

# %% Imputed data sets (long format, like mice::complete(imp, "long"))
out <- cs_ml_out_dir("target/academy-parity/run-953/missing.mice/nhanes-pmm/out-r")
long <- do.call(rbind, lapply(seq_len(m), function(i) {
  part <- data.frame(.imp = rep(i, n), .id = seq_len(n))
  for (v in names_) part[[v]] <- if (is.null(levels_[[v]])) completed[[i]][[v]] else levels_[[v]][completed[[i]][[v]] + 1]
  part
}))
path <- file.path(out, "imputed.parquet")
nanoparquet::write_parquet(long, path)

# %% Summaries and assumptions
values <- list(n = n, n_vars = length(names_), m = m, maxit = maxit, n_incomplete = sum(miss_any),
               pct_incomplete = mean(miss_any), family = family, n_terms = length(terms), max_fmi = max(pooled$fmi))
imp_rows <- list()
for (v in names_) {
  miss <- is.na(cols[[v]])
  values[[sprintf("missing[%s]", v)]] <- sum(miss)
  if (!any(miss)) next
  values[[sprintf("method[%s]", v)]] <- imp$methods[[v]]
  if (kinds[[v]] == "numeric" || length(levels_[[v]]) == 2) {
    obs_mean <- mean(cols[[v]][!miss])
    imp_mean <- mean(unlist(lapply(completed, function(c) c[[v]][miss])))
    values[[sprintf("observed_mean[%s]", v)]] <- obs_mean
    values[[sprintf("imputed_mean[%s]", v)]] <- imp_mean
  } else {
    obs_mean <- NaN
    imp_mean <- NaN
  }
  imp_rows[[length(imp_rows) + 1]] <- list(variable = v, missing = sum(miss), method = imp$methods[[v]], observed = obs_mean, imputed = imp_mean)
}
for (j in seq_along(terms)) {
  for (key in c("estimate", "se", "df", "p", "fmi", "lambda", "riv", "ci_low", "ci_high")) values[[sprintf("%s[%s]", key, terms[j])]] <- pooled[[key]][j]
}
for (j in seq_along(cc$names)) {
  values[[sprintf("cc_estimate[%s]", cc$names[j])]] <- cc$coef[j]
  values[[sprintf("cc_se[%s]", cc$names[j])]] <- cc$se[j]
}
max_fmi <- values$max_fmi
assumptions <- list(
  list(key = "mar", label = "Missing at random", status = "info",
       detail = "Valid when missingness depends on observed values only; under MNAR consider a δ-adjusted sensitivity analysis."),
  list(key = "fmi", label = "Fraction of missing information", status = if (max_fmi <= 0.3) "pass" else "warn",
       detail = paste0(sprintf("Largest FMI %.2f", max_fmi), if (max_fmi > 0.3) " (> 0.3: results lean on the imputation model; use more imputations)." else ".")),
  list(key = "convergence", label = "Enough iterations", status = "info", detail = sprintf("%d iterations per imputation, %d imputations.", maxit, m))
)
if (m < 100 * values$pct_incomplete) {
  warnings <- c(warnings, sprintf("%.0f%% of rows are incomplete: consider at least %d imputations.", 100 * values$pct_incomplete, as.integer(ceiling(100 * values$pct_incomplete))))
}

# %% Result
eff <- which(terms != "(Intercept)")
cs_publish(list(
  method = "missing.mice",
  methodVersion = "1.0.1",
  title = "Multiple imputation (MICE)",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = sprintf("%d of %d rows had missing values; %d imputations × %d iterations; %s model pooled with Rubin's rules (largest FMI %.2f).",
                    sum(miss_any), n, m, maxit, family, max_fmi),
  statistics = list(list(key = "max_fmi", label = "Largest fraction of missing information", value = max_fmi)),
  tables = list(
    list(key = "pooled", title = "Pooled estimates (Rubin's rules)",
         columns = list(list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
                        list(key = "se", label = "SE", type = "number"), list(key = "df", label = "df", type = "number"),
                        list(key = "p", label = "p", type = "number", format = "p"), list(key = "low", label = "Lower", type = "number"),
                        list(key = "high", label = "Upper", type = "number"), list(key = "fmi", label = "FMI", type = "number"),
                        list(key = "cc", label = "Complete cases", type = "number")),
         rows = lapply(seq_along(terms), function(j) list(term = terms[j], estimate = pooled$estimate[j], se = pooled$se[j], df = pooled$df[j],
                                                         p = pooled$p[j], low = pooled$ci_low[j], high = pooled$ci_high[j], fmi = pooled$fmi[j],
                                                         cc = values[[sprintf("cc_estimate[%s]", terms[j])]]))),
    list(key = "imputation", title = "Imputed variables",
         columns = list(list(key = "variable", label = "Variable", type = "string"), list(key = "missing", label = "Missing", type = "integer"),
                        list(key = "method", label = "Method", type = "string"), list(key = "observed", label = "Observed mean", type = "number"),
                        list(key = "imputed", label = "Imputed mean", type = "number")),
         rows = imp_rows)
  ),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Seed %d; the %d completed data sets are saved as imputed.parquet (long format with .imp and .id).", seed, m)),
  charts = if (length(eff)) list(cs_chart(
    "pooled", "forest", "Pooled estimates",
    list(label = cs_col("term", terms[eff]), estimate = cs_col("estimate", pooled$estimate[eff]),
         low = cs_col("low", pooled$ci_low[eff]), high = cs_col("high", pooled$ci_high[eff]))
  )) else list(),
  artifacts = list(list(key = "imputed", path = path, format = "parquet", title = sprintf("%d imputed data sets (long format)", m))),
  values = values
))
Python

12 of 25 rows had missing values; 5 imputations × 5 iterations; gaussian model pooled with Rubin's rules (largest FMI 0.48).

Largest fraction of missing information
0.4822

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Missing at random — Valid when missingness depends on observed values only; under MNAR consider a δ-adjusted sensitivity analysis.
  • Fraction of missing information — Largest FMI 0.48 (> 0.3: results lean on the imputation model; use more imputations).
  • Enough iterations — 5 iterations per imputation, 5 imputations.

Pooled estimates (Rubin's rules)

TermEstimateSEdfpLowerUpperFMIComplete cases
(Intercept)−0.383158.82017.0390.9949−124.46123.690.1772−28.948
age[40-59]45.82421.1588.4970.0603−2.47494.1220.482255.810
age[60-99]52.22822.3309.2910.04331.955102.500.4474104.72
bmi6.1791.96018.3990.00542.06810.2910.12786.921

Imputed variables

VariableMissingMethodObserved meanImputed mean
hypertensive8logreg0.23530.4000
cholesterol10pmm191.40191.58
bmi9pmm26.56327.636
  • 48% of rows are incomplete: consider at least 48 imputations.
  • Seed 42; the 5 completed data sets are saved as imputed.parquet (long format with .imp and .id).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Multiple imputation by chained equations (MICE) with pooled analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method missing.mice 1.0.1 · spec add129afc9850239
# Dataset: s4_nhanes (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import json
import math
import os

import numpy as np
import pandas as pd
from scipy import stats

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.ml import run as csml  # artifact directory
from codesplash.stats import mice as csmice  # chained equations on the shared random stream (twin of codesplashr::cs_mice_impute)
from codesplash.stats import missing as csm  # Rubin's rules (mice::pool)
from codesplash.stats import selection as sel  # design columns named like the R twin

# %% Data (no rows are dropped: the missing values are imputed)
outcome = "cholesterol"
predictors = ["age", "bmi"]
names = list(dict.fromkeys(["age", "hypertensive"] + [outcome] + predictors))
kinds = json.loads("{\"age\":\"categorical\",\"bmi\":\"numeric\",\"cholesterol\":\"numeric\",\"hypertensive\":\"boolean\"}")
stored = json.loads("{\"age\":[\"20-39\",\"40-59\",\"60-99\"],\"bmi\":null,\"cholesterol\":null,\"hypertensive\":[\"false\",\"true\"]}")  # stored level order (null for numbers)
df = pd.read_parquet("tests/parity/fixtures/s4_nhanes.parquet", columns=names)
n = len(df)
warnings = []
levels, cols = {}, {}
for v in names:
    if kinds[v] in ("categorical", "boolean"):
        lv = stored[v] or sorted(df[v].dropna().astype(str).unique())
        codes = pd.Categorical(df[v], categories=lv).codes.astype(float)
        codes[codes < 0] = np.nan
        levels[v], cols[v] = [str(x) for x in lv], codes
    else:
        levels[v], cols[v] = None, df[v].to_numpy(dtype=float)
miss_any = np.zeros(n, dtype=bool)
for v in names:
    miss_any |= np.isnan(cols[v])

# Degenerate input stops with a catalog error; R runs the same checks in the same order.
cs.check_finite_columns(df, names)  # infinite values stop the run (registry/errors.yaml)
n_coef = 1 + sum(len(levels[p]) - 1 if levels[p] else 1 for p in predictors)  # analysis-model coefficients
cs.check_rows(n, n_coef + 1, "The MICE analysis model")  # more rows than coefficients
for v in names:
    if np.all(np.isnan(cols[v])):
        cs.cs_error("CS_E_ALL_MISSING", column=v)  # nothing observed to impute from
check_not_constant(cols[outcome], outcome)
for p in predictors:
    check_not_constant(cols[p], p)  # one value (or one level with data) is no variation

# %% Imputation (mice::mice(df, m, maxit, method = pmm / norm / logreg / polyreg) is the classic equivalent)
m = int(5)
maxit = int(5)
seed = 42  # shared Wichmann–Hill stream: the same imputations in Python and R
try:
    completed, methods = csmice.impute(cols, kinds, levels, names, m, maxit, seed, "pmm", int(5))
except np.linalg.LinAlgError:
    cs.cs_error("CS_E_COLLINEAR")  # an imputation model is singular (e.g. a category with no observed rows)

# %% Analysis model on every completed data set, pooled with Rubin's rules
family = "auto"
binary_y = kinds[outcome] != "numeric"
if family == "auto":
    family = "binomial" if binary_y else "gaussian"
if family == "binomial" and (not binary_y or len(levels[outcome]) != 2):
    raise ValueError(f"Logistic regression needs a yes/no outcome; {outcome} is not")
if family == "gaussian" and binary_y:
    raise ValueError(f"Linear regression needs a numeric outcome; {outcome} is categorical")
plev = {p: levels[p] for p in predictors}


def frame(c):
    return pd.DataFrame({p: ([plev[p][int(x)] for x in c[p]] if plev[p] else c[p]) for p in predictors})


def analyze(c):
    x, names_, _ = sel.design(frame(c), predictors, plev)
    y = c[outcome].astype(float)
    fit = sel.fit_model(x, y, family)
    if family == "gaussian":
        cov = fit["rss"] / (len(y) - fit["rank"]) * np.linalg.inv(x.T @ x)
    else:
        mu = fit["mu"]
        cov = np.linalg.inv(x.T @ (x * (mu * (1 - mu))[:, None]))
    return names_, fit["coef"], np.sqrt(np.diag(cov)), len(y) - fit["rank"]


results = [analyze(c) for c in completed]
terms = results[0][0]
conf = 0.95
pooled = csm.pool(np.array([r[1] for r in results]), np.array([r[2] for r in results]), dfcom=float(results[0][3]), conf=conf)
ok = np.ones(n, dtype=bool)  # complete in the analysis variables
for v in [outcome] + predictors:
    ok &= ~np.isnan(cols[v])
cc_data = {v: cols[v][ok] for v in names}
x_cc = sel.design(frame(cc_data), predictors, plev)[0]
# The complete-case fit needs more complete rows than coefficients and no empty category; otherwise it is left empty.
cc_ok = x_cc.shape[0] > x_cc.shape[1] and np.linalg.matrix_rank(x_cc) == x_cc.shape[1]
if cc_ok:
    cc_terms, cc_coef, cc_se, _ = analyze(cc_data)
else:
    cc_terms, cc_coef, cc_se = terms, [None] * len(terms), [None] * len(terms)
    warnings.append("The complete cases can't support the analysis model (too few rows or an empty category); that column is left empty.")

# %% Imputed data sets (long format, like mice::complete(imp, "long"))
out = csml.out_dir("target/academy-parity/run-953/missing.mice/nhanes-pmm/out-python")
rows = []
for i, c in enumerate(completed, start=1):
    part = {".imp": np.full(n, i), ".id": np.arange(1, n + 1)}
    for v in names:
        part[v] = [levels[v][int(x)] for x in c[v]] if levels[v] else c[v]
    rows.append(pd.DataFrame(part))
long = pd.concat(rows, ignore_index=True)
path = os.path.join(out, "imputed.parquet")
long.to_parquet(path, index=False)

# %% Summaries and assumptions
values = {"n": n, "n_vars": len(names), "m": m, "maxit": maxit, "n_incomplete": int(miss_any.sum()),
          "pct_incomplete": float(miss_any.mean()), "family": family, "n_terms": len(terms), "max_fmi": float(np.max(pooled["fmi"]))}
imp_rows = []
for v in names:
    miss = np.isnan(cols[v])
    values[f"missing[{v}]"] = int(miss.sum())
    if not miss.any():
        continue
    values[f"method[{v}]"] = methods[v]
    if kinds[v] == "numeric" or len(levels[v]) == 2:
        obs_mean = float(np.mean(cols[v][~miss]))
        imp_mean = float(np.mean(np.concatenate([c[v][miss] for c in completed])))
        values[f"observed_mean[{v}]"] = obs_mean
        values[f"imputed_mean[{v}]"] = imp_mean
    else:
        obs_mean = imp_mean = math.nan
    imp_rows.append({"variable": v, "missing": int(miss.sum()), "method": methods[v], "observed": obs_mean, "imputed": imp_mean})
for j, t in enumerate(terms):
    for key in ("estimate", "se", "df", "p", "fmi", "lambda", "riv", "ci_low", "ci_high"):
        values[f"{key}[{t}]"] = float(pooled[key][j])
for t, b, s in zip(cc_terms, cc_coef, cc_se):
    values[f"cc_estimate[{t}]"] = None if b is None else float(b)
    values[f"cc_se[{t}]"] = None if s is None else float(s)
max_fmi = values["max_fmi"]
assumptions = [
    {"key": "mar", "label": "Missing at random", "status": "info",
     "detail": "Valid when missingness depends on observed values only; under MNAR consider a δ-adjusted sensitivity analysis."},
    {"key": "fmi", "label": "Fraction of missing information", "status": "pass" if max_fmi <= 0.3 else "warn",
     "detail": f"Largest FMI {max_fmi:.2f}" + (" (> 0.3: results lean on the imputation model; use more imputations)." if max_fmi > 0.3 else ".")},
    {"key": "convergence", "label": "Enough iterations", "status": "info", "detail": f"{maxit} iterations per imputation, {m} imputations."},
]
if m < 100 * values["pct_incomplete"]:
    warnings.append(f"{values['pct_incomplete']:.0%} of rows are incomplete: consider at least {math.ceil(100 * values['pct_incomplete'])} imputations.")

# %% Result
pt = [(t, pooled["estimate"][j], pooled["ci_low"][j], pooled["ci_high"][j]) for j, t in enumerate(terms) if t != "(Intercept)"]
cs.publish({
    "method": "missing.mice",
    "methodVersion": "1.0.1",
    "title": "Multiple imputation (MICE)",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": f"{int(miss_any.sum())} of {n} rows had missing values; {m} imputations × {maxit} iterations; {family} model pooled with Rubin's rules (largest FMI {max_fmi:.2f}).",
    "statistics": [{"key": "max_fmi", "label": "Largest fraction of missing information", "value": max_fmi}],
    "tables": [
        {"key": "pooled", "title": "Pooled estimates (Rubin's rules)",
         "columns": [{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
                     {"key": "se", "label": "SE", "type": "number"}, {"key": "df", "label": "df", "type": "number"},
                     {"key": "p", "label": "p", "type": "number", "format": "p"}, {"key": "low", "label": "Lower", "type": "number"},
                     {"key": "high", "label": "Upper", "type": "number"}, {"key": "fmi", "label": "FMI", "type": "number"},
                     {"key": "cc", "label": "Complete cases", "type": "number"}],
         "rows": [{"term": t, "estimate": float(pooled["estimate"][j]), "se": float(pooled["se"][j]), "df": float(pooled["df"][j]),
                   "p": float(pooled["p"][j]), "low": float(pooled["ci_low"][j]), "high": float(pooled["ci_high"][j]),
                   "fmi": float(pooled["fmi"][j]), "cc": values.get(f"cc_estimate[{t}]")} for j, t in enumerate(terms)]},
        {"key": "imputation", "title": "Imputed variables",
         "columns": [{"key": "variable", "label": "Variable", "type": "string"}, {"key": "missing", "label": "Missing", "type": "integer"},
                     {"key": "method", "label": "Method", "type": "string"}, {"key": "observed", "label": "Observed mean", "type": "number"},
                     {"key": "imputed", "label": "Imputed mean", "type": "number"}],
         "rows": imp_rows},
    ],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Seed {seed}; the {m} completed data sets are saved as imputed.parquet (long format with .imp and .id)."],
    "charts": [cs.chart(
        "pooled", "forest", "Pooled estimates",
        {"label": cs.col("term", [r[0] for r in pt]), "estimate": cs.col("estimate", [float(r[1]) for r in pt]),
         "low": cs.col("low", [float(r[2]) for r in pt]), "high": cs.col("high", [float(r[3]) for r in pt])},
    )] if pt else [],
    "artifacts": [{"key": "imputed", "path": path, "format": "parquet", "title": f"{m} imputed data sets (long format)"}],
    "values": values,
})

The largest fraction of missing informationFraction of missing informationThe share of a pooled estimate's uncertainty that comes from the missing values, not from sampling. is 0.48: nearly half the information about that coefficient comes from the imputation model rather than the data.

04

How many imputations?

Reflect

Compare this with the air-quality data, where 27.5% of rows have gaps and the largest fraction of missing information is 0.17.

A common rule sets mm at least as large as the percentage of incomplete rows. Five may be enough for a point estimate and too few for a stable interval. Which of these two studies needs more imputations, and why?

05

What about MNAR?

Read

Imputation under MAR can't fix data that are MNARMissing not at randomMissingness depends on the missing values themselves (e.g. high earners skip income); needs sensitivity analysis.. The data can't tell you which it is, so test how much it matters:

  1. Assume the missing values are systematically higher or lower by some amount δ\delta.
  2. Shift the imputed values by δ\delta, using a formula step or a notebook, and pool again.
  3. Find the δ\delta at which your conclusion changes.

If that δ\delta is implausibly large, your conclusion is robust. CodeSplash doesn't automate this shift; do it in a notebook from the card's Code tab.

06

In code

Read
Python
import pandas as pd
import statsmodels.api as sm
from statsmodels.imputation.mice import MICE, MICEData

df = pd.read_csv("airquality.csv")[["Ozone", "Solar.R", "Wind", "Temp"]]
df.columns = ["Ozone", "Solar", "Wind", "Temp"]
imputed = MICEData(df)
result = MICE("Ozone ~ Solar + Wind + Temp", sm.OLS, imputed).fit(n_burnin=10, n_imputations=20)
print(result.summary())
R
library(mice)

df <- read.csv("airquality.csv")[, c("Ozone", "Solar.R", "Wind", "Temp")]
imp <- mice(df, m = 20, method = "pmm", seed = 1, printFlag = FALSE)
fit <- with(imp, lm(Ozone ~ Solar.R + Wind + Temp))
summary(pool(fit))

Each language uses its own random draws, so their numbers differ a little from each other and from CodeSplash's.

07

Check your understanding

Checkpoint

Check yourself

Why does multiple imputation give more honest standard errors than a single fill?

Show the answer

Answer: b

Disagreement between imputations measures your uncertainty about the missing values. A single fill sets it to zero.

Check yourself

What was the largest fraction of missing information in the survey above? Give two decimals.

Show the answer

Answer: 0.482200194884981

Read it from the card or the text. High values mean the answer leans heavily on the imputation model.

Check yourself

Multiple imputation is designed for which missingness mechanism?

Show the answer

Answer: b

It also works under MCAR. It doesn't fix MNAR, which is why you run the sensitivity check.

08

Recap

Recap
  • Multiple imputation draws several plausible fills and pools the results.
  • Rubin's rules add the disagreement between imputations to the variance.
  • It assumes MAR, so check how far an MNAR departure would have to go to change your conclusion.

Concepts in this lesson