BMultivariate · multivariate.box_m
Box's M test of equal covariance matrices
Do the groups share the same covariance matrix of several variables?
Box's M compares the groups' covariance matrices through their log-determinants, with Box's χ² and F approximations, each group's log-determinant next to the pooled one, and data ellipses of the first two variables. Very sensitive to non-normality and large samples, so it is usually judged at α = 0.001.
A real result
Example “Guide two groups”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Box's M = 5.86, χ²(6) = 5.64, p = .464
- M
- 5.862
- χ²
- 5.642
- df
- 6
- F
- 0.9402
- F df2
- 49155.68
- p
- .464
Plots
View data
| group | y1 | y2 |
|---|---|---|
| g1 | 0.5206 | −1.157 |
| g1 | −1.080 | 0.7780 |
| g1 | 0.1392 | −1.204 |
| g1 | −0.0847 | 0.3067 |
| g1 | −0.6666 | −0.8337 |
| g1 | −2.516 | 1.418 |
| g1 | −0.7351 | 0.7118 |
| g1 | −1.020 | −0.4025 |
| g1 | 0.1136 | 0.7994 |
| g1 | −0.4738 | 0.4265 |
| g1 | −0.4082 | −1.170 |
| g1 | −0.7304 | −0.2062 |
| g1 | −0.2214 | −0.9306 |
| g1 | −0.2258 | 0.4494 |
| g1 | −2.547 | −0.6448 |
| g1 | 1.347 | −0.2314 |
| g1 | 0.6164 | −1.236 |
| g1 | 0.2176 | −0.9610 |
| g1 | −0.8047 | 0.1340 |
| g1 | 0.6897 | −0.9991 |
| g1 | −0.3287 | −0.1415 |
| g1 | −0.1647 | 0.1673 |
| g1 | −1.392 | −0.1988 |
| g1 | 1.466 | −0.2912 |
| g1 | 0.0482 | −1.734 |
| g1 | 1.908 | −0.2727 |
| g1 | 1.731 | −1.800 |
| g1 | 0.0581 | 1.153 |
| g1 | 0.6453 | −1.003 |
| g1 | 1.726 | 0.1482 |
| g1 | −0.5290 | 0.5195 |
| g1 | 0.1664 | 0.0054 |
| g1 | −0.2547 | 1.347 |
| g1 | 0.3328 | −0.8470 |
| g1 | 0.1824 | 0.4434 |
| g1 | 1.165 | −0.9771 |
| g1 | 0.5935 | 2.124 |
| g1 | −0.8918 | 0.6877 |
| g1 | 0.5773 | −0.3434 |
| g1 | −0.8249 | 0.7852 |
| g2 | 2.206 | −0.0921 |
| g2 | 2.432 | −0.3867 |
| g2 | 0.5315 | 1.176 |
| g2 | 1.197 | −0.1811 |
| g2 | −1.439 | 0.3684 |
| g2 | 0.7688 | 0.4370 |
| g2 | −0.2441 | −1.559 |
| g2 | 0.1346 | 0.6463 |
| g2 | 0.8522 | 1.802 |
| g2 | 1.333 | 0.2863 |
| g2 | 0.2538 | −0.4752 |
| g2 | 2.939 | 1.611 |
| g2 | 0.8890 | 0.5605 |
| g2 | 0.0976 | 1.314 |
| g2 | 0.7416 | 0.5156 |
| g2 | 0.1997 | 0.9134 |
| g2 | −0.7934 | 1.746 |
| g2 | 0.8032 | 0.9581 |
| g2 | 1.249 | 0.6752 |
| g2 | 0.6828 | −0.3747 |
First 60 of 90 rows.
Assumptions
- Multivariate normality within groups — Mardia skewness p = .734, kurtosis z = 0.20, p = .845.
- Each group larger than the number of variables — Smallest group: 40 rows for 3 variables.
Log-determinants of the covariance matrices
| group | n | ln |S| |
|---|---|---|
| g1 | 40 | −0.1100 |
| g2 | 50 | −0.5283 |
| Pooled | 90 | −0.2763 |
- Box's M with the χ² approximation (1 − c₁)M, c₁ = 0.03758, and Box's F approximation; conventionally judged at α = 0.001 because it is sensitive to non-normality and large samples (Tabachnick & Fidell 2019).
Box's M = 5.86, χ²(6) = 5.64, p = .464
- M
- 5.862
- χ²
- 5.642
- df
- 6
- F
- 0.9402
- F df2
- 49155.68
- p
- .464
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Multivariate normality within groups — Mardia skewness p = .734, kurtosis z = 0.20, p = .845.
- Each group larger than the number of variables — Smallest group: 40 rows for 3 variables.
Log-determinants of the covariance matrices
| group | n | ln |S| |
|---|---|---|
| g1 | 40 | −0.1100 |
| g2 | 50 | −0.5283 |
| Pooled | 90 | −0.2763 |
- Box's M with the χ² approximation (1 − c₁)M, c₁ = 0.03758, and Box's F approximation; conventionally judged at α = 0.001 because it is sensitive to non-normality and large samples (Tabachnick & Fidell 2019).
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
- Guide two groupsmv_guide · group: group · variables: y1, y2, y3
- Iris speciesiris · group: Species · variables: Sepal.Length, Sepal.Width, Petal.Length, Petal.Width
- Iris f approximationiris · group: Species · variables: Sepal.Length, Petal.Length
- Unequal simmv_sim_unequal · group: group · variables: x1, x2, x3
- Degenerate constantmv_guide · group: group · variables: y1, y2, y3
- Degenerate single levelmv_guide · group: group · variables: y1, y2, y3
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Factorial designs, covariates, multivariate (ANCOVA, MANOVA) · Statistics Guide · B — Compare groups
What you need
- Variablesnumeric · 2–20 columns
- The numeric variables whose covariance matrix is compared across groups (each group needs more rows than variables).
- Groupscategorical / boolean · 1 column · 2–30 levels
- The groups to compare.
Choices you make
hypothesis
- Reference distributiondefault chisq
Which approximation leads the result (both are reported).
- χ² (Box 1949)(default) — (1 − c₁)M against χ² with (k − 1)p(p + 1)/2 df; the usual report (heplots::boxM).
- F (Box 1949) — Box's F approximation (SPSS); better with small groups or many variables.
- Significance leveldefault 0.001
Box's M is conventionally judged at α = 0.001 because it flags trivial differences in large or non-normal samples.
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.
Multivariate normality within groups
Box's M is far more sensitive to non-normality (kurtosis) than to unequal covariances.
Each group larger than the number of variables
Groups with n ≤ p have singular covariance matrices; aim for n ≥ 20 per group.
What it reports
- Tests: Equal covariance matrices
- m
- How many independent groups the result rests on, such as the studies in a multilevel meta-analysis.
- chisq
- A sum of squared, scaled differences between observed and expected counts or estimates.
- df
- How much independent information is left to estimate variability after fitting the model.
- chisq_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- f
- The ratio of explained to unexplained variance, used by ANOVA and regression tests.
- f_df1
- How much independent information is left to estimate variability after fitting the model.
- f_df2
- How much independent information is left to estimate variability after fitting the model.
- f_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- p
- How surprising your data would be if the null hypothesis were true, as a probability.
- k
- How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
- n
- How many independent units the analysis used; it sets precision and power.
- dims
- How many outcome columns a multivariate test compares at once. More of them need more rows per group.
- logdet_pooled
- Tests whether groups share one covariance matrix, by comparing their log-determinants.
- mardia_skew_p
- Multivariate skewness and kurtosis tests of whether rows (or residuals) are multivariate normal.
- mardia_kurt_p
- Multivariate skewness and kurtosis tests of whether rows (or residuals) are multivariate normal.
- missing_share
- Values that were not recorded; how they went missing decides which fixes are safe.
Per group, level or term: logdet[<group>]
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
The exact script CodeSplash ran for example “Guide two groups” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Box's M test of equal covariance matrices
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.box_m 1.0.1 · spec 9d8a9f700a8532ea
# Dataset: mv_guide (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
from scipy import stats
import codesplash as cs
from codesplash.stats import multivariate as mv
# %% Data
df = pd.read_parquet("tests/parity/fixtures/mv_guide.parquet", columns=["y1", "y2", "y3", "group"])
n_input = len(df)
df["group"] = pd.Categorical(df["group"], categories=["g1", "g2"]) # stored level order
df = df.dropna(subset=["y1", "y2", "y3", "group"]) # listwise deletion over the analysis columns
df["group"] = df["group"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["y1", "y2", "y3", "group"]) # infinite values stop the run (registry/errors.yaml)
# %% Test
# Box (1949): M = (N − k) ln|S_p| − Σ (n_j − 1) ln|S_j| with χ² and F approximations (heplots::boxM).
variables = ["y1", "y2", "y3"]
g = "group"
approximation = "chisq" # chisq | f
alpha = 0.001
levels = [str(lv) for lv in df[g].cat.categories]
k = len(levels)
if k < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=g, min=2, k=k)
Y = df[variables].to_numpy(dtype=float)
codes = df[g].cat.codes.to_numpy()
groups = [Y[codes == i] for i in range(k)]
dims = len(variables)
small = [(lv, x.shape[0]) for lv, x in zip(levels, groups) if x.shape[0] <= dims]
if small: # each group's covariance matrix needs more rows than variables
cs.cs_error("CS_E_SMALL_GROUP", min=dims + 1, group=small[0][0], n=small[0][1])
for j, v in enumerate(variables):
if len(np.unique(Y[:, j])) < 2: # a constant variable makes every covariance matrix singular
cs.cs_error("CS_E_CONSTANT", column=v)
res = mv.box_m(groups)
p = res["f_p"] if approximation == "f" else res["p"]
n = int(Y.shape[0])
# %% Assumptions
resid = np.vstack([x - x.mean(axis=0) for x in groups])
assumptions = []
mardia = mv.mardia(resid) if n > dims + 1 else None
if mardia is not None:
ok = mardia["skew_p"] >= 0.05 and mardia["kurt_p"] >= 0.05
assumptions.append({"key": "mv_normality", "label": "Multivariate normality within groups", "status": "pass" if ok else "warn",
"statistic": mardia["kurt_z"], "p": min(mardia["skew_p"], mardia["kurt_p"]),
"detail": f"Mardia skewness {cs.fmt_p(mardia['skew_p'])}, kurtosis z = {mardia['kurt_z']:.2f}, {cs.fmt_p(mardia['kurt_p'])}"
+ ("." if ok else "; Box's M then often rejects because of the tails, not the covariances — read it with care.")})
min_n = int(min(x.shape[0] for x in groups))
assumptions.append({"key": "group_size", "label": "Each group larger than the number of variables", "status": "pass" if min_n >= 20 else "info",
"detail": f"Smallest group: {min_n} rows for {dims} variables" + ("." if min_n >= 20 else "; small groups make Box's M unstable — prefer the F approximation.")})
# %% Result
reject = p < alpha
summary = (f"Box's M = {res['m']:.2f} compares the covariance matrices of {', '.join(variables)} across {k} groups of {g}: "
+ (f"they differ ({'F' if approximation == 'f' else 'χ²'} approximation, {cs.fmt_p(p)} < α = {alpha:g})." if reject
else f"no evidence that they differ ({'F' if approximation == 'f' else 'χ²'} approximation, {cs.fmt_p(p)}, α = {alpha:g})."))
spread = max(res["logdet"]) - min(res["logdet"])
summary += f" Log-determinants range over {spread:.2f} (generalized variance ratio {np.exp(spread):.1f}×)."
values = {"m": res["m"], "chisq": res["chisq"], "df": res["df"], "chisq_p": res["p"], "f": res["f"], "f_df1": res["f_df1"], "f_df2": res["f_df2"],
"f_p": res["f_p"], "p": p, "k": k, "n": n, "dims": dims, "logdet_pooled": res["logdet_pooled"],
"mardia_skew_p": None if mardia is None else mardia["skew_p"], "mardia_kurt_p": None if mardia is None else mardia["kurt_p"]}
for lv, ld in zip(levels, res["logdet"]):
values[f"logdet[{lv}]"] = float(ld)
values["missing_share"] = n_dropped / n_input if n_input else 0.0
rows = [{"group": lv, "n": int(x.shape[0]), "logdet": float(ld)} for lv, x, ld in zip(levels, groups, res["logdet"])]
rows.append({"group": "Pooled", "n": n, "logdet": res["logdet_pooled"]})
chart_rows = np.unique(np.round(np.linspace(0, len(df) - 1, min(len(df), 5000))).astype(int))
cs.publish({
"method": "multivariate.box_m",
"methodVersion": "1.0.1",
"title": "Box's M test of equal covariance matrices",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": (f"Box's M = {cs.fmt_num(res['m'])}, F({res['f_df1']:.0f}, {res['f_df2']:.2f}) = {cs.fmt_num(res['f'])}, {cs.fmt_p(p)}" if approximation == "f"
else f"Box's M = {cs.fmt_num(res['m'])}, χ²({res['df']:.0f}) = {cs.fmt_num(res['chisq'])}, {cs.fmt_p(p)}"),
"statistics": [{"key": "m", "label": "M", "value": res["m"]},
{"key": "chisq", "label": "χ²", "value": res["chisq"]}, {"key": "df", "label": "df", "value": res["df"]},
{"key": "f", "label": "F", "value": res["f"]}, {"key": "f_df2", "label": "F df2", "value": res["f_df2"]},
{"key": "p", "label": "p", "value": p, "format": "p"}],
"tables": [{"key": "logdet", "title": "Log-determinants of the covariance matrices",
"columns": [{"key": "group", "label": g, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "logdet", "label": "ln |S|", "type": "number"}],
"rows": rows}],
"effectSizes": [],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Box's M with the χ² approximation (1 − c₁)M, c₁ = {res['c1']:.5f}, and Box's F approximation; conventionally judged at α = 0.001 because it is sensitive to non-normality and large samples (Tabachnick & Fidell 2019)."],
"values": values,
"charts": [cs.chart("ellipse", "confidence-ellipse", f"{variables[0]} and {variables[1]}: 68% data ellipses by {g}", {
"x": cs.col(variables[0], Y[chart_rows, 0]),
"y": cs.col(variables[1], Y[chart_rows, 1]),
"group": cs.col(g, df[g].astype(str).to_numpy()[chart_rows], levels=levels)}, controls={"kind": "data", "level": 0.68})],
})
The exact script CodeSplash ran for example “Guide two groups” · R version 4.5.1 (2025-06-13)
# Box's M test of equal covariance matrices
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.box_m 1.0.1 · spec 9d8a9f700a8532ea
# Dataset: mv_guide (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/mv_guide.parquet", col_select = c("y1", "y2", "y3", "group")))
n_input <- nrow(df)
df[["group"]] <- factor(df[["group"]], levels = c("g1", "g2")) # stored level order
df <- df[stats::complete.cases(df[c("y1", "y2", "y3", "group")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("y1", "y2", "y3", "group")) # infinite values stop the run (registry/errors.yaml)
# %% Test
# Box (1949): M = (N − k) ln|S_p| − Σ (n_j − 1) ln|S_j| with χ² and F approximations (heplots::boxM).
variables <- c("y1", "y2", "y3")
g <- "group"
approximation <- "chisq" # chisq | f
alpha <- 0.001
levels_g <- levels(df[[g]])
k <- length(levels_g)
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = g, min = 2, k = k)
Y <- as.matrix(df[variables])
storage.mode(Y) <- "double"
codes <- as.integer(df[[g]]) - 1L
groups <- lapply(seq_len(k) - 1L, function(i) Y[codes == i, , drop = FALSE])
dims <- length(variables)
group_rows <- vapply(groups, nrow, 0L)
small <- which(group_rows <= dims)
# each group's covariance matrix needs more rows than variables
if (length(small)) cs_error("CS_E_SMALL_GROUP", min = dims + 1, group = levels_g[small[1]], n = group_rows[small[1]])
for (j in seq_along(variables)) {
# a constant variable makes every covariance matrix singular
if (length(unique(Y[, j])) < 2) cs_error("CS_E_CONSTANT", column = variables[j])
}
res <- cs_mv_box_m(groups)
p <- if (approximation == "f") res$f_p else res$p
n <- nrow(Y)
# %% Assumptions
resid <- do.call(rbind, lapply(groups, function(x) sweep(x, 2, colMeans(x))))
assumptions <- list()
mardia <- if (n > dims + 1) cs_mv_mardia(resid) else NULL
if (!is.null(mardia)) {
ok <- mardia$skew_p >= 0.05 && mardia$kurt_p >= 0.05
assumptions[[1]] <- list(key = "mv_normality", label = "Multivariate normality within groups", status = if (ok) "pass" else "warn",
statistic = mardia$kurt_z, p = min(mardia$skew_p, mardia$kurt_p),
detail = paste0(sprintf("Mardia skewness %s, kurtosis z = %.2f, %s", cs_fmt_p(mardia$skew_p), mardia$kurt_z, cs_fmt_p(mardia$kurt_p)),
if (ok) "." else "; Box's M then often rejects because of the tails, not the covariances — read it with care."))
}
min_n <- min(vapply(groups, nrow, 0L))
assumptions[[length(assumptions) + 1]] <- list(key = "group_size", label = "Each group larger than the number of variables", status = if (min_n >= 20) "pass" else "info",
detail = paste0(sprintf("Smallest group: %d rows for %d variables", min_n, dims),
if (min_n >= 20) "." else "; small groups make Box's M unstable — prefer the F approximation."))
# %% Result
reject <- p < alpha
lab <- if (approximation == "f") "F" else "χ²"
summary <- paste0(sprintf("Box's M = %.2f compares the covariance matrices of %s across %d groups of %s: ", res$m, paste(variables, collapse = ", "), k, g),
if (reject) sprintf("they differ (%s approximation, %s < α = %s).", lab, cs_fmt_p(p), format(alpha))
else sprintf("no evidence that they differ (%s approximation, %s, α = %s).", lab, cs_fmt_p(p), format(alpha)))
spread <- max(res$logdet) - min(res$logdet)
summary <- paste(summary, sprintf("Log-determinants range over %.2f (generalized variance ratio %.1f×).", spread, exp(spread)))
values <- list(m = res$m, chisq = res$chisq, df = res$df, chisq_p = res$p, f = res$f, f_df1 = res$f_df1, f_df2 = res$f_df2,
f_p = res$f_p, p = p, k = k, n = n, dims = dims, logdet_pooled = res$logdet_pooled,
mardia_skew_p = if (is.null(mardia)) NULL else mardia$skew_p, mardia_kurt_p = if (is.null(mardia)) NULL else mardia$kurt_p)
for (i in seq_len(k)) values[[sprintf("logdet[%s]", levels_g[i])]] <- res$logdet[i]
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0
rows <- data.frame(group = c(levels_g, "Pooled"), n = c(vapply(groups, nrow, 0L), n), logdet = c(res$logdet, res$logdet_pooled))
chart_rows <- unique(round(seq(1, nrow(df), length.out = min(nrow(df), 5000))))
cs_publish(list(
method = "multivariate.box_m",
methodVersion = "1.0.1",
title = "Box's M test of equal covariance matrices",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = if (approximation == "f") sprintf("Box's M = %s, F(%.0f, %.2f) = %s, %s", cs_fmt_num(res$m), res$f_df1, res$f_df2, cs_fmt_num(res$f), cs_fmt_p(p))
else sprintf("Box's M = %s, χ²(%.0f) = %s, %s", cs_fmt_num(res$m), res$df, cs_fmt_num(res$chisq), cs_fmt_p(p)),
statistics = list(list(key = "m", label = "M", value = res$m),
list(key = "chisq", label = "χ²", value = res$chisq), list(key = "df", label = "df", value = res$df),
list(key = "f", label = "F", value = res$f), list(key = "f_df2", label = "F df2", value = res$f_df2),
list(key = "p", label = "p", value = p, format = "p")),
tables = list(list(key = "logdet", title = "Log-determinants of the covariance matrices",
columns = list(list(key = "group", label = g, type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "logdet", label = "ln |S|", type = "number")),
rows = rows)),
effectSizes = list(),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Box's M with the χ² approximation (1 − c₁)M, c₁ = %.5f, and Box's F approximation; conventionally judged at α = 0.001 because it is sensitive to non-normality and large samples (Tabachnick & Fidell 2019).", res$c1)),
values = values,
charts = list(cs_chart("ellipse", "confidence-ellipse", sprintf("%s and %s: 68%% data ellipses by %s", variables[1], variables[2], g), list(
x = cs_col(variables[1], Y[chart_rows, 1]),
y = cs_col(variables[2], Y[chart_rows, 2]),
group = cs_col(g, as.character(df[[g]][chart_rows]), levels = levels_g)), controls = list(kind = "data", level = 0.68)))
))
Sources
- Box, G. E. P. (1949). A general distribution theory for a class of likelihood criteria. Biometrika, 36, 317–346.
- Friendly, M., & Sigal, M. (2018). Visualizing tests for equality of covariance matrices. The American Statistician, 74, 144–155.
- Tabachnick, B. G., & Fidell, L. S. (2019). Using Multivariate Statistics (7th ed.), §7.3 (Box's M at α = .001). Pearson.
From the CodeSplash method registry · multivariate.box_m v1.0.1.