ADescribe · missing.mice
Multiple imputation by chained equations (MICE) with pooled analysis
What does a regression conclude when missing values are filled in many plausible ways and the results are combined?
Imputes missing values m times by chained equations — predictive mean matching (or Bayesian linear regression) for numbers, logistic regression for yes/no variables and multinomial logit for categories — fits the analysis model (linear or logistic regression) to every completed data set and pools the estimates with Rubin's rules (Barnard–Rubin degrees of freedom, fraction of missing information), next to the complete-case estimates. The imputed data sets are saved.
A real result
Example “Nhanes pmm”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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
View data
| estimate | high | term | low |
|---|---|---|---|
| 45.824 | 94.122 | age[40-59] | −2.474 |
| 52.228 | 102.50 | age[60-99] | 1.955 |
| 6.179 | 10.291 | bmi | 2.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)
| Term | Estimate | SE | df | p | Lower | Upper | FMI | Complete cases |
|---|---|---|---|---|---|---|---|---|
| (Intercept) | −0.3831 | 58.820 | 17.039 | 0.9949 | −124.46 | 123.69 | 0.1772 | −28.948 |
| age[40-59] | 45.824 | 21.158 | 8.497 | 0.0603 | −2.474 | 94.122 | 0.4822 | 55.810 |
| age[60-99] | 52.228 | 22.330 | 9.291 | 0.0433 | 1.955 | 102.50 | 0.4474 | 104.72 |
| bmi | 6.179 | 1.960 | 18.399 | 0.0054 | 2.068 | 10.291 | 0.1278 | 6.921 |
Imputed variables
| Variable | Missing | Method | Observed mean | Imputed mean |
|---|---|---|---|---|
| hypertensive | 8 | logreg | 0.2353 | 0.4000 |
| cholesterol | 10 | pmm | 191.40 | 191.58 |
| bmi | 9 | pmm | 26.563 | 27.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).
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)
| Term | Estimate | SE | df | p | Lower | Upper | FMI | Complete cases |
|---|---|---|---|---|---|---|---|---|
| (Intercept) | −0.3831 | 58.820 | 17.039 | 0.9949 | −124.46 | 123.69 | 0.1772 | −28.948 |
| age[40-59] | 45.824 | 21.158 | 8.497 | 0.0603 | −2.474 | 94.122 | 0.4822 | 55.810 |
| age[60-99] | 52.228 | 22.330 | 9.291 | 0.0433 | 1.955 | 102.50 | 0.4474 | 104.72 |
| bmi | 6.179 | 1.960 | 18.399 | 0.0054 | 2.068 | 10.291 | 0.1278 | 6.921 |
Imputed variables
| Variable | Missing | Method | Observed mean | Imputed mean |
|---|---|---|---|---|
| hypertensive | 8 | logreg | 0.2353 | 0.4000 |
| cholesterol | 10 | pmm | 191.40 | 191.58 |
| bmi | 9 | pmm | 26.563 | 27.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).
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Nhanes pmms4_nhanes · outcome: cholesterol · predictors: age, bmi · variables: age, hypertensive
- Survey all typess4_survey_mi · outcome: systolic bp · predictors: age, smoker, region, income (k) · variables: age, smoker, region
- Survey norm logistics4_survey_mi · outcome: smoker · predictors: age, systolic bp · variables: systolic bp, income (k), region
- Airquality pmm donorsairquality · outcome: Ozone · predictors: Solar.R, Wind, Temp · variables: Wind, Temp, month_f
- Degenerate constants4_nhanes · outcome: cholesterol · predictors: age, bmi · variables: age, hypertensive
- Degenerate n3s4_nhanes · outcome: cholesterol · predictors: age, bmi · variables: age, hypertensive
- Degenerate all nas4_nhanes · outcome: cholesterol · predictors: age, bmi · variables: age, hypertensive
- Degenerate one group lefts4_nhanes · outcome: cholesterol · predictors: age, bmi · variables: age, hypertensive
In the guides
Where it sits in the decision guides
- Data quality: missing values · Statistics Guide · Step 0 — Prepare your data
- Missing data (MCAR/MAR/MNAR, MI) · Statistics Guide · Additional considerations
- Missing values: patterns and imputation (simple, model-based, multiple) · DS & ML Decision Guide · Prepare data for modelling
What you need
- Imputation variablesnumeric / categorical / boolean · 1–30 columns · 2–20 levels
- Variables used to impute each other (the analysis variables are always included). Auxiliary variables related to the missing values make imputations better.
- Analysis outcomenumeric / boolean / categorical · 1 column · 2–2 levels
- Outcome of the analysis run on each imputed dataset.
- Analysis predictorsnumeric / categorical / boolean · 1–20 columns · 2–20 levels
- Predictors of the analysis run on each imputed dataset.
Choices you make
statistics
- Imputations (m)default 20
A common rule: at least the percentage of incomplete rows.
- Iterations per imputationdefault 10
Iterations of the chained equations per imputed dataset. 10 is usually enough to settle.
- Numeric variablesdefault pmm
How numbers are imputed: predictive mean matching (only observed values) or Bayesian linear regression.
- Predictive mean matching (observed values only)(default) — Fills gaps with observed values from similar rows; keeps the data's shape and range, so it's the usual choice.
- Bayesian linear regression — Draws from a Bayesian linear model; pick it for data close to normal, and it can leave the observed range.
- PMM donorsdefault 5
Number of closest observed values PMM draws from for each missing value.
- Analysis modeldefault auto
Model fitted to each completed dataset before pooling with Rubin's rules. Automatic picks from the outcome type.
- Automatic (linear for numbers, logistic for yes/no)(default) — Uses linear for numeric outcomes and logistic for yes/no outcomes; the usual choice.
- Linear regression — Fits linear regression to each completed dataset; pick it for a numeric outcome.
- Logistic regression — Fits logistic regression to each completed dataset; pick it for a yes/no outcome.
hypothesis
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Missing at random
MICE is valid when missingness depends only on observed values (MAR); Little's MCAR test and missingness patterns (Missing-data patterns) help judge it. Under MNAR, run a δ-adjusted sensitivity analysis.
Fraction of missing information
FMI above 0.3 means the estimates lean heavily on the imputation model — use more imputations and check its plausibility.
Enough iterations
Chained equations need iterations to settle; 10 is usually enough, more with many missing values.
What it reports
- n
- How many independent units the analysis used; it sets precision and power.
- n_vars
- How many independent units the analysis used; it sets precision and power.
- m
- How many independent groups the result rests on, such as the studies in a multilevel meta-analysis.
- maxit
- Fills each gap several plausible ways, analyses every completed dataset and pools the results, so the uncertainty from the gaps stays in.
- n_incomplete
- How many independent units the analysis used; it sets precision and power.
- pct_incomplete
- Values that were not recorded; how they went missing decides which fixes are safe.
- family
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- n_terms
- How many distinct words a text method kept after lower-casing, removing stop words and dropping words in too few or too many documents.
- max_fmi
- The share of a pooled estimate's uncertainty that comes from the missing values, not from sampling.
Per group, level or term: missing[<var>], method[<var>], observed_mean[<var>], imputed_mean[<var>], estimate[<term>], se[<term>], df[<term>], p[<term>], fmi[<term>], lambda[<term>], riv[<term>], ci_low[<term>], ci_high[<term>], cc_estimate[<term>], cc_se[<term>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-8). Python uses pandas, numpy, scipy, pyarrow, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Both engines run the same chained-equations twin (cs mice.impute ↔ cs_mice_impute) on the shared Wichmann–Hill stream, so they draw the same imputations; mice::mice() is the classic equivalent but uses R's own random numbers. Differences come only from χ² / normal quantiles and linear algebra (≈ 1e-14), well inside P1.
- PMM compares distances rounded to 1e-10 standard deviations of the variable with ties to the earlier row (mice breaks ties at random); logistic and multinomial imputation models carry a 1e-3 ridge on the slopes (mice augments the data) so perfect prediction cannot diverge.
- Pooling: Rubin's rules with Barnard–Rubin degrees of freedom (dfcom = n − p), the columns of mice::pool.
The exact script CodeSplash ran for example “Nhanes pmm” · 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 exact script CodeSplash ran for example “Nhanes pmm” · 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
))
Sources
- van Buuren, S., & Groothuis-Oudshoorn, K. (2011). mice: Multivariate imputation by chained equations in R. Journal of Statistical Software, 45(3).
- Rubin, D. B. (1987). Multiple Imputation for Nonresponse in Surveys. Wiley.
- Barnard, J., & Rubin, D. B. (1999). Small-sample degrees of freedom with multiple imputation. Biometrika, 86, 948–955.
- Morris, T. P., White, I. R., & Royston, P. (2014). Tuning multiple imputation by predictive mean matching and local residual draws. BMC Medical Research Methodology, 14, 75.
From the CodeSplash method registry · missing.mice v1.0.1.