From a missing-data test to a plan
A consistent MCAR result can still hide missingness that depends on another column. Turn test results, standardized differences and domain knowledge into a plan.
What runs in CodeSplash
- STAT304Little MCAR test Runs in CodeSplash
- STAT305Hawkins homoscedasticity and normality test Runs in CodeSplash
- STAT306Jamshidian–Jalal missingness tests Runs in CodeSplash
- Missing-data patterns and MCAR tests Verified in Python and R
- Multiple imputation by chained equations (MICE) with pooled analysis Verified in Python and R
You will be able to
- Explain why MCAR tests can pass when gaps depend on an observed column
- Say what the data can and can't tell you about MAR and MNAR
- Choose how many imputations a result needs from its fraction of missing information
A test that says "consistent"
PredictPredict first
In a simulated table, income is missing whenever v4 is high. So its gaps depend on another column, and are MARMissing at randomMissingness explained by observed variables; imputation that uses them can remove the bias. rather than MCAR.
You run Hawkins and Jamshidian–Jalal on these columns, with the comparison of rows with and without gaps. What finds it?
Reveal
The standardized differences. Hawkins gives p = .117, Anderson–Darling gives p = .803, and the decision is consistent. But 1 standardized difference is flagged.
Why they differ
ReadThose two MCAR tests compare covariances across patterns. If a gap shifts another column's mean but leaves the covariances alone, they have little to find.
A comparison of means looks for exactly that. So use them together, and read consistent as "no evidence from this test".
181 of 240 rows are complete; 2 missingness patterns.
- Complete rows
- 181
- Patterns
- 2
- Little's MCAR p
- —
- Hawkins p
- .117
- Jamshidian–Jalal p
- .803
Plots
View data
| v3 | v4 | income |
|---|---|---|
| 0.6422 | 1.138 | — |
| 1.157 | −0.7407 | 44.660 |
| −0.1736 | 1.238 | — |
| −0.9646 | 0.5896 | 10.850 |
| 1.854 | 1.007 | — |
| 1.684 | −1.753 | 31.660 |
| 1.057 | −0.7734 | 42.730 |
| 0.8146 | −0.3867 | 31.440 |
| −1.195 | 0.1883 | 5.050 |
| −2.029 | −0.0619 | 6.260 |
| 2.124 | −0.1484 | 85.610 |
| 0.2992 | 0.5991 | 12.520 |
| −0.8246 | 0.9138 | — |
| 1.524 | 1.667 | — |
| −0.6148 | 0.6036 | — |
| −0.4598 | −1.162 | 15.630 |
| 0.4436 | −1.372 | 21.200 |
| −1.396 | 1.334 | — |
| −0.5025 | −0.3935 | 15.260 |
| −1.061 | 0.3536 | 11.050 |
| 1.175 | 0.4001 | 64.100 |
| 0.3304 | 0.6667 | — |
| −0.2884 | −0.4202 | 14.820 |
| 1.322 | −0.3282 | 52.510 |
| −0.0455 | 0.4379 | 25.190 |
| −0.2148 | −0.7840 | 15.570 |
| 0.1348 | −0.2268 | 24.750 |
| −0.6450 | −0.5822 | 12.070 |
| 0.0571 | −1.098 | 16.850 |
| 0.9312 | 0.1624 | 24.500 |
| 0.2037 | 0.4506 | 19.730 |
| 1.626 | 0.0983 | 33.590 |
| −0.5934 | 0.3341 | 19.190 |
| −0.3086 | −0.0904 | 20.960 |
| 1.336 | −0.1754 | 37.830 |
| −1.206 | −1.571 | 17.920 |
| −1.409 | 1.212 | — |
| 0.6444 | 1.458 | — |
| −0.4089 | 0.8651 | — |
| −0.9792 | 0.5899 | 18.850 |
| −0.9272 | 0.0828 | 13.100 |
| 0.7927 | −0.4037 | 25.930 |
| −0.6891 | 0.1938 | 18.570 |
| −0.0417 | −0.5531 | 15.450 |
| −0.7856 | 0.7035 | — |
| 0.4345 | 0.3977 | 37.160 |
| −0.6656 | 0.0100 | 19.430 |
| 0.4499 | −0.2555 | 34.410 |
| −0.5480 | 0.3018 | 18.710 |
| 1.857 | 0.7236 | — |
| 0.4021 | 1.415 | — |
| −1.865 | −1.373 | 6.730 |
| 1.375 | −0.5995 | 37.120 |
| −0.0746 | 1.710 | — |
| 0.2278 | −0.1639 | 21.290 |
| 1.389 | 1.605 | — |
| 0.4058 | −0.7987 | 29.480 |
| 2.561 | 1.180 | — |
| −0.5263 | −0.8596 | 10.360 |
| 0.3524 | −0.8697 | 22.780 |
First 60 of 240 rows.
View data
| v3 | v4 | income |
|---|---|---|
| 0.6422 | 1.138 | — |
| 1.157 | −0.7407 | 44.660 |
| −0.1736 | 1.238 | — |
| −0.9646 | 0.5896 | 10.850 |
| 1.854 | 1.007 | — |
| 1.684 | −1.753 | 31.660 |
| 1.057 | −0.7734 | 42.730 |
| 0.8146 | −0.3867 | 31.440 |
| −1.195 | 0.1883 | 5.050 |
| −2.029 | −0.0619 | 6.260 |
| 2.124 | −0.1484 | 85.610 |
| 0.2992 | 0.5991 | 12.520 |
| −0.8246 | 0.9138 | — |
| 1.524 | 1.667 | — |
| −0.6148 | 0.6036 | — |
| −0.4598 | −1.162 | 15.630 |
| 0.4436 | −1.372 | 21.200 |
| −1.396 | 1.334 | — |
| −0.5025 | −0.3935 | 15.260 |
| −1.061 | 0.3536 | 11.050 |
| 1.175 | 0.4001 | 64.100 |
| 0.3304 | 0.6667 | — |
| −0.2884 | −0.4202 | 14.820 |
| 1.322 | −0.3282 | 52.510 |
| −0.0455 | 0.4379 | 25.190 |
| −0.2148 | −0.7840 | 15.570 |
| 0.1348 | −0.2268 | 24.750 |
| −0.6450 | −0.5822 | 12.070 |
| 0.0571 | −1.098 | 16.850 |
| 0.9312 | 0.1624 | 24.500 |
| 0.2037 | 0.4506 | 19.730 |
| 1.626 | 0.0983 | 33.590 |
| −0.5934 | 0.3341 | 19.190 |
| −0.3086 | −0.0904 | 20.960 |
| 1.336 | −0.1754 | 37.830 |
| −1.206 | −1.571 | 17.920 |
| −1.409 | 1.212 | — |
| 0.6444 | 1.458 | — |
| −0.4089 | 0.8651 | — |
| −0.9792 | 0.5899 | 18.850 |
| −0.9272 | 0.0828 | 13.100 |
| 0.7927 | −0.4037 | 25.930 |
| −0.6891 | 0.1938 | 18.570 |
| −0.0417 | −0.5531 | 15.450 |
| −0.7856 | 0.7035 | — |
| 0.4345 | 0.3977 | 37.160 |
| −0.6656 | 0.0100 | 19.430 |
| 0.4499 | −0.2555 | 34.410 |
| −0.5480 | 0.3018 | 18.710 |
| 1.857 | 0.7236 | — |
| 0.4021 | 1.415 | — |
| −1.865 | −1.373 | 6.730 |
| 1.375 | −0.5995 | 37.120 |
| −0.0746 | 1.710 | — |
| 0.2278 | −0.1639 | 21.290 |
| 1.389 | 1.605 | — |
| 0.4058 | −0.7987 | 29.480 |
| 2.561 | 1.180 | — |
| −0.5263 | −0.8596 | 10.360 |
| 0.3524 | −0.8697 | 22.780 |
First 60 of 240 rows.
Missing values by variable
| Variable | Kind | Missing | % |
|---|---|---|---|
| v3 | numeric | 0 | 0.0% |
| v4 | numeric | 0 | 0.0% |
| income | numeric | 59 | 24.6% |
Missingness patterns
| Missing variables | Rows | % | Variables missing |
|---|---|---|---|
| (complete) | 181 | 75.4% | 0 |
| income | 59 | 24.6% | 1 |
Tests of missing completely at random
| Test | Statistic | df | p | |
|---|---|---|---|---|
| Hawkins: normality and equal covariances | 7.393 | 4 | 0.1165 | Fisher's combination of the pattern p-values |
| Jamshidian–Jalal: equal covariances (k-sample Anderson–Darling) | 0.4222 | — | 0.8033 | permutation p (299 relabelings) |
No evidence against MCAR: after imputation the data look normal with equal covariances across the missingness patterns.
Normality and equal covariances by pattern (Hawkins)
| Missing variables | Rows | Neyman N₄ | p | p from |
|---|---|---|---|---|
| (complete) | 181 | 9.379 | 0.0523 | χ²(4) |
| income | 59 | 3.523 | 0.4744 | χ²(4) |
After one normal imputation from the EM estimate (seed 1); uniform tail probabilities mean normal data with equal covariances.
Do rows with missing values differ?
| Missing in | Compared variable | n missing | n observed | Mean when missing | Mean when observed | SMD | |
|---|---|---|---|---|---|---|---|
| income | v3 | 59 | 181 | 0.0290 | 0.0123 | 0.0176 | |
| income | v4 | 59 | 181 | 1.265 | −0.4318 | 2.714 | |SMD| > 0.2 |
- Little's test compares each pattern's means with EM estimates (multivariate normal, numeric variables). A small p is evidence against missing completely at random (MCAR); a large p does not prove MCAR. Complete-case analysis is unbiased only under MCAR.
- SMD > 0.2 in absolute value: rows missing one variable differ on another, so missingness depends on observed data (MAR-like) — consider multiple imputation.
- Hawkins and Jamshidian–Jalal: patterns are imputed once from the EM estimate. Hawkins' test rejects when the data are not normal or covariances differ across patterns; the nonparametric Anderson–Darling test separates the two. A rejection is about this imputed data set — repeat with another seed to see how stable it is.
The exact R script · R R version 4.5.1 (2025-06-13)
# Missing-data patterns and MCAR tests
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method missing.patterns 1.1.1 · spec 4c63949c97002366
# Dataset: c3_mcar (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data (no rows are dropped: missing values are what this analysis is about)
variables <- c("v3", "v4", "income")
kinds <- c(
"v3" = "numeric",
"v4" = "numeric",
"income" = "numeric"
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/c3_mcar.parquet", col_select = variables))
cs_check_finite_columns(df, variables) # infinite values stop the run (registry/errors.yaml)
n <- nrow(df)
mcar <- TRUE
mcar_tests <- "jamshidian_jalal"
min_n <- as.integer(10)
reps <- as.integer(299)
seed <- as.integer(1)
alpha <- 0.05
run_little <- mcar && mcar_tests %in% c("little", "all")
run_hawkins <- mcar && mcar_tests %in% c("hawkins", "jamshidian_jalal", "all")
run_ad <- mcar && mcar_tests %in% c("jamshidian_jalal", "all")
smd_on <- TRUE
max_patterns <- as.integer(20)
warnings <- list()
miss <- is.na(as.matrix(df))
colnames(miss) <- variables
# %% Per variable and patterns
values <- list(n_rows = n, n_vars = length(variables))
var_rows <- list()
for (j in seq_along(variables)) {
v <- variables[j]
k <- sum(miss[, j])
var_rows[[j]] <- list(variable = v, kind = kinds[[v]], n_missing = k, pct_missing = if (n) k / n else NaN)
values[[sprintf("missing[%s]", v)]] <- k
values[[sprintf("pct_missing[%s]", v)]] <- if (n) k / n else NaN
}
complete <- sum(!apply(miss, 1, any))
pats <- cs_missing_patterns(miss)
pat_rows <- list()
for (i in seq_len(nrow(pats))) {
code <- pats$code[i]
missing_vars <- variables[strsplit(code, "")[[1]] == "1"]
values[[sprintf("pattern_n[%s]", code)]] <- pats$n[i]
if (length(pat_rows) < max_patterns) {
pat_rows[[length(pat_rows) + 1]] <- list(pattern = if (length(missing_vars)) paste(missing_vars, collapse = ", ") else "(complete)",
code = code, n = pats$n[i], pct = pats$n[i] / n, n_missing_vars = length(missing_vars))
}
}
counts <- colSums(miss)
worst <- which.max(counts)
values$n_complete <- complete
values$pct_complete <- if (n) complete / n else NaN
values$n_patterns <- nrow(pats)
values$n_cells_missing <- sum(miss)
values$pct_cells_missing <- if (length(miss)) mean(miss) else NaN
values$most_missing <- variables[worst]
values$most_missing_pct <- counts[[worst]] / n
# %% Little's MCAR test (numeric variables; EM estimates of the mean and covariance)
numeric <- Filter(function(v) kinds[[v]] == "numeric" && sum(!is.na(df[[v]])) > 1 && isTRUE(stats::sd(df[[v]], na.rm = TRUE) > 0), variables)
mcar_res <- NULL
if (run_little && length(numeric) >= 2 && n > length(numeric)) {
mcar_res <- cs_little_mcar(as.matrix(df[numeric]))
} else if (run_little && length(numeric) >= 2) {
# With no more rows than variables the estimated covariance matrix is singular.
warnings <- c(warnings, "Little's test needs more rows than numeric variables; it was not run.")
} else if (run_little) {
warnings <- c(warnings, "Little's test needs at least two numeric variables with variation.")
}
values$mcar_done <- !is.null(mcar_res)
values$mcar_vars <- if (is.null(mcar_res)) 0 else length(numeric)
values["mcar_statistic"] <- list(if (is.null(mcar_res)) NULL else mcar_res$statistic)
values["mcar_df"] <- list(if (is.null(mcar_res)) NULL else mcar_res$df)
values["mcar_p"] <- list(if (is.null(mcar_res)) NULL else mcar_res$p)
values["mcar_patterns"] <- list(if (is.null(mcar_res)) NULL else mcar_res$patterns)
# %% Hawkins and Jamshidian–Jalal tests (normality and equal covariances across patterns after one imputation)
jj <- NULL
if (run_hawkins && length(numeric) >= 2) {
jj <- cs_jamshidian_jalal(as.matrix(df[numeric]), min_n, reps, seed, alpha, nonparametric = run_ad)
if (!jj$done) {
warnings <- c(warnings, sprintf("The Hawkins and Jamshidian–Jalal tests were not run: %s.", jj$reason))
jj <- NULL
} else if (jj$n_dropped > 0) {
warnings <- c(warnings, sprintf("%d rows in patterns with fewer than %d rows were left out of the Hawkins and Jamshidian–Jalal tests.", jj$n_dropped, min_n))
}
} else if (run_hawkins) {
warnings <- c(warnings, "The Hawkins and Jamshidian–Jalal tests need at least two numeric variables with variation.")
}
decisions <- c(
consistent = "No evidence against MCAR: after imputation the data look normal with equal covariances across the missingness patterns.",
not_mcar = "Covariances differ across the missingness patterns (Anderson–Darling): evidence against MCAR.",
non_normal = "The data do not look normal, but covariances do not differ across patterns: no evidence against MCAR."
)
has_ad <- !is.null(jj) && !is.null(jj$ad_statistic)
values$hawkins_done <- !is.null(jj)
values["hawkins_statistic"] <- list(if (is.null(jj)) NULL else jj$hawkins_statistic)
values["hawkins_df"] <- list(if (is.null(jj)) NULL else jj$hawkins_df)
values["hawkins_p"] <- list(if (is.null(jj)) NULL else jj$hawkins_p)
values["hawkins_patterns"] <- list(if (is.null(jj)) NULL else jj$n_patterns)
values["hawkins_n"] <- list(if (is.null(jj)) NULL else jj$n_used)
values$ad_done <- has_ad
values["ad_statistic"] <- list(if (has_ad) jj$ad_statistic else NULL)
values["ad_p"] <- list(if (has_ad) jj$ad_p else NULL)
values["jj_decision"] <- list(if (has_ad) jj$decision else NULL)
jj_rows <- list()
if (!is.null(jj)) {
for (g in jj$groups) {
flags <- strsplit(g$code, "")[[1]] == "1"
values[[sprintf("neyman_n4[%s]", g$code)]] <- g$n4
values[[sprintf("neyman_p[%s]", g$code)]] <- g$p
jj_rows[[length(jj_rows) + 1]] <- list(pattern = if (any(flags)) paste(numeric[flags], collapse = ", ") else "(complete)",
n = g$n, n4 = g$n4, p = g$p, method = if (g$n < 30) "Monte-Carlo" else "χ²(4)")
}
}
test_rows <- list()
if (!is.null(mcar_res)) {
test_rows[[length(test_rows) + 1]] <- list(test = "Little's MCAR test", statistic = mcar_res$statistic, df = mcar_res$df, p = mcar_res$p,
reading = "small p: not MCAR")
}
if (!is.null(jj)) {
test_rows[[length(test_rows) + 1]] <- list(test = "Hawkins: normality and equal covariances", statistic = jj$hawkins_statistic,
df = jj$hawkins_df, p = jj$hawkins_p, reading = "Fisher's combination of the pattern p-values")
if (has_ad) {
test_rows[[length(test_rows) + 1]] <- list(test = "Jamshidian–Jalal: equal covariances (k-sample Anderson–Darling)", statistic = jj$ad_statistic,
df = NULL, p = jj$ad_p, reading = sprintf("permutation p (%s relabelings)", format(reps, big.mark = ",")))
}
}
# %% Missingness vs other variables (SMD)
smd_rows <- list()
if (smd_on) {
for (v in variables) {
r <- is.na(df[[v]])
if (sum(r) < 2 || sum(!r) < 2) next
for (w in variables) {
if (w == v || kinds[[w]] != "numeric") next
xw <- as.numeric(df[[w]])
d <- cs_missing_smd(xw[r], xw[!r])
if (!is.finite(d)) next
values[[sprintf("smd[%s|%s]", v, w)]] <- d
smd_rows[[length(smd_rows) + 1]] <- list(missing = v, variable = w, n_missing = sum(r), n_observed = sum(!r),
mean_missing = mean(xw[r], na.rm = TRUE), mean_observed = mean(xw[!r], na.rm = TRUE),
smd = d, flag = if (abs(d) > 0.2) "|SMD| > 0.2" else "")
}
}
}
values$n_smd_flagged <- sum(vapply(smd_rows, function(s) abs(s$smd) > 0.2, logical(1)))
# %% Result
rows <- if (n) unique(round(seq(1, n, length.out = min(n, 5000)))) else integer(0)
chart_cols <- lapply(variables, function(v) {
if (kinds[[v]] == "numeric") cs_col(v, as.numeric(df[[v]][rows]), kind = "numeric") else cs_col(v, as.character(df[[v]][rows]), kind = "categorical")
})
cs_publish(list(
method = "missing.patterns",
methodVersion = "1.1.1",
title = "Missing-data patterns",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = paste0(sprintf("%d of %d rows are complete; %d missingness patterns.", complete, n, nrow(pats)),
if (!is.null(mcar_res)) sprintf(" Little's MCAR test: χ²(%d) = %.2f, %s.", mcar_res$df, mcar_res$statistic, cs_fmt_p(mcar_res$p)) else ""),
apa = if (!is.null(mcar_res)) sprintf("χ²(%d) = %s, %s", mcar_res$df, cs_fmt_num(mcar_res$statistic), cs_fmt_p(mcar_res$p)) else "",
statistics = c(list(list(key = "n_complete", label = "Complete rows", value = complete),
list(key = "n_patterns", label = "Patterns", value = nrow(pats)),
list(key = "mcar_p", label = "Little's MCAR p", value = if (is.null(mcar_res)) NULL else mcar_res$p, format = "p")),
if (!is.null(jj)) list(list(key = "hawkins_p", label = "Hawkins p", value = jj$hawkins_p, format = "p")),
if (has_ad) list(list(key = "ad_p", label = "Jamshidian–Jalal p", value = jj$ad_p, format = "p"))),
tables = list(
list(key = "variables", title = "Missing values by variable", columns = list(
list(key = "variable", label = "Variable", type = "string"), list(key = "kind", label = "Kind", type = "string"),
list(key = "n_missing", label = "Missing", type = "integer"), list(key = "pct_missing", label = "%", type = "percent")), rows = var_rows),
list(key = "patterns", title = "Missingness patterns", columns = list(
list(key = "pattern", label = "Missing variables", type = "string"), list(key = "n", label = "Rows", type = "integer"),
list(key = "pct", label = "%", type = "percent"), list(key = "n_missing_vars", label = "Variables missing", type = "integer")),
rows = pat_rows, note = if (nrow(pats) > max_patterns) sprintf("The %d most common patterns.", max_patterns) else NULL),
list(key = "mcar_tests", title = "Tests of missing completely at random", columns = list(
list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "Statistic", type = "number"),
list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "p"), list(key = "reading", label = "", type = "string")),
rows = test_rows, note = if (has_ad) unname(decisions[jj$decision]) else NULL),
list(key = "neyman", title = "Normality and equal covariances by pattern (Hawkins)", columns = list(
list(key = "pattern", label = "Missing variables", type = "string"), list(key = "n", label = "Rows", type = "integer"),
list(key = "n4", label = "Neyman N₄", type = "number"), list(key = "p", label = "p", type = "p"), list(key = "method", label = "p from", type = "string")),
rows = jj_rows, note = if (!is.null(jj)) sprintf("After one normal imputation from the EM estimate (seed %d); uniform tail probabilities mean normal data with equal covariances.", seed) else NULL),
list(key = "smd", title = "Do rows with missing values differ?", columns = list(
list(key = "missing", label = "Missing in", type = "string"), list(key = "variable", label = "Compared variable", type = "string"),
list(key = "n_missing", label = "n missing", type = "integer"), list(key = "n_observed", label = "n observed", type = "integer"),
list(key = "mean_missing", label = "Mean when missing", type = "number"), list(key = "mean_observed", label = "Mean when observed", type = "number"),
list(key = "smd", label = "SMD", type = "number"), list(key = "flag", label = "", type = "string")), rows = smd_rows)
),
effectSizes = list(),
assumptions = list(),
warnings = warnings,
notes = Filter(Negate(is.null), list(
paste("Little's test compares each pattern's means with EM estimates (multivariate normal, numeric variables). A small p is evidence against",
"missing completely at random (MCAR); a large p does not prove MCAR. Complete-case analysis is unbiased only under MCAR."),
"SMD > 0.2 in absolute value: rows missing one variable differ on another, so missingness depends on observed data (MAR-like) — consider multiple imputation.",
if (!is.null(jj)) paste("Hawkins and Jamshidian–Jalal: patterns are imputed once from the EM estimate. Hawkins' test rejects when the data are not normal or covariances differ",
"across patterns; the nonparametric Anderson–Darling test separates the two. A rejection is about this imputed data set — repeat with another seed to see how stable it is.")
)),
charts = list(cs_chart("matrix", "missing-matrix", "Missing values by row", list(vars = chart_cols)),
cs_chart("patterns", "upset", "Missingness patterns", list(vars = chart_cols))),
values = values
))
181 of 240 rows are complete; 2 missingness patterns.
- Complete rows
- 181
- Patterns
- 2
- Little's MCAR p
- —
- Hawkins p
- .117
- Jamshidian–Jalal p
- .803
To keep this page light, the plots are shown once, under the R tab.
Missing values by variable
| Variable | Kind | Missing | % |
|---|---|---|---|
| v3 | numeric | 0 | 0.0% |
| v4 | numeric | 0 | 0.0% |
| income | numeric | 59 | 24.6% |
Missingness patterns
| Missing variables | Rows | % | Variables missing |
|---|---|---|---|
| (complete) | 181 | 75.4% | 0 |
| income | 59 | 24.6% | 1 |
Tests of missing completely at random
| Test | Statistic | df | p | |
|---|---|---|---|---|
| Hawkins: normality and equal covariances | 7.393 | 4 | 0.1165 | Fisher's combination of the pattern p-values |
| Jamshidian–Jalal: equal covariances (k-sample Anderson–Darling) | 0.4222 | — | 0.8033 | permutation p (299 relabelings) |
No evidence against MCAR: after imputation the data look normal with equal covariances across the missingness patterns.
Normality and equal covariances by pattern (Hawkins)
| Missing variables | Rows | Neyman N₄ | p | p from |
|---|---|---|---|---|
| (complete) | 181 | 9.379 | 0.0523 | χ²(4) |
| income | 59 | 3.523 | 0.4744 | χ²(4) |
After one normal imputation from the EM estimate (seed 1); uniform tail probabilities mean normal data with equal covariances.
Do rows with missing values differ?
| Missing in | Compared variable | n missing | n observed | Mean when missing | Mean when observed | SMD | |
|---|---|---|---|---|---|---|---|
| income | v3 | 59 | 181 | 0.0290 | 0.0123 | 0.0176 | |
| income | v4 | 59 | 181 | 1.265 | −0.4318 | 2.714 | |SMD| > 0.2 |
- Little's test compares each pattern's means with EM estimates (multivariate normal, numeric variables). A small p is evidence against missing completely at random (MCAR); a large p does not prove MCAR. Complete-case analysis is unbiased only under MCAR.
- SMD > 0.2 in absolute value: rows missing one variable differ on another, so missingness depends on observed data (MAR-like) — consider multiple imputation.
- Hawkins and Jamshidian–Jalal: patterns are imputed once from the EM estimate. Hawkins' test rejects when the data are not normal or covariances differ across patterns; the nonparametric Anderson–Darling test separates the two. A rejection is about this imputed data set — repeat with another seed to see how stable it is.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Missing-data patterns and MCAR tests
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method missing.patterns 1.1.1 · spec 4c63949c97002366
# Dataset: c3_mcar (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.stats import missing as csm
# %% Data (no rows are dropped: missing values are what this analysis is about)
variables = ["v3", "v4", "income"]
kinds = {"income":"numeric","v3":"numeric","v4":"numeric"}
df = pd.read_parquet("tests/parity/fixtures/c3_mcar.parquet", columns=variables)
cs.check_finite_columns(df, variables) # infinite values stop the run (registry/errors.yaml)
n = len(df)
mcar = True
mcar_tests = "jamshidian_jalal"
min_n = int(10)
reps = int(299)
seed = int(1)
alpha = 0.05
run_little = mcar and mcar_tests in ("little", "all")
run_hawkins = mcar and mcar_tests in ("hawkins", "jamshidian_jalal", "all")
run_ad = mcar and mcar_tests in ("jamshidian_jalal", "all")
smd_on = True
max_patterns = int(20)
warnings = []
miss = df.isna().to_numpy()
# %% Per variable and patterns
values = {"n_rows": n, "n_vars": len(variables)}
var_rows = []
for j, v in enumerate(variables):
k = int(miss[:, j].sum())
var_rows.append({"variable": v, "kind": kinds[v], "n_missing": k, "pct_missing": k / n if n else float("nan")})
values[f"missing[{v}]"] = k
values[f"pct_missing[{v}]"] = k / n if n else float("nan")
complete = int((~miss.any(axis=1)).sum())
pats = csm.patterns(miss)
pat_rows = []
for code, count in pats:
missing_vars = [v for v, c in zip(variables, code) if c == "1"]
values[f"pattern_n[{code}]"] = count
if len(pat_rows) < max_patterns:
pat_rows.append({"pattern": ", ".join(missing_vars) if missing_vars else "(complete)", "code": code, "n": count,
"pct": count / n, "n_missing_vars": len(missing_vars)})
worst = max(var_rows, key=lambda r: (r["n_missing"], -variables.index(r["variable"])))
values.update({
"n_complete": complete, "pct_complete": complete / n if n else float("nan"), "n_patterns": len(pats),
"n_cells_missing": int(miss.sum()), "pct_cells_missing": float(miss.mean()) if miss.size else float("nan"),
"most_missing": worst["variable"], "most_missing_pct": worst["pct_missing"],
})
# %% Little's MCAR test (numeric variables; EM estimates of the mean and covariance)
numeric = [v for v in variables if kinds[v] == "numeric" and df[v].notna().sum() > 1 and df[v].std(ddof=1) > 0]
mcar_res = None
if run_little and len(numeric) >= 2 and n > len(numeric):
mcar_res = csm.little_mcar(df[numeric].to_numpy(dtype=float))
elif run_little and len(numeric) >= 2:
# With no more rows than variables the estimated covariance matrix is singular.
warnings.append("Little's test needs more rows than numeric variables; it was not run.")
elif run_little:
warnings.append("Little's test needs at least two numeric variables with variation.")
values.update({
"mcar_done": mcar_res is not None, "mcar_vars": len(numeric) if mcar_res else 0,
"mcar_statistic": None if mcar_res is None else mcar_res["statistic"], "mcar_df": None if mcar_res is None else mcar_res["df"],
"mcar_p": None if mcar_res is None else mcar_res["p"], "mcar_patterns": None if mcar_res is None else mcar_res["patterns"],
})
# %% Hawkins and Jamshidian–Jalal tests (normality and equal covariances across patterns after one imputation)
jj = None
if run_hawkins and len(numeric) >= 2:
jj = csm.jamshidian_jalal(df[numeric].to_numpy(dtype=float), min_n, reps, seed, alpha, nonparametric=run_ad)
if not jj["done"]:
warnings.append(f"The Hawkins and Jamshidian–Jalal tests were not run: {jj['reason']}.")
jj = None
elif jj["n_dropped"]:
warnings.append(f"{jj['n_dropped']} rows in patterns with fewer than {min_n} rows were left out of the Hawkins and Jamshidian–Jalal tests.")
elif run_hawkins:
warnings.append("The Hawkins and Jamshidian–Jalal tests need at least two numeric variables with variation.")
DECISIONS = {
"consistent": "No evidence against MCAR: after imputation the data look normal with equal covariances across the missingness patterns.",
"not_mcar": "Covariances differ across the missingness patterns (Anderson–Darling): evidence against MCAR.",
"non_normal": "The data do not look normal, but covariances do not differ across patterns: no evidence against MCAR.",
}
values.update({
"hawkins_done": jj is not None, "hawkins_statistic": jj["hawkins_statistic"] if jj else None, "hawkins_df": jj["hawkins_df"] if jj else None,
"hawkins_p": jj["hawkins_p"] if jj else None, "hawkins_patterns": jj["n_patterns"] if jj else None, "hawkins_n": jj["n_used"] if jj else None,
"ad_done": bool(jj and "ad_statistic" in jj), "ad_statistic": jj.get("ad_statistic") if jj else None, "ad_p": jj.get("ad_p") if jj else None,
"jj_decision": jj.get("decision") if jj else None,
})
jj_rows = []
if jj:
for g in jj["groups"]:
missing_vars = [v for v, c in zip(numeric, g["code"]) if c == "1"]
values[f"neyman_n4[{g['code']}]"] = g["n4"]
values[f"neyman_p[{g['code']}]"] = g["p"]
jj_rows.append({"pattern": ", ".join(missing_vars) if missing_vars else "(complete)", "n": g["n"], "n4": g["n4"], "p": g["p"],
"method": "Monte-Carlo" if g["n"] < 30 else "χ²(4)"})
test_rows = []
if mcar_res:
test_rows.append({"test": "Little's MCAR test", "statistic": mcar_res["statistic"], "df": mcar_res["df"], "p": mcar_res["p"],
"reading": "small p: not MCAR"})
if jj:
test_rows.append({"test": "Hawkins: normality and equal covariances", "statistic": jj["hawkins_statistic"], "df": jj["hawkins_df"],
"p": jj["hawkins_p"], "reading": "Fisher's combination of the pattern p-values"})
if "ad_statistic" in jj:
test_rows.append({"test": "Jamshidian–Jalal: equal covariances (k-sample Anderson–Darling)", "statistic": jj["ad_statistic"], "df": None,
"p": jj["ad_p"], "reading": f"permutation p ({reps:,} relabelings)"})
# %% Missingness vs other variables (SMD)
smd_rows = []
if smd_on:
for v in variables:
r = df[v].isna().to_numpy()
if r.sum() < 2 or (~r).sum() < 2:
continue
for w in variables:
if w == v or kinds[w] != "numeric":
continue
xw = df[w].to_numpy(dtype=float)
d = csm.smd(xw[r], xw[~r])
if not np.isfinite(d):
continue
values[f"smd[{v}|{w}]"] = d
smd_rows.append({"missing": v, "variable": w, "n_missing": int(r.sum()), "n_observed": int((~r).sum()),
"mean_missing": float(np.nanmean(xw[r])), "mean_observed": float(np.nanmean(xw[~r])), "smd": d,
"flag": "|SMD| > 0.2" if abs(d) > 0.2 else ""})
values["n_smd_flagged"] = sum(1 for s in smd_rows if abs(s["smd"]) > 0.2)
# %% Result
rows = np.unique(np.round(np.linspace(0, n - 1, min(n, 5000))).astype(int)) if n else np.array([], dtype=int)
def chart_col(v):
s = df[v].iloc[rows]
if kinds[v] == "numeric":
return cs.col(v, [None if pd.isna(x) else float(x) for x in s], kind="numeric")
return cs.col(v, [None if pd.isna(x) else str(x) for x in s], kind="categorical")
chart_cols = [chart_col(v) for v in variables]
cs.publish({
"method": "missing.patterns",
"methodVersion": "1.1.1",
"title": "Missing-data patterns",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": f"{complete} of {n} rows are complete; {len(pats)} missingness patterns."
+ (f" Little's MCAR test: χ²({mcar_res['df']}) = {mcar_res['statistic']:.2f}, {cs.fmt_p(mcar_res['p'])}." if mcar_res else ""),
"apa": f"χ²({mcar_res['df']}) = {cs.fmt_num(mcar_res['statistic'])}, {cs.fmt_p(mcar_res['p'])}" if mcar_res else "",
"statistics": [{"key": "n_complete", "label": "Complete rows", "value": complete},
{"key": "n_patterns", "label": "Patterns", "value": len(pats)},
{"key": "mcar_p", "label": "Little's MCAR p", "value": None if mcar_res is None else mcar_res["p"], "format": "p"}]
+ ([{"key": "hawkins_p", "label": "Hawkins p", "value": jj["hawkins_p"], "format": "p"}] if jj else [])
+ ([{"key": "ad_p", "label": "Jamshidian–Jalal p", "value": jj["ad_p"], "format": "p"}] if jj and "ad_p" in jj else []),
"tables": [
{"key": "variables", "title": "Missing values by variable", "columns": [
{"key": "variable", "label": "Variable", "type": "string"}, {"key": "kind", "label": "Kind", "type": "string"},
{"key": "n_missing", "label": "Missing", "type": "integer"}, {"key": "pct_missing", "label": "%", "type": "percent"}], "rows": var_rows},
{"key": "patterns", "title": "Missingness patterns", "columns": [
{"key": "pattern", "label": "Missing variables", "type": "string"}, {"key": "n", "label": "Rows", "type": "integer"},
{"key": "pct", "label": "%", "type": "percent"}, {"key": "n_missing_vars", "label": "Variables missing", "type": "integer"}],
"rows": pat_rows, "note": f"The {max_patterns} most common patterns." if len(pats) > max_patterns else None},
{"key": "mcar_tests", "title": "Tests of missing completely at random", "columns": [
{"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"},
{"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "p"}, {"key": "reading", "label": "", "type": "string"}],
"rows": test_rows, "note": DECISIONS.get(jj.get("decision")) if jj else None},
{"key": "neyman", "title": "Normality and equal covariances by pattern (Hawkins)", "columns": [
{"key": "pattern", "label": "Missing variables", "type": "string"}, {"key": "n", "label": "Rows", "type": "integer"},
{"key": "n4", "label": "Neyman N₄", "type": "number"}, {"key": "p", "label": "p", "type": "p"}, {"key": "method", "label": "p from", "type": "string"}],
"rows": jj_rows, "note": f"After one normal imputation from the EM estimate (seed {seed}); uniform tail probabilities mean normal data with equal covariances." if jj else None},
{"key": "smd", "title": "Do rows with missing values differ?", "columns": [
{"key": "missing", "label": "Missing in", "type": "string"}, {"key": "variable", "label": "Compared variable", "type": "string"},
{"key": "n_missing", "label": "n missing", "type": "integer"}, {"key": "n_observed", "label": "n observed", "type": "integer"},
{"key": "mean_missing", "label": "Mean when missing", "type": "number"}, {"key": "mean_observed", "label": "Mean when observed", "type": "number"},
{"key": "smd", "label": "SMD", "type": "number"}, {"key": "flag", "label": "", "type": "string"}], "rows": smd_rows},
],
"effectSizes": [],
"assumptions": [],
"warnings": warnings,
"notes": [
"Little's test compares each pattern's means with EM estimates (multivariate normal, numeric variables). A small p is evidence against "
"missing completely at random (MCAR); a large p does not prove MCAR. Complete-case analysis is unbiased only under MCAR.",
"SMD > 0.2 in absolute value: rows missing one variable differ on another, so missingness depends on observed data (MAR-like) — consider multiple imputation.",
] + (["Hawkins and Jamshidian–Jalal: patterns are imputed once from the EM estimate. Hawkins' test rejects when the data are not normal or covariances differ "
"across patterns; the nonparametric Anderson–Darling test separates the two. A rejection is about this imputed data set — repeat with another seed to see how stable it is."] if jj else []),
"charts": [cs.chart("matrix", "missing-matrix", "Missing values by row", {"vars": chart_cols}),
cs.chart("patterns", "upset", "Missingness patterns", {"vars": chart_cols})],
"values": values,
})
What the data can see
Read| Mechanism | Gaps depend on | Can the data show it? |
|---|---|---|
| MCARMissing completely at randomMissingness unrelated to any value, observed or not; complete-case analysis stays unbiased. | Nothing | You can reject it, never confirm it |
| MAR | Observed columns | You can see the link to observed columns |
| MNARMissing not at randomMissingness depends on the missing values themselves (e.g. high earners skip income); needs sensitivity analysis. | The missing value itself | No: the values you'd need are missing |
So no test can tell MAR from MNAR. That part of the argument comes from how the data were collected.
Could it be MNAR?
ReflectHigh earners may decline to report income, even among people with the same education and age.
For a column with gaps in your own data, who would decline, fail or get skipped? Would knowing their other columns explain it, or does the reason depend on the missing value itself? How would you find out, other than from the data?
Choosing a method
Read| What you've learned | A reasonable next step |
|---|---|
| Few gaps, no link to any column | Complete cases, reported as an assumption |
| Gaps linked to observed columns | Multiple imputation, including those columns |
| A plausible link to the missing value | Multiple imputation with a sensitivity analysis |
The Data Prep track shows the method in full. Here, the question is how to size it.
How many imputations?
PredictPredict first
A rule of thumb sets the number of imputations to about the largest fraction of missing information.
A cholesterol model has a largest fraction of missing informationFraction of missing informationThe share of a pooled estimate's uncertainty that comes from the missing values, not from sampling. of 0.48, and it was run with = 5.
Is that enough?
Reveal
Too few, by this rule: it suggests about 48. On the air-quality model, the largest fraction is 0.17, which suggests about 17. Run more imputations before you report; a small is fine while exploring.
Check your understanding
CheckpointCheck yourself
Can a statistical test on your data tell MAR from MNAR?
Show the answer
Answer: c
The missing values are what you'd need to check. Use knowledge of the design, and test how much your conclusion depends on the assumption.
Check yourself
Your largest fraction of missing information is . How many imputations does the rule of thumb suggest?
Show the answer
Answer: 30
.
Check yourself
Hawkins and Jamshidian–Jalal say consistent, but one column has a large standardized difference between rows with and without gaps. What do you do?
Show the answer
Answer: b
The tests look at covariances, and the standardized difference looks at means. A link to an observed column is what multiple imputation can use.
Check yourself
Read the air-quality imputation card. What is the largest fraction of missing information? Give two decimals.
Show the answer
Answer: 0.172739900881995
That is the most uncertainty any coefficient takes from the gaps. It sets how many imputations you need for that model.
Do it in CodeSplash
In the appRun the patterns method with its standardized differences on, then multiple imputation with the columns it flags in the model. Set Imputations (m) from the fraction of missing information on your first run.
This script reproduces the card's standardized differences for income. Values near zero mean no link, and v4 stands far out from v3.
import numpy as np
import pandas as pd
d = pd.read_csv("c3_mcar.csv")
gap = d["income"].isna()
for col in ["v3", "v4"]:
a, b = d.loc[gap, col], d.loc[~gap, col]
print(col, (a.mean() - b.mean()) / np.sqrt((a.var() + b.var()) / 2))d <- read.csv("c3_mcar.csv")
gap <- is.na(d$income)
smd <- function(x) {
a <- x[gap]; b <- x[!gap]
(mean(a) - mean(b)) / sqrt((var(a) + var(b)) / 2)
}
c(v3 = smd(d$v3), v4 = smd(d$v4))Recap
Recapconsistentmeans no evidence from that test. Check standardized differences too.- You can see links to observed columns. MNAR is an argument from the design, not a test result.
- Include the columns linked to the gaps in your imputation model.
- Size from the fraction of missing information, and run a sensitivity analysis when MNAR is plausible.
Concepts in this lesson