Skip to content

ADescribe · missing.patterns

Missing-data patterns and MCAR tests

How much is missing, in which patterns — and is it missing completely at random?

Missing values by variable, the missingness patterns and how common each is, tests of missing completely at random — Little's test (EM estimates of a multivariate normal), Hawkins' test of normality and equal covariances across patterns, and the Jamshidian–Jalal nonparametric test that tells non-normal data apart from non-MCAR — and standardized differences showing whether rows with a missing value differ on the other variables.

Verified in Python and R Python and R agree to 6 decimals Seeded Also called Little's MCAR test, Hawkins test, Jamshidian-Jalal test…

A real result

Example “Airquality naniar”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Missing-data patternsRecorded · Python and R agreeRecorded 2026-11-17 · 52 values compared
R

χ²(14) = 35.11, p = .001

Complete rows
111
Patterns
4
Little's MCAR p
.001

Plots

Missing values by rowWhere are the gaps, and do columns go missing together?
View data
OzoneSolar.RWindTempMonthDay
411907.4006751
3611887252
1214912.6007453
1831311.5006254
——14.3005655
28—14.9006656
232998.6006557
199913.8005958
81920.1006159
—1948.60069510
7—6.90074511
162569.70069512
112909.20066513
1427410.90068514
186513.20058515
1433411.50064516
343071266517
67818.40057518
3032211.50068519
11449.70062520
189.70059521
1132016.60073522
4259.70061523
32921261524
—6616.60057525
—26614.90058526
——857527
23131267528
4525214.90081529
1152235.70079530
372797.40076531
—2868.6007861
—2879.7007462
—24216.1006763
—1869.2008464
—2208.6008565
—26414.3007966
291279.7008267
—2736.9008768
7129113.8009069
3932311.50087610
—25910.90093611
—2509.20092612
23148882613
—33213.80080614
—32211.50079615
2119114.90077616
3728420.70072617
20379.20065618
1212011.50073619
1313710.30076620
—1506.30077621
—591.70076622
—914.60076623
—2506.30076624
—135875625
—127878626
—4710.30073627
—9811.50080628
—3114.90077629

First 60 of 153 rows.

Missingness patternsWhich combinations of columns are missing together, and how often?
View data
OzoneSolar.RWindTempMonthDay
411907.4006751
3611887252
1214912.6007453
1831311.5006254
——14.3005655
28—14.9006656
232998.6006557
199913.8005958
81920.1006159
—1948.60069510
7—6.90074511
162569.70069512
112909.20066513
1427410.90068514
186513.20058515
1433411.50064516
343071266517
67818.40057518
3032211.50068519
11449.70062520
189.70059521
1132016.60073522
4259.70061523
32921261524
—6616.60057525
—26614.90058526
——857527
23131267528
4525214.90081529
1152235.70079530
372797.40076531
—2868.6007861
—2879.7007462
—24216.1006763
—1869.2008464
—2208.6008565
—26414.3007966
291279.7008267
—2736.9008768
7129113.8009069
3932311.50087610
—25910.90093611
—2509.20092612
23148882613
—33213.80080614
—32211.50079615
2119114.90077616
3728420.70072617
20379.20065618
1212011.50073619
1313710.30076620
—1506.30077621
—591.70076622
—914.60076623
—2506.30076624
—135875625
—127878626
—4710.30073627
—9811.50080628
—3114.90077629

First 60 of 153 rows.

Missing values by variable

VariableKindMissing%
Ozonenumeric3724.2%
Solar.Rnumeric74.6%
Windnumeric00.0%
Tempnumeric00.0%
Monthnumeric00.0%
Daynumeric00.0%

Missingness patterns

Missing variablesRows%Variables missing
(complete)11172.5%0
Ozone3522.9%1
Solar.R53.3%1
Ozone, Solar.R21.3%2

Tests of missing completely at random

TestStatisticdfp
Little's MCAR test35.106140.0014small p: not MCAR

Normality and equal covariances by pattern (Hawkins)

Missing variablesRowsNeyman N₄pp from

Do rows with missing values differ?

Missing inCompared variablen missingn observedMean when missingMean when observedSMD
OzoneSolar.R37116189.51184.800.0527
OzoneWind3711610.2579.8620.1134
OzoneTemp3711677.91977.8710.0051
OzoneMonth371166.3517.198−0.6765|SMD| > 0.2
OzoneDay3711616.64915.5340.1235
Solar.ROzone714642.80042.0990.0225
Solar.RWind7146910.003−0.2678|SMD| > 0.2
Solar.RTemp71467378.116−0.4411|SMD| > 0.2
Solar.RMonth71466.2867.027−0.4921|SMD| > 0.2
Solar.RDay71469.14316.123−0.8212|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.
Python

χ²(14) = 35.11, p = .001

Complete rows
111
Patterns
4
Little's MCAR p
.001

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

Missing values by variable

VariableKindMissing%
Ozonenumeric3724.2%
Solar.Rnumeric74.6%
Windnumeric00.0%
Tempnumeric00.0%
Monthnumeric00.0%
Daynumeric00.0%

Missingness patterns

Missing variablesRows%Variables missing
(complete)11172.5%0
Ozone3522.9%1
Solar.R53.3%1
Ozone, Solar.R21.3%2

Tests of missing completely at random

TestStatisticdfp
Little's MCAR test35.106140.0014small p: not MCAR

Normality and equal covariances by pattern (Hawkins)

Missing variablesRowsNeyman N₄pp from

Do rows with missing values differ?

Missing inCompared variablen missingn observedMean when missingMean when observedSMD
OzoneSolar.R37116189.51184.800.0527
OzoneWind3711610.2579.8620.1134
OzoneTemp3711677.91977.8710.0051
OzoneMonth371166.3517.198−0.6765|SMD| > 0.2
OzoneDay3711616.64915.5340.1235
Solar.ROzone714642.80042.0990.0225
Solar.RWind7146910.003−0.2678|SMD| > 0.2
Solar.RTemp71467378.116−0.4411|SMD| > 0.2
Solar.RMonth71466.2867.027−0.4921|SMD| > 0.2
Solar.RDay71469.14316.123−0.8212|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.

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

  • Airquality naniarairquality · variables: Ozone, Solar.R, Wind, Temp, Month, Day
  • Survey mixeds1_survey · variables: sex, pulse rate, height, smoke, span_writing, age
  • No mcarairquality · variables: Ozone, month_f
  • Hawkins guide designc3_mcar · variables: v1, v2, v3, v4
  • Jj guide designc3_mcar · variables: v1, v2, v3, v4
  • All small patternc3_mcar · variables: v1, v2, v3, v4, v5
  • Jj mar incomec3_mcar · variables: v3, v4, income
  • Jj unequal covariancesc3_mcar · variables: spread, partner, v3

In the guides

Tests from the statistics guide this method runs

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
  • Automated EDA (profiling, anomaly detection) · DS & ML Decision Guide · Describe — summarize and visualize

What you need

Variablesnumeric / categorical / boolean / temporal · 2–50 columns
The variables to examine (Little's test uses the numeric ones).

Choices you make

hypothesis

Test missing completely at random (MCAR)default on

The tests need at least two numeric variables.

MCAR testsdefault little

Little's test compares pattern means; Hawkins and Jamshidian–Jalal look at covariances, and tell non-normal data from non-MCAR.

  • Little's χ² test(default) — Compares each pattern's means with the EM estimates; assumes multivariate normal data.
  • Hawkins' test of normality and equal covariances — After one imputation, tests whether every pattern looks normal with the same covariance; rejects for either reason.
  • Jamshidian–Jalal (Hawkins + nonparametric test) — Adds a k-sample Anderson–Darling test of equal covariances, which stays valid when the data are not normal.
  • All three — Runs Little's, Hawkins' and Jamshidian–Jalal's tests; pick it to tell non-normal data from non-MCAR.
Significance leveldefault 0.05

Used by the Jamshidian–Jalal decision (normal and MCAR / non-normal / not MCAR).

statistics

Smallest pattern used (rows)default 6

Hawkins and Jamshidian–Jalal leave out patterns with fewer rows (MissMech uses 6).

Compare rows with and without missing values (SMD)default on

Compare rows with and without missing values on each variable using standardized mean differences.

options

Monte-Carlo samplesdefault 999

Simulations for small patterns' Neyman p-values and permutations for the Anderson–Darling p-value.

Random seeddefault 1

Seed of the imputation and Monte-Carlo stream (the same draws in Python and R).

Patterns showndefault 20

Most common missing-value patterns to show.

What it reports

n_rows
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.
n_complete
How many independent units the analysis used; it sets precision and power.
pct_complete
Values that were not recorded; how they went missing decides which fixes are safe.
n_patterns
How many independent units the analysis used; it sets precision and power.
n_cells_missing
How many independent units the analysis used; it sets precision and power.
pct_cells_missing
Values that were not recorded; how they went missing decides which fixes are safe.
most_missing
Values that were not recorded; how they went missing decides which fixes are safe.
most_missing_pct
Values that were not recorded; how they went missing decides which fixes are safe.
mcar_done
Missingness unrelated to any value, observed or not; complete-case analysis stays unbiased.
mcar_vars
Missingness unrelated to any value, observed or not; complete-case analysis stays unbiased.
mcar_statistic
Missingness unrelated to any value, observed or not; complete-case analysis stays unbiased.
mcar_df
How much independent information is left to estimate variability after fitting the model.
mcar_p
How surprising your data would be if the null hypothesis were true, as a probability.
mcar_patterns
Missingness unrelated to any value, observed or not; complete-case analysis stays unbiased.
hawkins_done
Tests whether several groups are multivariate normal with the same covariance; for missing data the groups are the missingness patterns.
hawkins_statistic
Tests whether several groups are multivariate normal with the same covariance; for missing data the groups are the missingness patterns.
hawkins_df
How much independent information is left to estimate variability after fitting the model.
hawkins_p
Tests whether several groups are multivariate normal with the same covariance; for missing data the groups are the missingness patterns.
hawkins_patterns
Tests whether several groups are multivariate normal with the same covariance; for missing data the groups are the missingness patterns.
hawkins_n
Tests whether several groups are multivariate normal with the same covariance; for missing data the groups are the missingness patterns.
ad_done
Tests MCAR via equal covariances across missingness patterns; its nonparametric (Anderson–Darling) version suits non-normal data.
ad_statistic
Tests MCAR via equal covariances across missingness patterns; its nonparametric (Anderson–Darling) version suits non-normal data.
ad_p
Tests MCAR via equal covariances across missingness patterns; its nonparametric (Anderson–Darling) version suits non-normal data.
jj_decision
Tests MCAR via equal covariances across missingness patterns; its nonparametric (Anderson–Darling) version suits non-normal data.
n_smd_flagged
How many independent units the analysis used; it sets precision and power.

Per group, level or term: missing[<variable>], pct_missing[<variable>], pattern_n[<code: 1 = missing, per variable>], smd[<missing variable>|<compared variable>], neyman_n4[<code over the numeric variables>], neyman_p[<code over the numeric variables>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Little's statistic uses EM estimates iterated to 1e-12 in both engines (same algorithm, standardized columns); observed agreement ~1e-15. airquality reproduces naniar::mcar_test (χ² = 35.1, df = 14, p = .00142).
  • Hawkins / Jamshidian–Jalal are written from the papers. Given the same imputed data, MissMech::TestMCARNormality(imputed.data = …) gives the same combined Hawkins p (0.224178181915204) and Anderson–Darling statistic (1.61339660635545) on the guide's design. Differences by design: one normal imputation on the shared Wichmann–Hill stream (MissMech defaults to a distribution-free imputation with R's RNG), Monte-Carlo p-values as (1 + #)/(B + 1), and a label-permutation p-value for the Anderson–Darling test where MissMech interpolates Scholz & Stephens' asymptotic table (0.529 vs our 0.552 on that example).
Python

The exact script CodeSplash ran for example “Airquality naniar” · 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 97315f9f1884aa9d
# Dataset: airquality (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 = ["Ozone", "Solar.R", "Wind", "Temp", "Month", "Day"]
kinds = {"Day":"numeric","Month":"numeric","Ozone":"numeric","Solar.R":"numeric","Temp":"numeric","Wind":"numeric"}
df = pd.read_parquet("tests/parity/fixtures/airquality.parquet", columns=variables)
cs.check_finite_columns(df, variables)  # infinite values stop the run (registry/errors.yaml)
n = len(df)
mcar = True
mcar_tests = "little"
min_n = int(6)
reps = int(999)
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,
})
R

The exact script CodeSplash ran for example “Airquality naniar” · 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 97315f9f1884aa9d
# Dataset: airquality (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("Ozone", "Solar.R", "Wind", "Temp", "Month", "Day")
kinds <- c(
  "Ozone" = "numeric",
  "Solar.R" = "numeric",
  "Wind" = "numeric",
  "Temp" = "numeric",
  "Month" = "numeric",
  "Day" = "numeric"
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/airquality.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 <- "little"
min_n <- as.integer(6)
reps <- as.integer(999)
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
))

Sources

  • Little, R. J. A. (1988). A test of missing completely at random for multivariate data with missing values. JASA, 83, 1198–1202.
  • Dempster, A. P., Laird, N. M., & Rubin, D. B. (1977). Maximum likelihood from incomplete data via the EM algorithm. JRSS B, 39, 1–38.
  • Hawkins, D. M. (1981). A new test for multivariate normality and homoscedasticity. Technometrics, 23, 105–110.
  • Jamshidian, M., & Jalal, S. (2010). Tests of homoscedasticity, normality, and missing completely at random for incomplete multivariate data. Psychometrika, 75, 649–674.
  • Scholz, F. W., & Stephens, M. A. (1987). K-sample Anderson–Darling tests. JASA, 82, 918–924.
  • Tierney, N., & Cook, D. (2023). Expanding tidy data principles to facilitate missing data exploration, visualization and assessment of imputations. Journal of Statistical Software, 105(7).

From the CodeSplash method registry · missing.patterns v1.1.1.