Hotelling's T²: a t test for several outcomes at once
Test a whole mean vector in one step, see why correlation between outcomes changes the answer, and read the distance behind T².
What runs in CodeSplash
- STAT152One sample Hotelling T squared test Runs in CodeSplash
- STAT153Two sample Hotelling T squared test Runs in CodeSplash
- Hotelling's T² (one-sample, two-sample, paired) Verified in Python and R
You will be able to
- Explain why one joint test differs from several separate t tests
- Read T², its F form and the Mahalanobis distance on a result card
- Choose between pooled T² and the unequal-covariance version
Read first
Three outcomes, one question
ExploreYou measure three outcomes on two groups. Three t tests look natural, but they answer three separate questions, each with its own chance of a false alarm.
If the outcomes were independent, three tests at 0.05 give a family-wise error of .
BExplorable · The family-wise error rate
If you run many tests, how likely is at least one false alarm, and what does correcting cost?
Without correction, how often does this family produce at least one false alarm?
Commit your prediction above to see the result
Make your prediction to see the result.
A joint test asks one question: do the groups differ anywhere in this set of means? That single question has a single error rate.
Predict what correlation does
PredictPredict first
Two outcomes are strongly positively correlated. Group A is a little higher on the first and a little lower on the second. Neither t test reaches 0.05.
Could a joint test on both outcomes still find a difference?
Reveal
It can. People who are high on one outcome are usually high on the other, so "high on one, low on the other" is unusual in itself. A joint test uses the correlation between outcomes, and separate t tests can't.
From t to T²
ReadSquare the t statistic and write it with the inverse of the variance:
Hotelling's T²Hotelling's T²The multivariate t-test — one test of several outcome means at once, using their correlations. is that same form with vectors and a covariance matrix :
is the part that matters. It measures the gap in standard deviations and allows for correlation. That measure is the Mahalanobis distanceMahalanobis distanceDistance between points or means measured in standard deviations, allowing for the variables' correlations., and T² is that squared distance scaled up by the sample size.
Read a two-sample result
In the appA simulated study compares three outcomes in 40 and 50 rows.
T² = 24.40, F(3, 86) = 7.95, p < .001, D = 1.05
- T²
- 24.399
- F
- 7.948
- df1
- 3
- df2
- 86
- p
- < .001
Effect size
- Mahalanobis D 1.048 · large
- D² 1.098
Plots
View data
| Difference (g1 − g2) | CI high | Outcome | CI low |
|---|---|---|---|
| −0.5488 | 0.0285 | y1 | −1.126 |
| −0.6025 | −0.0273 | y2 | −1.178 |
| −0.4995 | 0.1223 | y3 | −1.121 |
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.
View data
| D² of each row |
|---|
| 2.013 |
| 3.910 |
| 1.980 |
| 2.447 |
| 1.273 |
| 8.630 |
| 1.132 |
| 1.693 |
| 2.447 |
| 6.425 |
| 4.314 |
| 3.150 |
| 0.8975 |
| 1.411 |
| 11.042 |
| 2.201 |
| 1.977 |
| 0.8316 |
| 1.688 |
| 1.697 |
| 1.913 |
| 0.2725 |
| 2.192 |
| 3.363 |
| 4.986 |
| 4.965 |
| 6.749 |
| 3.958 |
| 1.901 |
| 4.762 |
| 2.764 |
| 1.226 |
| 2.698 |
| 1.305 |
| 0.9415 |
| 2.097 |
| 7.354 |
| 2.608 |
| 6.619 |
| 2.620 |
| 3.338 |
| 10.079 |
| 1.111 |
| 1.338 |
| 4.689 |
| 1.301 |
| 6.291 |
| 0.9918 |
| 2.466 |
| 1.261 |
| 1.262 |
| 9.729 |
| 0.3846 |
| 0.8933 |
| 0.4656 |
| 0.6266 |
| 9.858 |
| 0.6737 |
| 0.8701 |
| 5.414 |
First 60 of 90 rows.
Assumptions
- Multivariate normality — Mardia skewness χ²(10) = 6.91, p = .734; kurtosis z = 0.20, p = .845.
- Equal covariance matrices — Box's M χ²(6) = 5.64, p = .464 (judged at α = 0.001).
- More rows than outcomes — 90 rows for 3 outcomes (denominator df = 86).
Outcome by outcome
| Outcome | Mean (g1) | Mean (g2) | Difference (g1 − g2) | 95% T² simultaneous low | 95% T² simultaneous high | 95% Bonferroni low | 95% Bonferroni high | t | p (unadjusted) |
|---|---|---|---|---|---|---|---|---|---|
| y1 | −0.0414 | 0.5074 | −0.5488 | −1.126 | 0.0285 | −1.037 | −0.0604 | −2.742 | .007 |
| y2 | −0.1295 | 0.4730 | −0.6025 | −1.178 | −0.0273 | −1.089 | −0.1159 | −3.022 | .003 |
| y3 | −0.1403 | 0.3592 | −0.4995 | −1.121 | 0.1223 | −1.026 | 0.0266 | −2.317 | .023 |
- Two-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.
The exact R script · R 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 78aef5af295673af
# 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)
# %% 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("group")
paired_cols <- c()
design <- "two_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))
)
))
T² = 24.40, F(3, 86) = 7.95, p < .001, D = 1.05
- T²
- 24.399
- F
- 7.948
- df1
- 3
- df2
- 86
- p
- < .001
Effect size
- Mahalanobis D 1.048 · large
- D² 1.098
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Multivariate normality — Mardia skewness χ²(10) = 6.91, p = .734; kurtosis z = 0.20, p = .845.
- Equal covariance matrices — Box's M χ²(6) = 5.64, p = .464 (judged at α = 0.001).
- More rows than outcomes — 90 rows for 3 outcomes (denominator df = 86).
Outcome by outcome
| Outcome | Mean (g1) | Mean (g2) | Difference (g1 − g2) | 95% T² simultaneous low | 95% T² simultaneous high | 95% Bonferroni low | 95% Bonferroni high | t | p (unadjusted) |
|---|---|---|---|---|---|---|---|---|---|
| y1 | −0.0414 | 0.5074 | −0.5488 | −1.126 | 0.0285 | −1.037 | −0.0604 | −2.742 | .007 |
| y2 | −0.1295 | 0.4730 | −0.6025 | −1.178 | −0.0273 | −1.089 | −0.1159 | −3.022 | .003 |
| y3 | −0.1403 | 0.3592 | −0.4995 | −1.121 | 0.1223 | −1.026 | 0.0266 | −2.317 | .023 |
- Two-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.
The exact Python script · Python 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 78aef5af295673af
# 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)
# %% 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 = ["group"]
paired_cols = []
design = "two_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}),
],
})
T² = 24.40 becomes F(3, 86) = 7.95, p < .001. The squared distance is = 1.10, so the groups sit about one standard deviation apart in the joint space.
Open the Outcome by outcome table, with its simultaneous and Bonferroni intervals. Which outcome has the widest interval?
Three designs, one statistic
Reflect| Design | What is tested | Example here |
|---|---|---|
| One sample | Mean vector against a target | Pottery Al, Fe and Mg against a target: p = .447 |
| Two samples | Two mean vectors | The study above |
| Paired | Mean vector of each row's differences | Three scores before and after: p = .002 |
A one-sample result with a large p, such as p = .716 on standard-normal data, says the data are compatible with the target. It doesn't show that the target is right.
Which of your measurements come as a set, where one joint question would be more honest than many small ones?
When covariances differ
PredictPredict first
The pooled T² assumes both groups share one covariance matrix. Here Box's M gives p < .001, with 25 and 40 rows.
What should you expect if you switch to a test that doesn't pool?
Reveal
They differ. Pooled gives p = .339, and the Krishnamoorthy–Yu test gives p = .175. Unequal sizes make this worse, because pooling then weights the larger group's covariance. Set Covariance matrices to Unequal when you doubt the assumption.
Check your understanding
CheckpointCheck yourself
The two-sample F form is . With , , and , what is F? Give two decimals.
Show the answer
Answer: 7.94806836167028
. The result card shows the same value.
Check yourself
Why does T² use the inverse covariance matrix rather than adding up separate squared t statistics?
Show the answer
Answer: b
Correlated outcomes share information. The inverse covariance discounts what is shared and highlights differences that run against the correlation.
Check yourself
T² gives p = 0.002. Which statement can you defend?
Show the answer
Answer: b
The joint test says something differs somewhere in the set. It doesn't say which outcome, and it can reject when no single outcome does.
Do it in CodeSplash
In the appChoose your Outcomes, then Groups (two) for two samples or Paired measurements for matched columns. Design follows the roles you fill.
import pandas as pd
import pingouin as pg
df = pd.read_csv("study.csv")
X = df.loc[df["group"] == "g1", ["y1", "y2", "y3"]]
Y = df.loc[df["group"] == "g2", ["y1", "y2", "y3"]]
print(pg.multivariate_ttest(X, Y))# install.packages("ICSNP")
df <- read.csv("study.csv")
X <- df[df$group == "g1", c("y1", "y2", "y3")]
Y <- df[df$group == "g2", c("y1", "y2", "y3")]
ICSNP::HotellingsT2(X, Y)Recap
Recap- T² is a t test for a set of means, with one error rate for the set.
- It uses the correlation between outcomes, so it can find differences that separate t tests miss.
- Report the distance and the intervals, not only p.
- If covariances look unequal, use the unequal-covariance version rather than the pooled one.
Concepts in this lesson