Skip to content

BCompare groups · robust.yuen

Yuen's trimmed-means t-test (independent or paired)

Do two groups (or two paired measurements) differ in their trimmed means?

Compares 20% trimmed means, which resist outliers and heavy tails: Yuen's test with Welch-type degrees of freedom for two independent groups (bind Groups) or the paired version for two measurements on the same rows (bind Second measurement). Reports the AKP robust effect size for independent groups.

Verified in Python and R Python and R agree to 10 decimals Also called Yuen's test, Yuen–Welch test, trimmed means t test…

A real result

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

Yuen's trimmed-means t-testRecorded · Python and R agreeRecorded 2026-11-25 · 17 values compared
R

t(33.49) = 2.29, p = .029

t
2.287
df
33.491
p
.029
Trimmed-mean difference (OJ − VC)
5.122
95% CI
[0.5687, 9.676]

Effect size

  • AKP robust d 0.6393

Plots

Trimmed-mean difference (95% CI)How large are several estimates, how precise, and which exclude the null?
View data
Difference in lenCI highEstimateCI low
5.1229.676OJ − VC0.5687

Assumptions

  • Design — Two independent groups (Yuen's test).
  • Enough values after trimming — 18 and 18 values remain after trimming 6 and 6 from each tail.

Descriptives (20% trimming)

SamplenTrimmed meanMeanMedianWinsorized SD
OJ3021.70620.66322.7004.816
VC3016.58316.96316.5005.451
  • Difference = OJ − VC; 20% trimmed from each tail; alternative: two-sided.
Python

t(33.49) = 2.29, p = .029

t
2.287
df
33.491
p
.029
Trimmed-mean difference (OJ − VC)
5.122
95% CI
[0.5687, 9.676]

Effect size

  • AKP robust d 0.6393

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

Assumptions

  • Design — Two independent groups (Yuen's test).
  • Enough values after trimming — 18 and 18 values remain after trimming 6 and 6 from each tail.

Descriptives (20% trimming)

SamplenTrimmed meanMeanMedianWinsorized SD
OJ3021.70620.66322.7004.816
VC3016.58316.96316.5005.451
  • Difference = OJ − VC; 20% trimmed from each tail; alternative: two-sided.

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

  • Independenttoothgrowth · group: supp · outcome: len
  • Paired sleepsleep_wide · outcome: drug1 · second: drug2
  • Boolean group lessmtcars · group: manual · outcome: mpg
  • Paired missingairquality · outcome: Ozone · second: Temp
  • Lens equivalencea_xy_long · group: sample · outcome: value
  • Lens noninferiority pairedsleep_wide · outcome: drug2 · second: drug1
  • Degenerate constanttoothgrowth · group: supp · outcome: len
  • Degenerate single leveltoothgrowth · group: supp · outcome: len

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • 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
  • Robust, permutation and exact methods · Statistics Guide · Step 3 — If assumptions are violated
  • Non-parametric alternatives · Statistics Guide · Additional considerations

What you need

Outcome / first measurementnumeric · 1 column
The measurement (two groups) or the first measurement (paired).
Groups (independent design)categorical / boolean · 0–1 column · 2–2 levels
Two independent groups. Leave empty and bind a second measurement for the paired test.
Second measurement (paired design)numeric · 0–1 column
Measured on the same rows; the difference is first − second.

Choices you make

hypothesis

Alternative hypothesisdefault two-sided

Which direction counts as evidence. Keep two-sided unless you fixed the direction before seeing the data.

  • Trimmed means differ (≠)(default) — Tests for a difference in trimmed means in either direction; keep it unless you fixed a direction before seeing the data.
  • First higher (>) — Tests only for the first trimmed mean being higher; pick it only if you fixed this direction before seeing the data.
  • First lower (<) — Tests only for the first trimmed mean being lower; pick it only if you fixed this direction before seeing the data.
Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.

Lensdefault none

Also test against bounds you set before seeing the data: equivalence, a minimal effect or non-inferiority.

  • Off(default) — Test for a difference only.
  • Equivalence (TOST) — Show the effect lies inside your bounds (two one-sided tests).
  • Minimal effect — Show the effect lies outside your bounds, i.e. is big enough to matter.
  • Non-inferiority — Show the effect is not worse than the lower bound.
Lower bound (raw units)default —

The smallest effect that matters on the low side (for non-inferiority: the margin, as a negative number).

Upper bound (raw units)default —

The smallest effect that matters on the high side.

options

Trimming proportion (each tail)default 0.2

0.2 (20%) is the usual choice; 0 gives Welch's / the paired t-test.

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.

  • Design

    Exactly one of Groups or Second measurement must be bound.

  • Enough values after trimming

    Each group needs at least two values left after trimming.

What it reports

  • Tests: Difference in trimmed means
t
An estimate divided by its standard error, compared with a t distribution.
df
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.
diff
The mean after dropping a fixed share of the smallest and largest values (often 20% each side).
se
The typical size of the error in an estimate, the standard deviation of its sampling distribution.
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.
tm_1
The mean after dropping a fixed share of the smallest and largest values (often 20% each side).
tm_2
The mean after dropping a fixed share of the smallest and largest values (often 20% each side).
n_1
How many independent units the analysis used; it sets precision and power.
n_2
How many independent units the analysis used; it sets precision and power.
trim
The mean after dropping a fixed share of the smallest and largest values (often 20% each side).
akp
A robust Cohen's d built from trimmed means and winsorized variances, rescaled to match d under normality.
design
The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
label_1
The first sample: a group level (independent design) or the first column (paired). The difference is this minus the second.
label_2
The second sample: a group level (independent design) or the second column (paired). It is subtracted from the first.
missing_share
Values that were not recorded; how they went missing decides which fixes are safe.

Per group, level or term: lens_p (when a lens is on), lens_ci_low (when a lens is on), lens_ci_high (when a lens is on), lens_verdict (when a lens is on)

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.

Default traps between the two languages

  • Twin implementation of WRS2 yuen/yuend (codesplash.stats.robust ↔ cs_yuen/cs_yuend); the independent test equals scipy ttest_ind(trim=, equal_var=False).
Python

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

# Yuen's trimmed-means t-test (independent or paired)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method robust.yuen 1.1.1 · spec b068cc1a7845e371
# 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

import codesplash as cs
from codesplash.stats import means as csm
from codesplash.stats import robust

# %% 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)

# %% Two samples (independent groups or paired measurements, from the bound roles)
y = "len"
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)
design, label_1, label_2 = "independent", levels[0], levels[1]

# %% Test
trim = 0.2
conf = 0.95
alternative = "two-sided"
n1, n2 = len(x1), len(x2)
g1, g2 = int(np.floor(trim * n1)), int(np.floor(trim * n2))
for lab, n_s in ((label_1, n1), (label_2, n2)):
    if n_s < 2:
        cs.cs_error("CS_E_SMALL_GROUP", min=2, group=f"{g} = {lab}" if design == "independent" else lab, n=n_s)
if n1 - 2 * g1 < 2 or n2 - 2 * g2 < 2:
    cs.cs_error("CS_E_UNDEFINED", what="Yuen's test", reason="each sample needs at least two values left after trimming")
if design == "independent":
    if len(np.unique(np.concatenate([x1, x2]))) < 2:  # no variation: the standard error is 0
        cs.cs_error("CS_E_CONSTANT", column=y)
    if np.ptp(robust.winsorize(x1, trim)) == 0 and np.ptp(robust.winsorize(x2, trim)) == 0:
        cs.cs_error("CS_E_UNDEFINED", what="Yuen's test", reason="neither group has any spread left after Winsorizing")
elif np.all(x1 == x2):
    cs.cs_error("CS_E_ALL_ZERO_DIFFERENCES")
if design == "independent":
    r = robust.yuen(x1, x2, trim, conf, alternative)  # WRS2::yuen (= scipy ttest_ind(trim=, equal_var=False))
    akp = r["akp"]
else:
    r = robust.yuend(x1, x2, trim, conf, alternative)  # WRS2::yuend
    akp = None

# Lens (equivalence / minimal effect / non-inferiority) on the trimmed-mean difference, at α = 1 − confidence.
lens_kind = "none"
lens = None
if lens_kind != "none":
    lens = csm.lens(lens_kind, r["diff"], r["se"], r["df"], None, None, 1 - conf)

# %% Assumptions
assumptions = [
    {"key": "design", "label": "Design", "status": "info",
     "detail": "Two independent groups (Yuen's test)." if design == "independent" else "Paired measurements on the same rows (Yuen's paired test)."},
    {"key": "sample_size", "label": "Enough values after trimming", "status": "warn" if min(n1 - 2 * g1, n2 - 2 * g2) < 5 else "pass",
     "detail": f"{n1 - 2 * g1} and {n2 - 2 * g2} values remain after trimming {g1} and {g2} from each tail."},
]

# %% Result
values = {"t": r["t"], "df": r["df"], "p": r["p"], "diff": r["diff"], "se": r["se"], "ci_low": r["ci_low"], "ci_high": r["ci_high"],
          "tm_1": r["tm_1"], "tm_2": r["tm_2"], "n_1": n1, "n_2": n2, "trim": trim, "akp": akp, "design": design,
          "label_1": label_1, "label_2": label_2, **(lens or {})}
effects = [{"key": "akp", "label": "AKP robust d", "value": akp, "method": "0.642 × Δ_t / pooled winsorized SD (Algina et al. 2005)"}] if akp is not None else []
descr = [{"sample": lab, "n": len(x), "trimmed_mean": robust.trim_mean(x, trim), "mean": float(np.mean(x)), "median": float(np.median(x)),
          "win_sd": float(np.std(robust.winsorize(x, trim), ddof=1))} for lab, x in ((label_1, x1), (label_2, x2))]
values["missing_share"] = n_dropped / n_input if n_input else 0.0  # consult-a-statistician input
cs.publish({
    "method": "robust.yuen",
    "methodVersion": "1.1.1",
    "title": "Yuen's trimmed-means t-test" + (" (paired)" if design == "paired" else ""),
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n1 + (n2 if design == "independent" else 0),
    "summary": f"Trimmed means {r['tm_1']:.2f} vs {r['tm_2']:.2f}: difference {r['diff']:.2f}, {cs.fmt_p(r['p'])}."
               + (f" Lens ({lens_kind.replace('_', ' ')}): {lens['lens_verdict']} ({cs.fmt_p(lens['lens_p'])})." if lens else ""),
    "apa": f"t({cs.fmt_num(r['df'])}) = {cs.fmt_num(r['t'])}, {cs.fmt_p(r['p'])}",
    "statistics": [{"key": "t", "label": "t", "value": r["t"]}, {"key": "df", "label": "df", "value": r["df"]},
                   {"key": "p", "label": "p", "value": r["p"], "format": "p"},
                   {"key": "diff", "label": f"Trimmed-mean difference ({label_1} − {label_2})", "value": r["diff"]},
                   {"key": "ci", "label": f"{conf:.0%} CI", "value": [r["ci_low"], r["ci_high"]]}]
                  + ([{"key": "lens_p", "label": f"Lens p ({lens_kind.replace('_', ' ')})", "value": lens["lens_p"], "format": "p"}] if lens else []),
    "tables": [{"key": "descriptives", "title": f"Descriptives ({trim:.0%} trimming)", "columns": [
        {"key": "sample", "label": "Sample", "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
        {"key": "trimmed_mean", "label": "Trimmed mean", "type": "number"}, {"key": "mean", "label": "Mean", "type": "number"},
        {"key": "median", "label": "Median", "type": "number"}, {"key": "win_sd", "label": "Winsorized SD", "type": "number"}], "rows": descr}],
    "effectSizes": effects,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Difference = {label_1} − {label_2}; {trim:.0%} trimmed from each tail; alternative: {alternative}."]
             + ([f"The lens interval [{lens['lens_ci_low']:.3g}, {lens['lens_ci_high']:.3g}] is the {1 - 2 * (1 - conf):.0%} interval for the trimmed-mean difference."] if lens else []),
    "values": values,
    "charts": [cs.chart("estimate", "forest", f"Trimmed-mean difference ({conf:.0%} CI)", {
        "label": cs.col("Estimate", [f"{label_1} − {label_2}"], "categorical"),
        "estimate": cs.col(f"Difference in {y}", [r["diff"]], "numeric"),
        "low": cs.col("CI low", [r["ci_low"]], "numeric"), "high": cs.col("CI high", [r["ci_high"]], "numeric")}, controls={"reference": 0})],
})
R

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

# Yuen's trimmed-means t-test (independent or paired)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method robust.yuen 1.1.1 · spec b068cc1a7845e371
# 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)

# %% Two samples (independent groups or paired measurements, from the bound roles)
y <- "len"
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]]
design <- "independent"
label_1 <- levels_g[1]
label_2 <- levels_g[2]

# %% Test
trim <- 0.2
conf <- 0.95
alternative <- "two-sided"
n1 <- length(x1)
n2 <- length(x2)
g1 <- floor(trim * n1)
g2 <- floor(trim * n2)
for (i in 1:2) {
  lab <- c(label_1, label_2)[i]
  if (c(n1, n2)[i] < 2) cs_error("CS_E_SMALL_GROUP", min = 2, group = if (design == "independent") paste0(g, " = ", lab) else lab, n = c(n1, n2)[i])
}
if (n1 - 2 * g1 < 2 || n2 - 2 * g2 < 2) {
  cs_error("CS_E_UNDEFINED", what = "Yuen's test", reason = "each sample needs at least two values left after trimming")
}
if (design == "independent") {
  if (length(unique(c(x1, x2))) < 2) cs_error("CS_E_CONSTANT", column = y)  # no variation: the standard error is 0
  if (diff(range(cs_winsorize(x1, trim))) == 0 && diff(range(cs_winsorize(x2, trim))) == 0) {
    cs_error("CS_E_UNDEFINED", what = "Yuen's test", reason = "neither group has any spread left after Winsorizing")
  }
} else if (all(x1 == x2)) {
  cs_error("CS_E_ALL_ZERO_DIFFERENCES")
}
if (design == "independent") {
  r <- cs_yuen(x1, x2, trim, conf, alternative)  # WRS2::yuen
  akp <- r$akp
} else {
  r <- cs_yuend(x1, x2, trim, conf, alternative)  # WRS2::yuend
  akp <- NULL
}

# Lens (equivalence / minimal effect / non-inferiority) on the trimmed-mean difference, at alpha = 1 - confidence.
lens_kind <- "none"
lens <- NULL
if (lens_kind != "none") lens <- cs_lens(lens_kind, r$diff, r$se, r$df, NULL, NULL, 1 - conf)

# %% Assumptions
assumptions <- list(
  list(key = "design", label = "Design", status = "info",
       detail = if (design == "independent") "Two independent groups (Yuen's test)." else "Paired measurements on the same rows (Yuen's paired test)."),
  list(key = "sample_size", label = "Enough values after trimming", status = if (min(n1 - 2 * g1, n2 - 2 * g2) < 5) "warn" else "pass",
       detail = sprintf("%d and %d values remain after trimming %d and %d from each tail.", n1 - 2 * g1, n2 - 2 * g2, g1, g2))
)

# %% Result
values <- list(t = r$t, df = r$df, p = r$p, diff = r$diff, se = r$se, ci_low = r$ci_low, ci_high = r$ci_high,
               tm_1 = r$tm_1, tm_2 = r$tm_2, n_1 = n1, n_2 = n2, trim = trim, akp = akp, design = design,
               label_1 = label_1, label_2 = label_2)
if (!is.null(lens)) values <- c(values, lens)
effects <- if (!is.null(akp)) list(list(key = "akp", label = "AKP robust d", value = akp, method = "0.642 × Δ_t / pooled winsorized SD (Algina et al. 2005)")) else list()
descr <- data.frame(sample = c(label_1, label_2), n = c(n1, n2), trimmed_mean = c(cs_trim_mean(x1, trim), cs_trim_mean(x2, trim)),
                    mean = c(mean(x1), mean(x2)), median = c(median(x1), median(x2)),
                    win_sd = c(sd(cs_winsorize(x1, trim)), sd(cs_winsorize(x2, trim))), stringsAsFactors = FALSE)
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0  # consult-a-statistician input
pct <- sprintf("%.0f%%", conf * 100)
cs_publish(list(
  method = "robust.yuen",
  methodVersion = "1.1.1",
  title = paste0("Yuen's trimmed-means t-test", if (design == "paired") " (paired)" else ""),
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n1 + if (design == "independent") n2 else 0,
  summary = paste0(sprintf("Trimmed means %.2f vs %.2f: difference %.2f, %s.", r$tm_1, r$tm_2, r$diff, cs_fmt_p(r$p)),
                   if (!is.null(lens)) sprintf(" Lens (%s): %s (%s).", gsub("_", " ", lens_kind), lens$lens_verdict, cs_fmt_p(lens$lens_p)) else ""),
  apa = sprintf("t(%s) = %s, %s", cs_fmt_num(r$df), cs_fmt_num(r$t), cs_fmt_p(r$p)),
  statistics = c(list(list(key = "t", label = "t", value = r$t), list(key = "df", label = "df", value = r$df),
                    list(key = "p", label = "p", value = r$p, format = "p"),
                    list(key = "diff", label = sprintf("Trimmed-mean difference (%s − %s)", label_1, label_2), value = r$diff),
                    list(key = "ci", label = paste(pct, "CI"), value = c(r$ci_low, r$ci_high))),
                 if (!is.null(lens)) list(list(key = "lens_p", label = sprintf("Lens p (%s)", gsub("_", " ", lens_kind)), value = lens$lens_p, format = "p")) else list()),
  tables = list(list(key = "descriptives", title = sprintf("Descriptives (%.0f%% trimming)", trim * 100),
                     columns = list(list(key = "sample", label = "Sample", type = "string"), list(key = "n", label = "n", type = "integer"),
                                    list(key = "trimmed_mean", label = "Trimmed mean", type = "number"), list(key = "mean", label = "Mean", type = "number"),
                                    list(key = "median", label = "Median", type = "number"), list(key = "win_sd", label = "Winsorized SD", type = "number")),
                     rows = descr)),
  effectSizes = effects,
  assumptions = assumptions,
  warnings = warnings,
  notes = c(list(sprintf("Difference = %s − %s; %.0f%% trimmed from each tail; alternative: %s.", label_1, label_2, trim * 100, alternative)),
            if (!is.null(lens)) list(sprintf("The lens interval [%.3g, %.3g] is the %.0f%% interval for the trimmed-mean difference.", lens$lens_ci_low, lens$lens_ci_high, (1 - 2 * (1 - conf)) * 100)) else list()),
  values = values,
  charts = list(cs_chart("estimate", "forest", sprintf("Trimmed-mean difference (%s CI)", pct), list(
    label = cs_col("Estimate", sprintf("%s − %s", label_1, label_2), "categorical"),
    estimate = cs_col(sprintf("Difference in %s", y), r$diff, "numeric"),
    low = cs_col("CI low", r$ci_low, "numeric"), high = cs_col("CI high", r$ci_high, "numeric")), controls = list(reference = 0)))
))

Sources

  • Yuen, K. K. (1974). The two-sample trimmed t for unequal population variances. Biometrika, 61, 165–170.
  • Algina, J., Keselman, H. J., & Penfield, R. D. (2005). An alternative to Cohen's standardized mean difference effect size. Psychological Methods, 10, 317–328.
  • Wilcox, R. R. (2017). Introduction to robust estimation and hypothesis testing (4th ed.). Academic Press.

From the CodeSplash method registry · robust.yuen v1.1.1.