Trimmed means and Yuen's test
Heavy tails blow up the variance and rob a t test of power. Yuen's test compares trimmed means, and changes the question slightly to answer it better.
What runs in CodeSplash
- STAT012Yuen trimmed mean test Runs in CodeSplash
- Yuen's trimmed-means t-test (independent or paired) Verified in Python and R
You will be able to
- Compute what a 20% trimmed mean keeps and removes
- Explain why trimming can raise power under heavy tails
- Report a Yuen result without calling it a test of means
Read first
What trimming does
ReadA 20% trimmed meanTrimmed meanThe mean after dropping a fixed share of the smallest and largest values (often 20% each side). sorts the values, removes the lowest 20% and the highest 20%, and averages the middle.
Its standard error uses the WinsorizedWinsorizingReplacing the most extreme values with the nearest remaining ones instead of dropping them. variance, where the removed values are replaced by the nearest kept value. Heavy tails stop inflating the spread.
See robustness
ExploreAdd contamination to the sample and watch the mean, the median and the trimmed mean respond. Notice which estimator holds still, and what it costs when the data are clean.
AExplorable · Robust measures of the center
How many bad points does it take to drag each measure of the center away?
Which measure moves furthest from zero?
Commit your prediction above to see the result
Make your prediction to see the result.
The statistic
ReadHere is the number of values kept in group and is its Winsorized variance. Degrees of freedom follow a Welch-style formula.
Predict the conclusion
PredictPredict first
Welch's t on ToothGrowth gave p = .061, a difference in means of 3.70.
The OJ group is skewed to the left, so its lower tail pulls its mean down. What happens to the p-value with 20% trimming?
Reveal
Yuen's is smaller: p = .029. Trimmed means are 21.7 and 16.6, a difference of 5.12, t(33.5) = 2.29.
Don't test-shop
ReflectWelch lands above 0.05 and Yuen falls below it. It's tempting to report whichever crosses the line.
Decide which question you want before seeing the results. If you care about the typical animal, trimmed means are a fine pre-specified choice. If you care about the population mean, including its tails, they answer a different question. Reporting both as a sensitivity analysis is honest; picking the winner isn't.
What would you have pre-specified for this study?
Read the result
Readt(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
View data
| Difference in len | CI high | Estimate | CI low |
|---|---|---|---|
| 5.122 | 9.676 | OJ − VC | 0.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)
| Sample | n | Trimmed mean | Mean | Median | Winsorized SD |
|---|---|---|---|---|---|
| OJ | 30 | 21.706 | 20.663 | 22.700 | 4.816 |
| VC | 30 | 16.583 | 16.963 | 16.500 | 5.451 |
- Difference = OJ − VC; 20% trimmed from each tail; alternative: two-sided.
The exact R script · R 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)))
))
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)
| Sample | n | Trimmed mean | Mean | Median | Winsorized SD |
|---|---|---|---|---|---|
| OJ | 30 | 21.706 | 20.663 | 22.700 | 4.816 |
| VC | 30 | 16.583 | 16.963 | 16.500 | 5.451 |
- Difference = OJ − VC; 20% trimmed from each tail; alternative: two-sided.
The exact Python script · Python 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})],
})
The robust standardized effect (Algina–Keselman–Penfield) is 0.64, with a 95% interval for the trimmed difference from 0.57 to 9.68.
The same logic works for paired data, trimming the differences: on the sleep study with 10% trimming, t(7) = −3.30, p = .013.
Check your understanding
CheckpointCheck yourself
A group has 20 values. With 20% trimming per tail, how many values does the trimmed mean average?
Show the answer
Answer: 12
Remove 4 from each end, leaving 20 − 8 = 12.
Check yourself
Yuen's test gives p = 0.03. Which sentence should you write?
Show the answer
Answer: b
The estimand is the trimmed mean. Under skew it can differ from both the mean and the median, so name it.
Check yourself
Why can trimming raise power when tails are heavy?
Show the answer
Answer: b
Under heavy tails a few extreme values dominate the variance. Reducing their influence shrinks the standard error more than it loses signal.
Do it in CodeSplash
In the appSet Trimming proportion (each tail); 20% is the usual default. Fill Groups for independent samples or Second measurement for paired data. Choose one, never both.
import pandas as pd
from scipy import stats
df = pd.read_csv("toothgrowth.csv")
oj = df.loc[df["supp"] == "OJ", "len"]
vc = df.loc[df["supp"] == "VC", "len"]
print(stats.ttest_ind(oj, vc, equal_var=False, trim=0.2))# install.packages("WRS2")
df <- read.csv("toothgrowth.csv")
WRS2::yuen(len ~ supp, data = df, tr = 0.2)Recap
Recap- A trimmed mean removes a fixed share from each tail, and its standard error uses the Winsorized variance.
- Under heavy tails it can be far more powerful than a mean-based test.
- Name the estimand, and choose it before you see the results.
Concepts in this lesson