BMultivariate · multivariate.hotelling
Hotelling's T² (one-sample, two-sample, paired)
Does a mean vector of several outcomes differ from a target, between two groups, or before and after?
Hotelling's T² tests several correlated outcomes at once: one mean vector against a target, two independent groups (pooled covariance, or Krishnamoorthy–Yu's test when the covariance matrices differ), or paired difference vectors. Reports the F transformation, Mahalanobis D, each outcome's difference with T² simultaneous and Bonferroni intervals, and checks multivariate normality and equal covariances.
A real result
Example “One sample guide”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
T² = 1.44, F(3, 37) = 0.45, p = .716, D = 0.19
- T²
- 1.436
- F
- 0.4541
- df1
- 3
- df2
- 37
- p
- .716
Effect size
- Mahalanobis D 0.1895 · negligible
- D² 0.0359
Plots
View data
| Difference from target | CI high | Outcome | CI low |
|---|---|---|---|
| −0.0414 | 0.4336 | y1 | −0.5164 |
| −0.1295 | 0.3008 | y2 | −0.5599 |
| −0.1403 | 0.4084 | y3 | −0.6890 |
View data
| y1 | y2 |
|---|---|
| 0.5206 | −1.157 |
| −1.080 | 0.7780 |
| 0.1392 | −1.204 |
| −0.0847 | 0.3067 |
| −0.6666 | −0.8337 |
| −2.516 | 1.418 |
| −0.7351 | 0.7118 |
| −1.020 | −0.4025 |
| 0.1136 | 0.7994 |
| −0.4738 | 0.4265 |
| −0.4082 | −1.170 |
| −0.7304 | −0.2062 |
| −0.2214 | −0.9306 |
| −0.2258 | 0.4494 |
| −2.547 | −0.6448 |
| 1.347 | −0.2314 |
| 0.6164 | −1.236 |
| 0.2176 | −0.9610 |
| −0.8047 | 0.1340 |
| 0.6897 | −0.9991 |
| −0.3287 | −0.1415 |
| −0.1647 | 0.1673 |
| −1.392 | −0.1988 |
| 1.466 | −0.2912 |
| 0.0482 | −1.734 |
| 1.908 | −0.2727 |
| 1.731 | −1.800 |
| 0.0581 | 1.153 |
| 0.6453 | −1.003 |
| 1.726 | 0.1482 |
| −0.5290 | 0.5195 |
| 0.1664 | 0.0054 |
| −0.2547 | 1.347 |
| 0.3328 | −0.8470 |
| 0.1824 | 0.4434 |
| 1.165 | −0.9771 |
| 0.5935 | 2.124 |
| −0.8918 | 0.6877 |
| 0.5773 | −0.3434 |
| −0.8249 | 0.7852 |
View data
| D² of each row |
|---|
| 1.658 |
| 2.969 |
| 1.761 |
| 2.295 |
| 1.541 |
| 7.210 |
| 1.073 |
| 1.608 |
| 2.088 |
| 4.951 |
| 3.613 |
| 2.766 |
| 1.019 |
| 1.082 |
| 10.271 |
| 2.052 |
| 1.708 |
| 0.8458 |
| 1.487 |
| 1.712 |
| 1.608 |
| 0.2861 |
| 2.114 |
| 3.023 |
| 5.855 |
| 4.546 |
| 5.481 |
| 3.421 |
| 1.491 |
| 4.760 |
| 2.642 |
| 1.089 |
| 3.234 |
| 1.379 |
| 1.100 |
| 1.862 |
| 9.210 |
| 1.986 |
| 5.598 |
| 2.608 |
Assumptions
- Multivariate normality — Mardia skewness χ²(10) = 7.13, p = .713; kurtosis z = -0.49, p = .625.
- More rows than outcomes — 40 rows for 3 outcomes (denominator df = 37).
Outcome by outcome
| Outcome | Mean | Target | Difference from target | 95% T² simultaneous low | 95% T² simultaneous high | 95% Bonferroni low | 95% Bonferroni high | t | p (unadjusted) |
|---|---|---|---|---|---|---|---|---|---|
| y1 | −0.0414 | 0 | −0.0414 | −0.5164 | 0.4336 | −0.4366 | 0.3538 | −0.2621 | .795 |
| y2 | −0.1295 | 0 | −0.1295 | −0.5599 | 0.3008 | −0.4876 | 0.2285 | −0.9051 | .371 |
| y3 | −0.1403 | 0 | −0.1403 | −0.6890 | 0.4084 | −0.5968 | 0.3162 | −0.7688 | .447 |
- One-sample Hotelling's T²; intervals are T² simultaneous (95%, valid for all outcomes and their combinations) and Bonferroni (95% over 3 outcomes); the per-outcome t tests are unadjusted.
T² = 1.44, F(3, 37) = 0.45, p = .716, D = 0.19
- T²
- 1.436
- F
- 0.4541
- df1
- 3
- df2
- 37
- p
- .716
Effect size
- Mahalanobis D 0.1895 · negligible
- D² 0.0359
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Multivariate normality — Mardia skewness χ²(10) = 7.13, p = .713; kurtosis z = -0.49, p = .625.
- More rows than outcomes — 40 rows for 3 outcomes (denominator df = 37).
Outcome by outcome
| Outcome | Mean | Target | Difference from target | 95% T² simultaneous low | 95% T² simultaneous high | 95% Bonferroni low | 95% Bonferroni high | t | p (unadjusted) |
|---|---|---|---|---|---|---|---|---|---|
| y1 | −0.0414 | 0 | −0.0414 | −0.5164 | 0.4336 | −0.4366 | 0.3538 | −0.2621 | .795 |
| y2 | −0.1295 | 0 | −0.1295 | −0.5599 | 0.3008 | −0.4876 | 0.2285 | −0.9051 | .371 |
| y3 | −0.1403 | 0 | −0.1403 | −0.6890 | 0.4084 | −0.5968 | 0.3162 | −0.7688 | .447 |
- One-sample Hotelling's T²; intervals are T² simultaneous (95%, valid for all outcomes and their combinations) and Bonferroni (95% over 3 outcomes); the per-outcome t tests are unadjusted.
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
- One sample guidemv_guide_one · outcomes: y1, y2, y3
- Two sample guidemv_guide · group: group · outcomes: y1, y2, y3
- Unequal covariancesmv_sim_unequal · group: group · outcomes: x1, x2, x3
- Pooled unequal datamv_sim_unequal · group: group · outcomes: x1, x2, x3
- Paired differencesmv_sim_paired · outcomes: post_a, post_b, post_c · paired_with: pre_a, pre_b, pre_c
- One sample targetmv_pottery · outcomes: Al, Fe, Mg
- Degenerate constantmv_guide_one · outcomes: y1, y2, y3
- Degenerate n3mv_guide_one · outcomes: 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
- Outcomesnumeric · 2–30 columns
- Two or more numeric outcomes measured on each row; they are tested jointly, so their correlations count.
- Groups (two)categorical / boolean · 0–1 column · 2–2 levels
- Two independent groups for the two-sample test; leave empty for a one-sample or paired test.
- Paired measurementsnumeric · 0–30 columns
- For paired data, the second measurement of each outcome in the same order (e.g. post-test columns); the test uses the differences.
Choices you make
hypothesis
- Designdefault auto
Which T² test to run; usually read from the roles you filled.
- From the roles(default) — Two-sample when a group is chosen, paired when paired measurements are chosen, otherwise one-sample.
- One sample — The mean vector against a target vector (zeros unless you enter one).
- Two independent samples — Compares the mean vectors of the two groups.
- Paired (difference vectors) — One-sample T² of each row's differences (outcome − paired measurement).
- Target mean vectordefault
One value per outcome (in order); empty means all zeros. For paired data, the hypothesized mean differences.
- Confidence leveldefault 0.95
For the T² simultaneous and Bonferroni intervals of each outcome's difference.
assumptions
- Covariance matricesdefault pooled
Assume the two groups share one covariance matrix, or allow them to differ (the multivariate Behrens–Fisher problem).
- Equal (pooled T²)(default) — Classical two-sample T² with the pooled covariance matrix; exact under multivariate normality with equal covariances.
- Unequal (Krishnamoorthy–Yu) — Modified Nel–Van der Merwe test: T² with S₁/n₁ + S₂/n₂ and approximate F degrees of freedom; holds its size when covariances and sizes differ.
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
Mardia's skewness and kurtosis tests of the (group-centered) rows.
- If violated → MANOVA with Pillai's trace — With two groups the four MANOVA statistics equal T²; Pillai's trace is the most robust framing and adds univariate follow-ups. Changes the question: None — the same mean-vector comparison.
Equal covariance matrices
Two-sample pooled test only: Box's M at α = 0.001 (it is very sensitive to non-normality).
- If violated → Krishnamoorthy–Yu test — Does not assume the two covariance matrices are equal; holds its Type I error with unequal sizes and spreads. Changes the question: None — the same mean-vector difference, tested without pooling the covariances.
More rows than outcomes
T² needs n − p ≥ 1 (one-sample) or n₁ + n₂ − p − 1 ≥ 1 (two-sample); power falls quickly as p nears n.
What it reports
- Tests: Mean vector difference
- t2
- The multivariate t-test — one test of several outcome means at once, using their correlations.
- f
- The ratio of explained to unexplained variance, used by ANOVA and regression tests.
- df1
- How much independent information is left to estimate variability after fitting the model.
- df2
- How much independent information is left to estimate variability after fitting the model.
- p
- How surprising your data would be if the null hypothesis were true, as a probability.
- n
- How many independent units the analysis used; it sets precision and power.
- n1
- How many independent units the analysis used; it sets precision and power.
- n2
- 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.
- paired
- 1 when the test used paired differences between two sets of columns, 0 for one-sample or two-sample designs.
- d2
- Distance between points or means measured in standard deviations, allowing for the variables' correlations.
- mahalanobis_d
- Distance between points or means measured in standard deviations, allowing for the variables' correlations.
- nu
- Two-sample Hotelling's T² that does not assume the groups share a covariance matrix.
- 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.
- box_m_p
- Tests whether groups share one covariance matrix, by comparing their log-determinants.
- missing_share
- Values that were not recorded; how they went missing decides which fixes are safe.
Per group, level or term: diff[<outcome>], ci_low[<outcome>], ci_high[<outcome>], p_uni[<outcome>]
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 “One sample guide” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Hotelling's T² (one-sample, two-sample, paired)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.hotelling 1.0.1 · spec 48f8dfd63f53c637
# Dataset: mv_guide_one (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_one.parquet", columns=["y1", "y2", "y3"])
n_input = len(df)
df = df.dropna(subset=["y1", "y2", "y3"]) # listwise deletion over the analysis columns
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"]) # infinite values stop the run (registry/errors.yaml)
# %% Helpers
def magnitude(x, cuts, labels=("negligible", "small", "medium", "large")):
"""Benchmark label for an effect size (rule set named in the result)."""
if x is None or not np.isfinite(x):
return "undetermined"
for cut, label in zip(cuts, labels):
if abs(x) < cut:
return label
return labels[-1]
# %% Test
# Hotelling (1931); Krishnamoorthy & Yu (2004) when the covariance matrices may differ.
outcomes = ["y1", "y2", "y3"]
group_cols = []
paired_cols = []
design = "one_sample" # auto | one_sample | two_sample | paired
if design == "auto":
design = "two_sample" if group_cols else ("paired" if paired_cols else "one_sample")
variance = "pooled" # pooled | unequal (two-sample)
mu0 = []
conf = 0.95
dims = len(outcomes)
Y = df[outcomes].to_numpy(dtype=float)
n1 = n2 = nu = box = None
labels = None
if design == "two_sample":
if not group_cols:
raise ValueError("Choose a column with two groups for the two-sample test, or change the design")
g = group_cols[0]
labels = [str(lv) for lv in df[g].cat.categories]
if len(labels) != 2:
cs.cs_error("CS_E_GROUP_COUNT", column=g, expected=2, k=len(labels))
if len(Y) < dims + 2: # the pooled covariance needs n₁ + n₂ − 2 ≥ p
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Hotelling's T²", min=dims + 2, n=len(Y))
for j, o in enumerate(outcomes):
if len(np.unique(Y[:, j])) < 2: # a constant outcome makes the covariance matrix singular
cs.cs_error("CS_E_CONSTANT", column=o)
in1 = (df[g] == df[g].cat.categories[0]).to_numpy()
res = mv.hotelling_two(Y[in1], Y[~in1], variance, conf)
n1, n2, nu = res["n1"], res["n2"], res["nu"]
n = n1 + n2
resid = np.where(in1[:, None], Y - res["mean1"], Y - res["mean2"])
S_res = res["Sp"]
if min(n1, n2) > dims:
box = mv.box_m([Y[in1], Y[~in1]])
X = Y
else:
if design == "paired":
if len(paired_cols) != dims:
raise ValueError(f"Choose one paired measurement for each of the {dims} outcomes (in the same order)")
X = Y - df[paired_cols].to_numpy(dtype=float)
else:
X = Y
if len(X) <= dims: # the covariance matrix needs more rows than variables
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Hotelling's T²", min=dims + 1, n=len(X))
for j, o in enumerate(outcomes):
if len(np.unique(X[:, j])) < 2: # a constant variable makes the covariance matrix singular
if design == "paired":
cs.cs_error("CS_E_UNDEFINED", what="Hotelling's T²", reason=f"the paired differences of {o} are all the same")
cs.cs_error("CS_E_CONSTANT", column=o)
res = mv.hotelling_one(X, mu0, conf)
n = res["n"]
resid = X - X.mean(axis=0)
S_res = resid.T @ resid / (n - 1)
d2 = res["d2"]
md = float(np.sqrt(d2))
# %% Assumptions
assumptions = []
mardia = mv.mardia(resid) if n > dims + 1 else None
if mardia is None:
assumptions.append({"key": "mv_normality", "label": "Multivariate normality", "status": "info", "detail": "Mardia's tests need more rows than outcomes + 1."})
else:
ok = mardia["skew_p"] >= 0.05 and mardia["kurt_p"] >= 0.05
status = "pass" if ok else ("info" if n >= 50 else "warn")
assumptions.append({"key": "mv_normality", "label": "Multivariate normality", "status": status, "statistic": mardia["skew"], "p": min(mardia["skew_p"], mardia["kurt_p"]),
"detail": f"Mardia skewness χ²({mardia['skew_df']:.0f}) = {mardia['skew']:.2f}, {cs.fmt_p(mardia['skew_p'])}; kurtosis z = {mardia['kurt_z']:.2f}, {cs.fmt_p(mardia['kurt_p'])}"
+ (("; with this many rows T² is fairly robust." if status == "info" else "; consider MANOVA with Pillai's trace or a larger sample.") if not ok else ".")})
if design == "two_sample":
if variance == "unequal":
assumptions.append({"key": "equal_covariance", "label": "Equal covariance matrices", "status": "info",
"detail": "Not assumed: the Krishnamoorthy–Yu test allows different covariance matrices." + (f" Box's M {cs.fmt_p(box['p'])}." if box else "")})
elif box is None:
assumptions.append({"key": "equal_covariance", "label": "Equal covariance matrices", "status": "info", "detail": "Box's M needs each group larger than the number of outcomes."})
else:
status = "warn" if box["p"] < 0.001 else "pass"
assumptions.append({"key": "equal_covariance", "label": "Equal covariance matrices", "status": status, "statistic": box["chisq"], "p": box["p"],
"detail": f"Box's M χ²({box['df']:.0f}) = {box['chisq']:.2f}, {cs.fmt_p(box['p'])}" + ("; use the unequal-covariance (Krishnamoorthy–Yu) test." if status == "warn" else " (judged at α = 0.001).")})
status = "warn" if res["df2"] < 5 else "pass"
assumptions.append({"key": "sample_size", "label": "More rows than outcomes", "status": status,
"detail": f"{n} rows for {dims} outcomes (denominator df = {res['df2']:.4g})" + ("; power is low and the covariance estimate unstable." if status == "warn" else ".")})
# %% Result
alpha = 1 - conf
p = res["p"]
size = magnitude(md, (0.2, 0.5, 0.8))
if design == "two_sample":
what = f"between {labels[0]} and {labels[1]}"
name = "Two-sample Hotelling's T²" + (" (Krishnamoorthy–Yu, unequal covariances)" if variance == "unequal" else "")
elif design == "paired":
what = "between the paired measurements"
name = "Paired Hotelling's T²"
else:
what = "from the target vector"
name = "One-sample Hotelling's T²"
significance = f"The mean vector differs {what} ({cs.fmt_p(p)})." if p < alpha else f"The data are compatible with no difference {what} ({cs.fmt_p(p)})."
summary = f"{name} on {dims} outcomes ({', '.join(outcomes)}). {significance} Mahalanobis D = {md:.2f} ({size})."
sig_vars = [o for o, pv in zip(outcomes, res["p_uni"]) if pv < alpha]
summary += f" Individually, {len(sig_vars)} of {dims} outcomes differ at α = {alpha:g} (unadjusted)."
values = {
"t2": res["t2"], "f": res["f"], "df1": res["df1"], "df2": res["df2"], "p": p, "n": int(n),
"n1": n1, "n2": n2, "dims": dims, "paired": 1 if design == "paired" else 0, "d2": d2, "mahalanobis_d": md, "nu": nu,
"mardia_skew_p": None if mardia is None else mardia["skew_p"], "mardia_kurt_p": None if mardia is None else mardia["kurt_p"],
"box_m_p": None if box is None else box["p"],
}
for i, o in enumerate(outcomes):
values[f"diff[{o}]"] = float(res["diff"][i])
values[f"ci_low[{o}]"] = float(res["ci_low"][i])
values[f"ci_high[{o}]"] = float(res["ci_high"][i])
values[f"p_uni[{o}]"] = float(res["p_uni"][i])
pct = f"{conf:.0%}"
if design == "two_sample":
cols = [{"key": "outcome", "label": "Outcome", "type": "string"},
{"key": "mean1", "label": f"Mean ({labels[0]})", "type": "number"}, {"key": "mean2", "label": f"Mean ({labels[1]})", "type": "number"}]
rows = [{"outcome": o, "mean1": float(res["mean1"][i]), "mean2": float(res["mean2"][i])} for i, o in enumerate(outcomes)]
diff_label = f"Difference ({labels[0]} − {labels[1]})"
else:
cols = [{"key": "outcome", "label": "Outcome" if design == "one_sample" else "Outcome − paired", "type": "string"},
{"key": "mean1", "label": "Mean", "type": "number"}, {"key": "mean2", "label": "Target", "type": "number"}]
rows = [{"outcome": o, "mean1": float(res["mean"][i]), "mean2": float(res["mu0"][i])} for i, o in enumerate(outcomes)]
diff_label = "Difference from target"
cols += [{"key": "diff", "label": diff_label, "type": "number"},
{"key": "ci_low", "label": f"{pct} T² simultaneous low", "type": "number"}, {"key": "ci_high", "label": f"{pct} T² simultaneous high", "type": "number"},
{"key": "bonf_low", "label": f"{pct} Bonferroni low", "type": "number"}, {"key": "bonf_high", "label": f"{pct} Bonferroni high", "type": "number"},
{"key": "t", "label": "t", "type": "number"}, {"key": "p_uni", "label": "p (unadjusted)", "type": "pvalue"}]
for i, r in enumerate(rows):
r.update({"diff": float(res["diff"][i]), "ci_low": float(res["ci_low"][i]), "ci_high": float(res["ci_high"][i]),
"bonf_low": float(res["bonf_low"][i]), "bonf_high": float(res["bonf_high"][i]), "t": float(res["t"][i]), "p_uni": float(res["p_uni"][i])})
tables = [{"key": "outcomes", "title": "Outcome by outcome", "columns": cols, "rows": rows}]
dist2 = mv.mahalanobis_sq(resid, S_res)
values["missing_share"] = n_dropped / n_input if n_input else 0.0
chart_rows = np.unique(np.round(np.linspace(0, len(df) - 1, min(len(df), 5000))).astype(int))
ellipse = {"x": cs.col(outcomes[0] if design != "paired" else f"{outcomes[0]} − {paired_cols[0]}", X[chart_rows, 0]),
"y": cs.col(outcomes[1] if design != "paired" else f"{outcomes[1]} − {paired_cols[1]}", X[chart_rows, 1])}
if design == "two_sample":
ellipse["group"] = cs.col(group_cols[0], df[group_cols[0]].astype(str).to_numpy()[chart_rows], levels=labels)
cs.publish({
"method": "multivariate.hotelling",
"methodVersion": "1.0.1",
"title": name,
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": int(n),
"summary": summary,
"apa": f"T² = {cs.fmt_num(res['t2'])}, F({res['df1']:.0f}, {res['df2']:.0f}) = {cs.fmt_num(res['f'])}, {cs.fmt_p(p)}, D = {cs.fmt_num(md)}" if variance != "unequal" or design != "two_sample"
else f"T² = {cs.fmt_num(res['t2'])}, F({res['df1']:.0f}, {res['df2']:.2f}) = {cs.fmt_num(res['f'])}, {cs.fmt_p(p)}, D = {cs.fmt_num(md)}",
"statistics": [{"key": "t2", "label": "T²", "value": res["t2"]}, {"key": "f", "label": "F", "value": res["f"]},
{"key": "df1", "label": "df1", "value": res["df1"]}, {"key": "df2", "label": "df2", "value": res["df2"]},
{"key": "p", "label": "p", "value": p, "format": "p"}],
"tables": tables,
"effectSizes": [{"key": "mahalanobis_d", "label": "Mahalanobis D", "value": md, "method": "√[(x̄ − μ)' S⁻¹ (x̄ − μ)] (pooled S for two samples)", "magnitude": size, "ruleSet": "Cohen (1988) d benchmarks"},
{"key": "d2", "label": "D²", "value": d2, "method": "Squared Mahalanobis distance of the mean difference"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"{name}; intervals are T² simultaneous ({pct}, valid for all outcomes and their combinations) and Bonferroni ({pct} over {dims} outcomes); the per-outcome t tests are unadjusted."]
+ ([f"Krishnamoorthy–Yu approximate degrees of freedom ν = {nu:.3f}."] if nu is not None else []),
"values": values,
"charts": [
cs.chart("differences", "forest", f"Differences ({pct} T² simultaneous intervals)", {
"label": cs.col("Outcome", outcomes, "categorical"),
"estimate": cs.col(diff_label, res["diff"], "numeric"),
"low": cs.col("CI low", res["ci_low"], "numeric"),
"high": cs.col("CI high", res["ci_high"], "numeric")}, controls={"reference": 0}),
cs.chart("ellipse", "confidence-ellipse", f"{ellipse['x']['name']} and {ellipse['y']['name']}: means with {pct} confidence ellipses", ellipse,
controls={"kind": "mean", "level": conf}),
cs.chart("mahalanobis", "mahalanobis-qq", "Squared Mahalanobis distances against χ² quantiles", {
"d2": cs.col("D² of each row", dist2[chart_rows], "numeric")}, controls={"df": dims}),
],
})
The exact script CodeSplash ran for example “One sample guide” · R version 4.5.1 (2025-06-13)
# Hotelling's T² (one-sample, two-sample, paired)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.hotelling 1.0.1 · spec 48f8dfd63f53c637
# Dataset: mv_guide_one (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_one.parquet", col_select = c("y1", "y2", "y3")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("y1", "y2", "y3")]), , 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")) # infinite values stop the run (registry/errors.yaml)
# %% Helpers
magnitude <- function(x, cuts, labels = c("negligible", "small", "medium", "large")) {
# Benchmark label for an effect size (rule set named in the result)
if (is.null(x) || !is.finite(x)) return("undetermined")
labels[findInterval(abs(x), cuts) + 1]
}
# %% Test
# Hotelling (1931); Krishnamoorthy & Yu (2004) when the covariance matrices may differ.
outcomes <- c("y1", "y2", "y3")
group_cols <- c()
paired_cols <- c()
design <- "one_sample" # auto | one_sample | two_sample | paired
if (design == "auto") design <- if (length(group_cols)) "two_sample" else if (length(paired_cols)) "paired" else "one_sample"
variance <- "pooled" # pooled | unequal (two-sample)
mu0 <- c()
conf <- 0.95
dims <- length(outcomes)
Y <- as.matrix(df[outcomes])
storage.mode(Y) <- "double"
n1 <- NULL
n2 <- NULL
nu <- NULL
box <- NULL
labels <- NULL
if (design == "two_sample") {
if (!length(group_cols)) stop("Choose a column with two groups for the two-sample test, or change the design")
g <- group_cols[1]
labels <- levels(df[[g]])
if (length(labels) != 2) cs_error("CS_E_GROUP_COUNT", column = g, expected = 2, k = length(labels))
# the pooled covariance needs n1 + n2 - 2 >= p
if (nrow(Y) < dims + 2) cs_error("CS_E_TOO_FEW_ROWS", what = "Hotelling's T²", min = dims + 2, n = nrow(Y))
for (j in seq_len(dims)) {
# a constant outcome makes the covariance matrix singular
if (length(unique(Y[, j])) < 2) cs_error("CS_E_CONSTANT", column = outcomes[j])
}
in1 <- df[[g]] == labels[1]
res <- cs_mv_hotelling_two(Y[in1, , drop = FALSE], Y[!in1, , drop = FALSE], variance, conf)
n1 <- res$n1
n2 <- res$n2
nu <- res$nu
n <- n1 + n2
resid <- Y - t(ifelse(matrix(in1, dims, nrow(Y), byrow = TRUE), res$mean1, res$mean2))
S_res <- res$Sp
if (min(n1, n2) > dims) box <- cs_mv_box_m(list(Y[in1, , drop = FALSE], Y[!in1, , drop = FALSE]))
X <- Y
} else {
if (design == "paired") {
if (length(paired_cols) != dims) stop(sprintf("Choose one paired measurement for each of the %d outcomes (in the same order)", dims))
P <- as.matrix(df[paired_cols])
storage.mode(P) <- "double"
X <- Y - P
} else {
X <- Y
}
# the covariance matrix needs more rows than variables
if (nrow(X) <= dims) cs_error("CS_E_TOO_FEW_ROWS", what = "Hotelling's T²", min = dims + 1, n = nrow(X))
for (j in seq_len(dims)) {
# a constant variable makes the covariance matrix singular
if (length(unique(X[, j])) < 2) {
if (design == "paired") {
cs_error("CS_E_UNDEFINED", what = "Hotelling's T²", reason = sprintf("the paired differences of %s are all the same", outcomes[j]))
}
cs_error("CS_E_CONSTANT", column = outcomes[j])
}
}
res <- cs_mv_hotelling_one(X, mu0, conf)
n <- res$n
resid <- sweep(X, 2, colMeans(X))
S_res <- crossprod(resid) / (n - 1)
}
d2 <- res$d2
md <- sqrt(d2)
# %% Assumptions
assumptions <- list()
mardia <- if (n > dims + 1) cs_mv_mardia(resid) else NULL
if (is.null(mardia)) {
assumptions[[1]] <- list(key = "mv_normality", label = "Multivariate normality", status = "info", detail = "Mardia's tests need more rows than outcomes + 1.")
} else {
ok <- mardia$skew_p >= 0.05 && mardia$kurt_p >= 0.05
status <- if (ok) "pass" else if (n >= 50) "info" else "warn"
assumptions[[1]] <- list(key = "mv_normality", label = "Multivariate normality", status = status, statistic = mardia$skew, p = min(mardia$skew_p, mardia$kurt_p),
detail = paste0(sprintf("Mardia skewness χ²(%.0f) = %.2f, %s; kurtosis z = %.2f, %s", mardia$skew_df, mardia$skew, cs_fmt_p(mardia$skew_p), mardia$kurt_z, cs_fmt_p(mardia$kurt_p)),
if (!ok) (if (status == "info") "; with this many rows T² is fairly robust." else "; consider MANOVA with Pillai's trace or a larger sample.") else "."))
}
if (design == "two_sample") {
if (variance == "unequal") {
assumptions[[length(assumptions) + 1]] <- list(key = "equal_covariance", label = "Equal covariance matrices", status = "info",
detail = paste0("Not assumed: the Krishnamoorthy–Yu test allows different covariance matrices.", if (!is.null(box)) sprintf(" Box's M %s.", cs_fmt_p(box$p)) else ""))
} else if (is.null(box)) {
assumptions[[length(assumptions) + 1]] <- list(key = "equal_covariance", label = "Equal covariance matrices", status = "info", detail = "Box's M needs each group larger than the number of outcomes.")
} else {
status <- if (box$p < 0.001) "warn" else "pass"
assumptions[[length(assumptions) + 1]] <- list(key = "equal_covariance", label = "Equal covariance matrices", status = status, statistic = box$chisq, p = box$p,
detail = paste0(sprintf("Box's M χ²(%.0f) = %.2f, %s", box$df, box$chisq, cs_fmt_p(box$p)),
if (status == "warn") "; use the unequal-covariance (Krishnamoorthy–Yu) test." else " (judged at α = 0.001)."))
}
}
status <- if (res$df2 < 5) "warn" else "pass"
assumptions[[length(assumptions) + 1]] <- list(key = "sample_size", label = "More rows than outcomes", status = status,
detail = paste0(sprintf("%d rows for %d outcomes (denominator df = %s)", as.integer(n), dims, format(signif(res$df2, 4))),
if (status == "warn") "; power is low and the covariance estimate unstable." else "."))
# %% Result
alpha <- 1 - conf
p <- res$p
size <- magnitude(md, c(0.2, 0.5, 0.8))
if (design == "two_sample") {
what <- sprintf("between %s and %s", labels[1], labels[2])
name <- paste0("Two-sample Hotelling's T²", if (variance == "unequal") " (Krishnamoorthy–Yu, unequal covariances)" else "")
} else if (design == "paired") {
what <- "between the paired measurements"
name <- "Paired Hotelling's T²"
} else {
what <- "from the target vector"
name <- "One-sample Hotelling's T²"
}
significance <- if (p < alpha) sprintf("The mean vector differs %s (%s).", what, cs_fmt_p(p)) else sprintf("The data are compatible with no difference %s (%s).", what, cs_fmt_p(p))
summary <- sprintf("%s on %d outcomes (%s). %s Mahalanobis D = %.2f (%s).", name, dims, paste(outcomes, collapse = ", "), significance, md, size)
summary <- paste(summary, sprintf("Individually, %d of %d outcomes differ at α = %s (unadjusted).", sum(res$p_uni < alpha), dims, format(alpha)))
values <- list(t2 = res$t2, f = res$f, df1 = res$df1, df2 = res$df2, p = p, n = as.integer(n), n1 = n1, n2 = n2, dims = dims,
paired = if (design == "paired") 1L else 0L, d2 = d2, mahalanobis_d = md, nu = nu,
mardia_skew_p = if (is.null(mardia)) NULL else mardia$skew_p, mardia_kurt_p = if (is.null(mardia)) NULL else mardia$kurt_p,
box_m_p = if (is.null(box)) NULL else box$p)
for (i in seq_len(dims)) {
o <- outcomes[i]
values[[sprintf("diff[%s]", o)]] <- res$diff[i]
values[[sprintf("ci_low[%s]", o)]] <- res$ci_low[i]
values[[sprintf("ci_high[%s]", o)]] <- res$ci_high[i]
values[[sprintf("p_uni[%s]", o)]] <- res$p_uni[i]
}
pct <- sprintf("%.0f%%", conf * 100)
if (design == "two_sample") {
cols <- list(list(key = "outcome", label = "Outcome", type = "string"),
list(key = "mean1", label = sprintf("Mean (%s)", labels[1]), type = "number"), list(key = "mean2", label = sprintf("Mean (%s)", labels[2]), type = "number"))
m1 <- res$mean1
m2 <- res$mean2
diff_label <- sprintf("Difference (%s − %s)", labels[1], labels[2])
} else {
cols <- list(list(key = "outcome", label = if (design == "one_sample") "Outcome" else "Outcome − paired", type = "string"),
list(key = "mean1", label = "Mean", type = "number"), list(key = "mean2", label = "Target", type = "number"))
m1 <- res$mean
m2 <- res$mu0
diff_label <- "Difference from target"
}
cols <- c(cols, list(list(key = "diff", label = diff_label, type = "number"),
list(key = "ci_low", label = paste(pct, "T² simultaneous low"), type = "number"), list(key = "ci_high", label = paste(pct, "T² simultaneous high"), type = "number"),
list(key = "bonf_low", label = paste(pct, "Bonferroni low"), type = "number"), list(key = "bonf_high", label = paste(pct, "Bonferroni high"), type = "number"),
list(key = "t", label = "t", type = "number"), list(key = "p_uni", label = "p (unadjusted)", type = "pvalue")))
rows <- data.frame(outcome = outcomes, mean1 = m1, mean2 = m2, diff = res$diff, ci_low = res$ci_low, ci_high = res$ci_high,
bonf_low = res$bonf_low, bonf_high = res$bonf_high, t = res$t, p_uni = res$p_uni)
tables <- list(list(key = "outcomes", title = "Outcome by outcome", columns = cols, rows = rows))
dist2 <- cs_mv_mahalanobis_sq(resid, S_res)
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0
chart_rows <- unique(round(seq(1, nrow(df), length.out = min(nrow(df), 5000))))
xname <- if (design == "paired") sprintf("%s − %s", outcomes[1], paired_cols[1]) else outcomes[1]
yname <- if (design == "paired") sprintf("%s − %s", outcomes[2], paired_cols[2]) else outcomes[2]
ellipse <- list(x = cs_col(xname, X[chart_rows, 1]), y = cs_col(yname, X[chart_rows, 2]))
if (design == "two_sample") ellipse$group <- cs_col(group_cols[1], as.character(df[[group_cols[1]]][chart_rows]), levels = labels)
apa_df2 <- if (design == "two_sample" && variance == "unequal") sprintf("%.2f", res$df2) else sprintf("%.0f", res$df2)
cs_publish(list(
method = "multivariate.hotelling",
methodVersion = "1.0.1",
title = name,
engine = cs_engine_info("stats", "nanoparquet"),
n = as.integer(n),
summary = summary,
apa = sprintf("T² = %s, F(%.0f, %s) = %s, %s, D = %s", cs_fmt_num(res$t2), res$df1, apa_df2, cs_fmt_num(res$f), cs_fmt_p(p), cs_fmt_num(md)),
statistics = list(list(key = "t2", label = "T²", value = res$t2), list(key = "f", label = "F", value = res$f),
list(key = "df1", label = "df1", value = res$df1), list(key = "df2", label = "df2", value = res$df2),
list(key = "p", label = "p", value = p, format = "p")),
tables = tables,
effectSizes = list(list(key = "mahalanobis_d", label = "Mahalanobis D", value = md, method = "√[(x̄ − μ)' S⁻¹ (x̄ − μ)] (pooled S for two samples)", magnitude = size, ruleSet = "Cohen (1988) d benchmarks"),
list(key = "d2", label = "D²", value = d2, method = "Squared Mahalanobis distance of the mean difference")),
assumptions = assumptions,
warnings = warnings,
notes = c(list(sprintf("%s; intervals are T² simultaneous (%s, valid for all outcomes and their combinations) and Bonferroni (%s over %d outcomes); the per-outcome t tests are unadjusted.", name, pct, pct, dims)),
if (!is.null(nu)) list(sprintf("Krishnamoorthy–Yu approximate degrees of freedom ν = %.3f.", nu)) else list()),
values = values,
charts = list(
cs_chart("differences", "forest", sprintf("Differences (%s T² simultaneous intervals)", pct), list(
label = cs_col("Outcome", outcomes, "categorical"),
estimate = cs_col(diff_label, res$diff, "numeric"),
low = cs_col("CI low", res$ci_low, "numeric"),
high = cs_col("CI high", res$ci_high, "numeric")), controls = list(reference = 0)),
cs_chart("ellipse", "confidence-ellipse", sprintf("%s and %s: means with %s confidence ellipses", xname, yname, pct), ellipse,
controls = list(kind = "mean", level = conf)),
cs_chart("mahalanobis", "mahalanobis-qq", "Squared Mahalanobis distances against χ² quantiles", list(
d2 = cs_col("D² of each row", dist2[chart_rows], "numeric")), controls = list(df = dims))
)
))
Sources
- Hotelling, H. (1931). The generalization of Student's ratio. Annals of Mathematical Statistics, 2, 360–378.
- Krishnamoorthy, K., & Yu, J. (2004). Modified Nel and Van der Merwe test for the multivariate Behrens–Fisher problem. Statistics & Probability Letters, 66, 161–169.
- Johnson, R. A., & Wichern, D. W. (2007). Applied Multivariate Statistical Analysis (6th ed.), §5.2–5.5, §6.3. Pearson.
- Mardia, K. V. (1970). Measures of multivariate skewness and kurtosis with applications. Biometrika, 57, 519–530.
From the CodeSplash method registry · multivariate.hotelling v1.0.1.