Skip to content

BCompare groups · Guide test 168

Energy two sample or k sample test

Tests equality of multivariate distributions using within sample and between sample distances.

Runs in CodeSplashPython (calls R) example not runR example validated

Do it in CodeSplash

In the app, set it up in Analyze with this method:

In Multivariate tests of equal distributions (energy, MMD, DISCO, classifier), choose Test = Energy test.

Do it in CodeSplash Run this test on your own data, in Python or R.

Bench

Change the design, drag the data, move α. The statistic, its reference distribution and the verdict follow.

Bench · Energy two sample or k sample test

20
25
0.60
0.00
0.50
0.050

Your data

Simulated with known truth

2 groups on two measurements; crosses mark the group means.

If H₀ were true

E = 5.24
  1. The reference: how E varies across samples when H₀ is true, E over relabelings of the pooled rows (permutation null: 199 relabelings of these data (seed 20261107)).
  2. Your statistic, from the data above.
  3. The p-value: the area at least as extreme as yours (p = .030).
  4. The hatched rejection region at α = .050: statistics landing here reject H₀.

The formula

E=n1n2n1+n2(2 ∥X−Y∥‾−∥X−X′∥‾−∥Y−Y′∥‾)\mathcal E = \dfrac{n_1n_2}{n_1+n_2}\Bigl(2\,\overline{\|X - Y\|} - \overline{\|X - X'\|} - \overline{\|Y - Y'\|}\Bigr)

With your numbers

E=5.24,n1=20, n2=25\mathcal E = 5.24,\qquad n_1 = 20,\ n_2 = 25
∥X−Y∥‾\overline{\|X-Y\|}
mean distance between the groups
∥X−X′∥‾\overline{\|X-X'\|}
mean distance within group 1

The verdict

E = 5.24, p = .030

p ≤ α = .050: reject H₀

Zero only when the distributions are identical, so it detects differences in location, spread or shape. The p-value comes from relabelling the pooled rows.

Statistic
5.237
p-value
0.0300
Energy two sample or k sample test on two groups of 20 and 25 rows on two variables: E = 5.24, p = .030. The p-value is below α = .050, so the data are hard to reconcile with H0.

Energy two sample or k sample test on two groups of 20 and 25 rows on two variables: E = 5.24, p = .030. The p-value is below α = .050, so the data are hard to reconcile with H₀.

Question and hypotheses

H0: independent samples have identical distributions.

Assumptions

Independent samples with finite first distance moments; an appropriate distance of strong negative type for broad consistency.

Formula

E=2mn∑ij∥Xi−Yj∥−1m2∑ii′∥Xi−Xi′∥−1n2∑jj′∥Yj−Yj′∥\mathcal E=\frac2{mn}\sum_{ij}\|X_i-Y_j\|-\frac1{m^2}\sum_{ii^\prime}\|X_i-X_{i^\prime}\|-\frac1{n^2}\sum_{jj^\prime}\|Y_j-Y_{j^\prime}\|

Parameters and notation

A common two sample statistic is mn/(m+n) times E; k-sample forms combine weighted pairwise energy distances.

Structure of the method

Compute within-group and between-group distance averages, combine them into energy distances, and aggregate pairwise group discrepancies for a multisample statistic. Under the exchangeable null, relabel observations while retaining the original group sizes. The statistic detects distributional differences rather than fitting a parametric density for each group.

Estimated and nuisance parameters

Empirical distance expectations and group sample sizes determine the statistic. There are no nuisance means or covariance matrices to estimate in the basic unstandardized Euclidean version; a separately fitted scaling or representation becomes part of the analysis pipeline.

Settings and design choices

Choose the distance, feature scaling, group weighting/multisample variant, permutation restrictions, replication count, and seed in advance. Original energy, DISCO-between, and DISCO-F options have different weights/statistics despite sharing distance ingredients.

Fitting and adaptation

No predictive-model training is required. Recompute group-dependent terms under each permitted relabeling. Label-blind pooled preprocessing can remain fixed when exchangeability permits; supervised feature selection must be trained independently or repeated within the permutation procedure. For repeated measures, the allowed exchangeable units must match the actual design.

Sensitivity and robustness

Unequal sample sizes, high-dimensional distance concentration, feature units, outliers, and finite distance moments influence power. Rejection can reflect means, spread, tails, or shape. Assess Monte Carlo resolution and report an effect summary alongside p-values; unrestricted label permutations are invalid when groups differ in dependence or sampling structure under the intended null.

How to use and calibrate

Use group label permutations respecting the design; reject for large distances.

Example application

Compare high-dimensional response distributions across groups.

Interpretation and pitfalls

Watch out

Feature scaling matters. Distributional differences may concern spread or shape, not only mean vectors.

What changed in edition 2

  • New sections: structure of the method, estimated and nuisance parameters, settings and design choices, fitting and adaptation, sensitivity and robustness.

Python and R

Energy distribution-equality test with independent samples concatenated in group order.

Python · invokes R

Not run — Executed end to end through Rscript · needs Python standard library + Rscript; R packages: energy

# Python launcher for the complete R implementation below.
# Requires Rscript on PATH and the listed R packages.
import shutil
import subprocess
rscript = shutil.which("Rscript")
if rscript is None:
    raise RuntimeError("Install R and make Rscript available on PATH.")
r_code = r"""
set.seed(2026)
X<-matrix(rnorm(120),ncol=3);Y<-matrix(rnorm(150,mean=.3),ncol=3)
print(energy::eqdist.etest(rbind(X,Y),sizes=c(nrow(X),nrow(Y)),R=999))
"""
# No shell interpolation. A failed R execution raises an error in Python.
result = subprocess.run([rscript, "--vanilla", "-"], input=r_code,
                        text=True, capture_output=True)
print(result.stdout)
if result.stderr:
    print(result.stderr)
result.check_returncode()
R

Validated — Executed successfully in the validation environment · needs energy

set.seed(2026)
X<-matrix(rnorm(120),ncol=3);Y<-matrix(rnorm(150,mean=.3),ncol=3)
print(energy::eqdist.etest(rbind(X,Y),sizes=c(nrow(X),nrow(Y)),R=999))
Output
	Multivariate 2-sample E-test of equal distributions

data:  sample sizes 40 50, replicates 999
E-statistic = 9.6419, p-value = 0.001

Sources

Statistics guide v4 (historical):
Python: Executed end to end through Rscript · R: Executed successfully in the validation environment
Reference's record:
Edition 2 review: Python: skip · R: not executed (Rscript unavailable); why not run: Python: Python-to-R bridge; Rscript is unavailable. R code was not executed. Python: Not run in the reference's review: Python-to-R bridge; Rscript is unavailable. R code was not executed. R: Reviewed but not run: R wasn't available to the reference's authors.

From the CodeSplash statistics guide (v4), entry 168, updated from the reference's edition 2 (reviewed 14 November 2026) as STAT168.