Skip to content

BCompare groups · equivalence.tost

Equivalence and minimal-effect tests (TOST)

Is an effect small enough to be practically equivalent to zero, or large enough to matter?

Two one-sided tests (Schuirmann 1987) against an equivalence margin: one sample against a reference value, paired measurements, or two independent groups (Welch by default). The t version takes raw or standardized bounds; the Wilcoxon version tests a location shift with ranks; the Brunner–Munzel version bounds the relative effect. Flip the hypothesis to a minimal-effect test to show an effect is big enough.

Verified in Python and R Python and R agree to 10 decimals Also called TOST, two one-sided tests, Schuirmann's test…

A real result

Example “Two sample d”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Equivalence test (TOST, two-sample)Recorded · Python and R agreeRecorded 2026-11-25 · 27 values compared
R

TOST: t(55.31) = 3.85, p < .001; t(55.31) = −0.02, p = .492

difference in means (OJ − VC)
3.700
p (TOST)
.492
90% CI
[0.4683, 6.932]
p (no difference)
.061

Plots

Estimate and 90% CI against the boundsHow large are several estimates, how precise, and which exclude the null?
View data
lenCI highEstimateCI low
3.7006.932OJ − VC0.4683

Assumptions

  • Normality — Shapiro–Wilk p < .05 in 1 of 2 sample(s); consider the Wilcoxon version.
  • Bounds set in advance — Bounds [-3.74, 3.74] (d = -0.5 to 0.5 × SD 7.48).

One-sided tests at the bounds

TestBoundtdfp
Lower (H0: effect ≤ lower bound)−3.7413.85255.309< .001
Upper (H0: effect ≥ upper bound)3.741−0.021255.309.492
No difference (two-sided)01.91555.309.061
  • Equivalence is concluded when both one-sided tests reject at α = 0.05, i.e. the 90% CI lies inside the bounds.
Python

TOST: t(55.31) = 3.85, p < .001; t(55.31) = −0.02, p = .492

difference in means (OJ − VC)
3.700
p (TOST)
.492
90% CI
[0.4683, 6.932]
p (no difference)
.061

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

Assumptions

  • Normality — Shapiro–Wilk p < .05 in 1 of 2 sample(s); consider the Wilcoxon version.
  • Bounds set in advance — Bounds [-3.74, 3.74] (d = -0.5 to 0.5 × SD 7.48).

One-sided tests at the bounds

TestBoundtdfp
Lower (H0: effect ≤ lower bound)−3.7413.85255.309< .001
Upper (H0: effect ≥ upper bound)3.741−0.021255.309.492
No difference (two-sided)01.91555.309.061
  • Equivalence is concluded when both one-sided tests reject at α = 0.05, i.e. the 90% CI lies inside the bounds.

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

  • Two sample dtoothgrowth · group: supp · outcome: len
  • Paired rawsleep_wide · outcome: drug1 · second: drug2
  • One samplemtcars · outcome: mpg
  • Student booleanmtcars · group: manual · outcome: qsec
  • Wilcoxon guidea_xy_long · group: sample · outcome: value
  • Wilcoxon paired exacta_depression · outcome: first · second: second
  • Wilcoxon one samplemtcars · outcome: mpg
  • Brunner munzeltoothgrowth · group: supp · outcome: len

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • One sample (continuous): one-sample t, Wilcoxon signed-rank · Statistics Guide · B — Compare groups
  • Two independent groups (continuous): Student / Welch t, Mann–Whitney U · Statistics Guide · B — Compare groups
  • Paired (continuous): paired t, Wilcoxon signed-rank · Statistics Guide · B — Compare groups
  • Statistic, p, effect size, CI, adjustment, context · Statistics Guide · Step 4 — Report and interpret

What you need

Outcome / first measurementnumeric · 1 column
The measurement (two-sample design) or the first measurement (paired design).
Groups (two-sample design)categorical / boolean · 0–1 column · 2–2 levels
Two groups to compare, in the two-sample design.
Second measurement (paired design)numeric · 0–1 column
Leave Groups and this empty to test one sample against the reference value.

Choices you make

hypothesis

Testdefault t

Which one-sided tests run at each bound.

  • t tests (means)(default) — Bounds on the mean or mean difference; Welch's version for two groups.
  • Wilcoxon (ranks) — Bounds on a location shift (Hodges–Lehmann); for skewed data or outliers. Raw-unit bounds.
  • Brunner–Munzel (relative effect) — Bounds on P(X > Y) + ½P(X = Y), e.g. 0.4 to 0.6; no shape assumption. Two groups only.
Hypothesisdefault equivalence

Equivalence shows the effect is inside the bounds; minimal effect shows it is beyond them.

  • Equivalence (effect inside the bounds)(default) — H0: the effect lies outside the bounds; rejecting shows it is negligible.
  • Minimal effect (effect beyond the bounds) — H0: the effect lies inside the bounds; rejecting shows it is big enough to matter.
Meaningful in which directiondefault both

Decide before seeing the data. One direction uses only that bound.

  • Either direction(default) — Below the lower bound or above the upper bound.
  • Above the upper bound — An increase larger than the upper bound.
  • Below the lower bound — A decrease larger than the lower bound.
Lower bounddefault -0.5

The smallest effect that matters on the low side (raw units for the Wilcoxon version).

Upper bounddefault 0.5

The smallest effect that matters on the high side.

Lower relative-effect bounddefault 0.4

P(X > Y) + ½P(X = Y) below this is a meaningful disadvantage for the first group.

Upper relative-effect bounddefault 0.6

P(X > Y) + ½P(X = Y) above this is a meaningful advantage for the first group.

Bounds aredefault d

Standardized bounds are multiplied by the SD (one sample), the SD of the differences (paired) or the average SD (two groups).

  • Raw units of the outcome — Sets the equivalence bounds in the outcome's own units; pick it when you know what size of difference matters.
  • Standardized (Cohen's d)(default) — Sets the bounds in SD units (Cohen's d); pick it when the outcome's units have no agreed meaning.
Reference value (one sample)default 0

In the one-sample design, the reference value the mean is compared with.

Significance level αdefault 0.05

The interval shown is the (1 − 2α) interval, e.g. 90% for α = .05.

assumptions

Welch's version (unequal variances)default on

Use Welch's version, which doesn't assume equal variances (recommended).

options

Rank-test p-valuesdefault auto

As R's wilcox.test: exact for fewer than 50 values without ties (or zeros).

  • Exact when possible(default) — Exact null distribution for small samples without ties; otherwise the normal approximation.
  • Exact (no ties) — Exact null distribution; falls back to the normal approximation when there are ties.
  • Normal approximation — With tie correction; the guide's example uses this.
Continuity correctiondefault on

Half-unit correction on the normal approximation (R's default).

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.

  • Normality / shape

    t version: Shapiro–Wilk of the sample, the differences or the groups. Rank versions: the shape the test assumes.

  • Bounds set in advance

    The bounds (the smallest effect size of interest) must be justified before seeing the data.

What it reports

  • Tests: Equivalence (TOST)
estimate
How much the outcome changes for a one-unit change in a predictor, holding the others fixed.
se
The typical size of the error in an estimate, the standard deviation of its sampling distribution.
df
How much independent information is left to estimate variability after fitting the model.
t_lower
A range of effect values compatible with your data at the chosen confidence level.
p_lower
A range of effect values compatible with your data at the chosen confidence level.
t_upper
A range of effect values compatible with your data at the chosen confidence level.
p_upper
A range of effect values compatible with your data at the chosen confidence level.
p
How surprising your data would be if the null hypothesis were true, as a probability.
ci_low
A range of effect values compatible with your data at the chosen confidence level.
ci_high
A range of effect values compatible with your data at the chosen confidence level.
low_raw
Tests whether an effect is small enough to ignore, by rejecting effects beyond ± the SESOI.
high_raw
Tests whether an effect is small enough to ignore, by rejecting effects beyond ± the SESOI.
equivalent
Tests whether an effect is small enough to ignore, by rejecting effects beyond ± the SESOI.
decision
Tests whether an effect is small enough to ignore, by rejecting effects beyond ± the SESOI.
t_nhst
A single number that summarizes how far your data are from what H₀ predicts.
p_nhst
How surprising your data would be if the null hypothesis were true, as a probability.
sd_used
The typical distance of values from their mean, in the data's own units.
design
The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
n
How many independent units the analysis used; it sets precision and power.
test
The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
hypothesis
What the test set out to show: equivalence (the effect lies inside the bounds) or minimal_effect (it lies beyond them).
estimand
The exact quantity an analysis targets, such as a difference in means or a ratio of medians.
stat_lower
A range of effect values compatible with your data at the chosen confidence level.
stat_upper
A range of effect values compatible with your data at the chosen confidence level.
stat_nhst
A single number that summarizes how far your data are from what H₀ predicts.
exact
True when the Wilcoxon tests used the exact null distribution, false for the normal approximation. Empty for other tests.
missing_share
Values that were not recorded; how they went missing decides which fixes are safe.

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.

Python

The exact script CodeSplash ran for example “Two sample d” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Equivalence and minimal-effect tests (TOST)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method equivalence.tost 1.1.1 · spec 16bace8c3b91ebbd
# Dataset: toothgrowth (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 equivalence

# %% Data
df = pd.read_parquet("tests/parity/fixtures/toothgrowth.parquet", columns=["len", "supp"])
n_input = len(df)
df["supp"] = pd.Categorical(df["supp"], categories=["OJ", "VC"])  # stored level order
df = df.dropna(subset=["len", "supp"])  # listwise deletion over the analysis columns
df["supp"] = df["supp"].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, ["len", "supp"])  # infinite values stop the run (registry/errors.yaml)

# %% Estimate
y = "len"
alpha = 0.05
test = "t"  # t | wilcoxon | brunner_munzel
hypothesis = "equivalence"  # equivalence (TOST) | minimal_effect
direction = "both"  # minimal effect: both | above | below
low, high = -0.5, 0.5
bound_type = "d" if test == "t" else "raw"  # standardized bounds are for the t version only
mu = 0.0
g = "supp"
levels = [str(x) for x in df[g].cat.categories]
if len(levels) != 2:
    cs.cs_error("CS_E_GROUP_COUNT", column=g, expected=2, k=len(levels))
x1 = df.loc[df[g] == df[g].cat.categories[0], y].to_numpy(dtype=float)
x2 = df.loc[df[g] == df[g].cat.categories[1], y].to_numpy(dtype=float)
n1, n2 = len(x1), len(x2)
if test != "wilcoxon":  # the t and Brunner–Munzel versions estimate a variance in each group
    for lvl, n_g in zip(levels, (n1, n2)):
        if n_g < 2:
            cs.cs_error("CS_E_SMALL_GROUP", min=2, group=f"{g} = {lvl}", n=n_g)
    if len(np.unique(df[y].to_numpy(dtype=float))) < 2:  # no variation: the standard error is 0
        cs.cs_error("CS_E_CONSTANT", column=y)
v1, v2 = x1.var(ddof=1), x2.var(ddof=1)
design, n = "two-sample", n1 + n2
estimate = x1.mean() - x2.mean()
if True:  # Welch: no equal-variance assumption
    se = np.sqrt(v1 / n1 + v2 / n2)
    dof = (v1 / n1 + v2 / n2) ** 2 / ((v1 / n1) ** 2 / (n1 - 1) + (v2 / n2) ** 2 / (n2 - 1))
    sd_used = np.sqrt((v1 + v2) / 2)  # average SD scales standardized bounds
else:
    sp2 = ((n1 - 1) * v1 + (n2 - 1) * v2) / (n1 + n2 - 2)
    se, dof, sd_used = np.sqrt(sp2 * (1 / n1 + 1 / n2)), n1 + n2 - 2, np.sqrt(sp2)
samples, rank_x, rank_y = [x1, x2], x1, x2
what = f"{levels[0]} − {levels[1]}"
estimand = {"t": "difference in means", "wilcoxon": "Hodges–Lehmann shift", "brunner_munzel": "relative effect P(X > Y) + ½P(X = Y)"}[test]
if test == "brunner_munzel":
    low_raw, high_raw = 0.4, 0.6
    if not 0 <= low_raw < high_raw <= 1:
        raise ValueError("Relative-effect bounds must satisfy 0 ≤ lower < upper ≤ 1 (e.g. 0.4 and 0.6)")
else:
    if low >= high:
        raise ValueError("The lower bound must be below the upper bound")
    low_raw, high_raw = (low * sd_used, high * sd_used) if bound_type == "d" else (low, high)

# %% Test
stat_lower = stat_upper = stat_nhst = exact = None
t_lower = t_upper = t_nhst = None
if test == "t":
    r = equivalence.bounds_t(estimate, se, dof, low_raw, high_raw, alpha, hypothesis, direction)  # one-sided t tests at each bound
    t_lower, t_upper = r["t_lower"], r["t_upper"]
    t_nhst = estimate / se
    p_nhst = float(2 * stats.t.sf(abs(t_nhst), dof))
elif test == "wilcoxon":
    r = equivalence.rank_tost(rank_x, rank_y, low_raw, high_raw, alpha, mu, "auto", True,
                              hypothesis, direction)  # one-sided rank tests at each bound (R wilcox.test)
    estimate, se, dof, sd_used = r["estimate"], None, None, None
    stat_lower, stat_upper, stat_nhst, exact = r["stat_lower"], r["stat_upper"], r["stat_nhst"], r["exact"]
    p_nhst = r["p_nhst"]
else:
    r = equivalence.bm_tost(x1, x2, low_raw, high_raw, alpha, hypothesis, direction)  # Brunner–Munzel at each bound
    estimate, se, dof, sd_used = r["estimate"], r["se"], r["df"], None
    t_lower, t_upper, t_nhst, p_nhst = r["t_lower"], r["t_upper"], r["stat_nhst"], r["p_nhst"]
decision = r["decision"]
name = "TOST" if hypothesis == "equivalence" else "minimal-effect test"
version = {"t": "", "wilcoxon": "Wilcoxon ", "brunner_munzel": "Brunner–Munzel "}[test]

# %% Assumptions
assumptions = []
if test == "t":
    sw = [stats.shapiro(s).pvalue for s in samples if 3 <= len(s) <= 5000]
    bad = [p for p in sw if p < 0.05]
    assumptions.append({"key": "normality", "label": "Normality", "status": ("warn" if n < 30 else "info") if bad else ("pass" if sw else "info"),
                        "detail": (f"Shapiro–Wilk p < .05 in {len(bad)} of {len(sw)} sample(s); consider the Wilcoxon version." if bad else "Shapiro–Wilk p ≥ .05.")
                        if sw else "Too few values for Shapiro–Wilk."})
elif test == "wilcoxon":
    assumptions.append({"key": "normality", "label": "Shape", "status": "info",
                        "detail": "Rank-based: the groups share a shape (a pure shift)." if design == "two-sample"
                        else "Rank-based: the differences are symmetric about their center."})
else:
    assumptions.append({"key": "normality", "label": "Shape", "status": "info",
                        "detail": "No distributional assumption: the bounds apply to the relative effect P(X > Y) + ½P(X = Y)."})
assumptions.append({"key": "bounds", "label": "Bounds set in advance", "status": "info",
                    "detail": f"Bounds [{low_raw:.3g}, {high_raw:.3g}]" + (f" (d = {low:g} to {high:g} × SD {sd_used:.3g})." if bound_type == "d" else ".")})

# %% Result
level = 1 - 2 * alpha
values = {"estimate": float(estimate), "se": None if se is None else float(se), "df": None if dof is None else float(dof),
          "t_lower": t_lower, "p_lower": r["p_lower"], "t_upper": t_upper, "p_upper": r["p_upper"], "p": r["p"],
          "ci_low": r["ci_low"], "ci_high": r["ci_high"], "low_raw": float(low_raw), "high_raw": float(high_raw),
          "equivalent": decision == "equivalent", "decision": decision, "t_nhst": None if t_nhst is None else float(t_nhst), "p_nhst": float(p_nhst),
          "sd_used": None if sd_used is None else float(sd_used), "design": design, "n": n, "test": test, "hypothesis": hypothesis,
          "estimand": estimand, "stat_lower": stat_lower, "stat_upper": stat_upper, "stat_nhst": stat_nhst, "exact": exact}
values["missing_share"] = n_dropped / n_input if n_input else 0.0  # consult-a-statistician input
stat_label = "W" if test == "wilcoxon" else "t"
if hypothesis == "equivalence":
    labels = ("Lower (H0: effect ≤ lower bound)", "Upper (H0: effect ≥ upper bound)")
else:
    labels = ("Below (H1: effect < lower bound)", "Above (H1: effect > upper bound)")
rows = [{"test": labels[0], "bound": float(low_raw), "statistic": stat_lower if test == "wilcoxon" else t_lower, "df": values["df"], "p": r["p_lower"]},
        {"test": labels[1], "bound": float(high_raw), "statistic": stat_upper if test == "wilcoxon" else t_upper, "df": values["df"], "p": r["p_upper"]},
        {"test": "No difference (two-sided)" if test != "brunner_munzel" else "Relative effect 0.5 (two-sided)",
         "bound": 0.5 if test == "brunner_munzel" else 0.0, "statistic": stat_nhst if test == "wilcoxon" else values["t_nhst"], "df": values["df"], "p": float(p_nhst)}]
if hypothesis == "equivalence":
    note = f"Equivalence is concluded when both one-sided tests reject at α = {alpha:g}, i.e. the {level:.0%} CI lies inside the bounds."
else:
    side = {"both": "either", "above": "the upper", "below": "the lower"}[direction]
    note = f"A meaningful effect is concluded when {side} outward one-sided test rejects at α = {alpha:g} (the effect lies beyond the bound)."
if test == "wilcoxon":
    note += f" Rank tests use the {'exact' if exact else 'normal-approximation'} null distribution (as R's wilcox.test); the interval is the order-statistic interval for the {estimand}."
verdict = {"equivalent": "equivalent", "not shown equivalent": "equivalence not shown", "meaningful effect": "a meaningful effect",
           "not shown meaningful": "a meaningful effect not shown"}[decision]
cs.publish({
    "method": "equivalence.tost",
    "methodVersion": "1.1.1",
    "title": f"{version}Equivalence test (TOST, {design})" if hypothesis == "equivalence" else f"{version}Minimal-effect test ({design})",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": f"{what}: {estimand} = {estimate:.3f}, {level:.0%} CI [{r['ci_low']:.3f}, {r['ci_high']:.3f}]; bounds [{low_raw:.3f}, {high_raw:.3f}]; "
               f"{verdict} ({version}{name} {cs.fmt_p(r['p'])}).",
    "apa": (f"{version}{name}: W = {cs.fmt_num(stat_lower)}, {cs.fmt_p(r['p_lower'])}; W = {cs.fmt_num(stat_upper)}, {cs.fmt_p(r['p_upper'])}"
            if test == "wilcoxon" else
            f"{version}{name}: t({cs.fmt_num(dof)}) = {cs.fmt_num(t_lower)}, {cs.fmt_p(r['p_lower'])}; t({cs.fmt_num(dof)}) = {cs.fmt_num(t_upper)}, {cs.fmt_p(r['p_upper'])}"),
    "statistics": [{"key": "estimate", "label": f"{estimand} ({what})", "value": float(estimate)},
                   {"key": "p", "label": f"p ({name})", "value": r["p"], "format": "p"},
                   {"key": "ci", "label": f"{level:.0%} CI", "value": [r["ci_low"], r["ci_high"]]},
                   {"key": "p_nhst", "label": "p (no difference)", "value": float(p_nhst), "format": "p"}],
    "tables": [{"key": "tost", "title": "One-sided tests at the bounds", "columns": [
        {"key": "test", "label": "Test", "type": "string"}, {"key": "bound", "label": "Bound", "type": "number"},
        {"key": "statistic", "label": stat_label, "type": "number"}, {"key": "df", "label": "df", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
        "rows": rows}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [note],
    "values": values,
    "charts": [cs.chart("equivalence", "forest", f"Estimate and {level:.0%} CI against the bounds", {
        "label": cs.col("Estimate", [what], "categorical"), "estimate": cs.col(y, [float(estimate)], "numeric"),
        "low": cs.col("CI low", [r["ci_low"]], "numeric"), "high": cs.col("CI high", [r["ci_high"]], "numeric")},
        controls={"reference": 0.5 if test == "brunner_munzel" else 0, "bandLow": float(low_raw), "bandHigh": float(high_raw)})],
})
R

The exact script CodeSplash ran for example “Two sample d” · R version 4.5.1 (2025-06-13)

# Equivalence and minimal-effect tests (TOST)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method equivalence.tost 1.1.1 · spec 16bace8c3b91ebbd
# Dataset: toothgrowth (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/toothgrowth.parquet", col_select = c("len", "supp")))
n_input <- nrow(df)
df[["supp"]] <- factor(df[["supp"]], levels = c("OJ", "VC"))  # stored level order
df <- df[stats::complete.cases(df[c("len", "supp")]), , 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("len", "supp"))  # infinite values stop the run (registry/errors.yaml)

# %% Estimate
y <- "len"
alpha <- 0.05
test <- "t"  # t | wilcoxon | brunner_munzel
hypothesis <- "equivalence"  # equivalence (TOST) | minimal_effect
direction <- "both"  # minimal effect: both | above | below
low <- -0.5
high <- 0.5
bound_type <- if (test == "t") "d" else "raw"  # standardized bounds are for the t version only
mu <- 0
g <- "supp"
levels_g <- levels(df[[g]])
if (length(levels_g) != 2) cs_error("CS_E_GROUP_COUNT", column = g, expected = 2, k = length(levels_g))
x1 <- df[[y]][df[[g]] == levels_g[1]]
x2 <- df[[y]][df[[g]] == levels_g[2]]
n1 <- length(x1)
n2 <- length(x2)
if (test != "wilcoxon") {  # the t and Brunner-Munzel versions estimate a variance in each group
  for (i in 1:2) {
    if (c(n1, n2)[i] < 2) cs_error("CS_E_SMALL_GROUP", min = 2, group = paste0(g, " = ", levels_g[i]), n = c(n1, n2)[i])
  }
  if (length(unique(df[[y]])) < 2) cs_error("CS_E_CONSTANT", column = y)  # no variation: the standard error is 0
}
v1 <- var(x1)
v2 <- var(x2)
design <- "two-sample"
n <- n1 + n2
estimate <- mean(x1) - mean(x2)
if (TRUE) {  # Welch: no equal-variance assumption
  se <- sqrt(v1 / n1 + v2 / n2)
  dof <- (v1 / n1 + v2 / n2)^2 / ((v1 / n1)^2 / (n1 - 1) + (v2 / n2)^2 / (n2 - 1))
  sd_used <- sqrt((v1 + v2) / 2)  # average SD scales standardized bounds
} else {
  sp2 <- ((n1 - 1) * v1 + (n2 - 1) * v2) / (n1 + n2 - 2)
  se <- sqrt(sp2 * (1 / n1 + 1 / n2))
  dof <- n1 + n2 - 2
  sd_used <- sqrt(sp2)
}
samples <- list(x1, x2)
rank_x <- x1
rank_y <- x2
what <- sprintf("%s − %s", levels_g[1], levels_g[2])
estimand <- c(t = "difference in means", wilcoxon = "Hodges–Lehmann shift", brunner_munzel = "relative effect P(X > Y) + ½P(X = Y)")[[test]]
if (test == "brunner_munzel") {
  low_raw <- 0.4
  high_raw <- 0.6
  if (!(0 <= low_raw && low_raw < high_raw && high_raw <= 1)) stop("Relative-effect bounds must satisfy 0 ≤ lower < upper ≤ 1 (e.g. 0.4 and 0.6)")
} else {
  if (low >= high) stop("The lower bound must be below the upper bound")
  bounds <- if (bound_type == "d") c(low, high) * sd_used else c(low, high)
  low_raw <- bounds[1]
  high_raw <- bounds[2]
}

# %% Test
stat_lower <- NULL
stat_upper <- NULL
stat_nhst <- NULL
exact <- NULL
t_lower <- NULL
t_upper <- NULL
t_nhst <- NULL
if (test == "t") {
  r <- cs_bounds_t(estimate, se, dof, low_raw, high_raw, alpha, hypothesis, direction)  # one-sided t tests at each bound
  t_lower <- r$t_lower
  t_upper <- r$t_upper
  t_nhst <- estimate / se
  p_nhst <- 2 * pt(abs(t_nhst), dof, lower.tail = FALSE)
} else if (test == "wilcoxon") {
  r <- cs_rank_tost(rank_x, rank_y, low_raw, high_raw, alpha, mu, "auto", TRUE,
                    hypothesis, direction)  # one-sided rank tests at each bound (wilcox.test)
  estimate <- r$estimate
  se <- NULL
  dof <- NULL
  sd_used <- NULL
  stat_lower <- r$stat_lower
  stat_upper <- r$stat_upper
  stat_nhst <- r$stat_nhst
  exact <- r$exact
  p_nhst <- r$p_nhst
} else {
  r <- cs_bm_tost(x1, x2, low_raw, high_raw, alpha, hypothesis, direction)  # Brunner-Munzel at each bound
  estimate <- r$estimate
  se <- r$se
  dof <- r$df
  sd_used <- NULL
  t_lower <- r$t_lower
  t_upper <- r$t_upper
  t_nhst <- r$stat_nhst
  p_nhst <- r$p_nhst
}
decision <- r$decision
name <- if (hypothesis == "equivalence") "TOST" else "minimal-effect test"
version <- c(t = "", wilcoxon = "Wilcoxon ", brunner_munzel = "Brunner–Munzel ")[[test]]

# %% Assumptions
assumptions <- list()
if (test == "t") {
  sw <- unlist(lapply(samples, function(s) if (length(s) >= 3 && length(s) <= 5000) shapiro.test(s)$p.value else NULL))
  bad <- sw[sw < 0.05]
  assumptions[[1]] <- list(key = "normality", label = "Normality",
                           status = if (length(bad)) (if (n < 30) "warn" else "info") else if (length(sw)) "pass" else "info",
                           detail = if (length(sw)) (if (length(bad)) sprintf("Shapiro–Wilk p < .05 in %d of %d sample(s); consider the Wilcoxon version.", length(bad), length(sw)) else "Shapiro–Wilk p ≥ .05.")
                                    else "Too few values for Shapiro–Wilk.")
} else if (test == "wilcoxon") {
  assumptions[[1]] <- list(key = "normality", label = "Shape", status = "info",
                           detail = if (design == "two-sample") "Rank-based: the groups share a shape (a pure shift)." else "Rank-based: the differences are symmetric about their center.")
} else {
  assumptions[[1]] <- list(key = "normality", label = "Shape", status = "info",
                           detail = "No distributional assumption: the bounds apply to the relative effect P(X > Y) + ½P(X = Y).")
}
assumptions[[2]] <- list(key = "bounds", label = "Bounds set in advance", status = "info",
                         detail = paste0(sprintf("Bounds [%s, %s]", format(signif(low_raw, 3)), format(signif(high_raw, 3))),
                                         if (bound_type == "d") sprintf(" (d = %s to %s × SD %s).", format(low), format(high), format(signif(sd_used, 3))) else "."))

# %% Result
level <- 1 - 2 * alpha
values <- list(estimate = estimate, se = se, df = dof, t_lower = t_lower, p_lower = r$p_lower, t_upper = t_upper, p_upper = r$p_upper,
               p = r$p, ci_low = r$ci_low, ci_high = r$ci_high, low_raw = low_raw, high_raw = high_raw,
               equivalent = decision == "equivalent", decision = decision, t_nhst = t_nhst, p_nhst = p_nhst, sd_used = sd_used,
               design = design, n = n, test = test, hypothesis = hypothesis, estimand = estimand,
               stat_lower = stat_lower, stat_upper = stat_upper, stat_nhst = stat_nhst, exact = exact)
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0  # consult-a-statistician input
pct <- sprintf("%.0f%%", level * 100)
stat_label <- if (test == "wilcoxon") "W" else "t"
labels <- if (hypothesis == "equivalence") c("Lower (H0: effect ≤ lower bound)", "Upper (H0: effect ≥ upper bound)") else
  c("Below (H1: effect < lower bound)", "Above (H1: effect > upper bound)")
na_null <- function(v) if (is.null(v)) NA else v
rows <- list(
  list(test = labels[1], bound = low_raw, statistic = na_null(if (test == "wilcoxon") stat_lower else t_lower), df = na_null(dof), p = r$p_lower),
  list(test = labels[2], bound = high_raw, statistic = na_null(if (test == "wilcoxon") stat_upper else t_upper), df = na_null(dof), p = r$p_upper),
  list(test = if (test != "brunner_munzel") "No difference (two-sided)" else "Relative effect 0.5 (two-sided)",
       bound = if (test == "brunner_munzel") 0.5 else 0, statistic = na_null(if (test == "wilcoxon") stat_nhst else t_nhst), df = na_null(dof), p = p_nhst)
)
note <- if (hypothesis == "equivalence") {
  sprintf("Equivalence is concluded when both one-sided tests reject at α = %s, i.e. the %s CI lies inside the bounds.", format(alpha), pct)
} else {
  side <- c(both = "either", above = "the upper", below = "the lower")[[direction]]
  sprintf("A meaningful effect is concluded when %s outward one-sided test rejects at α = %s (the effect lies beyond the bound).", side, format(alpha))
}
if (test == "wilcoxon") {
  note <- paste0(note, sprintf(" Rank tests use the %s null distribution (as R's wilcox.test); the interval is the order-statistic interval for the %s.",
                               if (exact) "exact" else "normal-approximation", estimand))
}
verdict <- c(equivalent = "equivalent", `not shown equivalent` = "equivalence not shown", `meaningful effect` = "a meaningful effect",
             `not shown meaningful` = "a meaningful effect not shown")[[decision]]
cs_publish(list(
  method = "equivalence.tost",
  methodVersion = "1.1.1",
  title = if (hypothesis == "equivalence") sprintf("%sEquivalence test (TOST, %s)", version, design) else sprintf("%sMinimal-effect test (%s)", version, design),
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = sprintf("%s: %s = %.3f, %s CI [%.3f, %.3f]; bounds [%.3f, %.3f]; %s (%s%s %s).", what, estimand, estimate, pct, r$ci_low, r$ci_high,
                    low_raw, high_raw, verdict, version, name, cs_fmt_p(r$p)),
  apa = if (test == "wilcoxon") sprintf("%s%s: W = %s, %s; W = %s, %s", version, name, cs_fmt_num(stat_lower), cs_fmt_p(r$p_lower),
                                        cs_fmt_num(stat_upper), cs_fmt_p(r$p_upper))
        else sprintf("%s%s: t(%s) = %s, %s; t(%s) = %s, %s", version, name, cs_fmt_num(dof), cs_fmt_num(t_lower), cs_fmt_p(r$p_lower),
                     cs_fmt_num(dof), cs_fmt_num(t_upper), cs_fmt_p(r$p_upper)),
  statistics = list(list(key = "estimate", label = sprintf("%s (%s)", estimand, what), value = estimate),
                    list(key = "p", label = sprintf("p (%s)", name), value = r$p, format = "p"),
                    list(key = "ci", label = paste(pct, "CI"), value = c(r$ci_low, r$ci_high)),
                    list(key = "p_nhst", label = "p (no difference)", value = p_nhst, format = "p")),
  tables = list(list(key = "tost", title = "One-sided tests at the bounds",
                     columns = list(list(key = "test", label = "Test", type = "string"), list(key = "bound", label = "Bound", type = "number"),
                                    list(key = "statistic", label = stat_label, type = "number"), list(key = "df", label = "df", type = "number"),
                                    list(key = "p", label = "p", type = "pvalue")),
                     rows = rows)),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(note),
  values = values,
  charts = list(cs_chart("equivalence", "forest", sprintf("Estimate and %s CI against the bounds", pct), list(
    label = cs_col("Estimate", what, "categorical"), estimate = cs_col(y, estimate, "numeric"),
    low = cs_col("CI low", r$ci_low, "numeric"), high = cs_col("CI high", r$ci_high, "numeric")),
    controls = list(reference = if (test == "brunner_munzel") 0.5 else 0, bandLow = low_raw, bandHigh = high_raw)))
))

Sources

  • Schuirmann, D. J. (1987). A comparison of the two one-sided tests procedure and the power approach for assessing the equivalence of average bioavailability. Journal of Pharmacokinetics and Biopharmaceutics, 15, 657–680.
  • Lakens, D. (2017). Equivalence tests: A practical primer for t tests, correlations, and meta-analyses. Social Psychological and Personality Science, 8, 355–362.
  • Lakens, D., Scheel, A. M., & Isager, P. M. (2018). Equivalence testing for psychological research: A tutorial. Advances in Methods and Practices in Psychological Science, 1, 259–269.
  • Wellek, S. (2010). Testing statistical hypotheses of equivalence and noninferiority (2nd ed.). Chapman & Hall/CRC.
  • Brunner, E., & Munzel, U. (2000). The nonparametric Behrens–Fisher problem: Asymptotic theory and a small-sample approximation. Biometrical Journal, 42, 17–25.
  • Hollander, M., Wolfe, D. A., & Chicken, E. (2014). Nonparametric statistical methods (3rd ed.). Wiley.

From the CodeSplash method registry · equivalence.tost v1.1.1.