Skip to content

The robust mindset

Ask what would have to go wrong for your answer to change. Use robust methods and sensitivity runs to find out, without turning them into a search for a smaller p-value.

Applied ~10 min8 steps

What runs in CodeSplash

You will be able to

  • Explain what robustness means and what it doesn't
  • Compare a mean-based and a trimmed-mean analysis and name what changed
  • Use a sensitivity run without turning it into p-hacking

Read first

01

What would change your mind?

Read

A robust analysis asks a simple question: if a few values were wrong, or the tails were heavier than you assumed, would your answer change?

Two ideas carry most of it. The breakdown point is the share of bad data an estimator can take before it follows them anywhere: for the mean, a single point; for the median, half. And efficiency is what you pay for that protection when the data are clean.

02

Three methods on bad points

Explore

Move the contamination further from the data, then add more bad points. Find the share where each measure of the center gives up.

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?

How sure?
20
2
10.0
true centerMean0.96Huber0.1820% trimmed0.23Median0.38

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

A trimmed meanTrimmed meanThe mean after dropping a fixed share of the smallest and largest values (often 20% each side). drops a fixed share from each end before averaging. At 20% it keeps a large part of the mean's efficiency and much of the median's resistance.

03

Same data, trimmed

Predict

Predict first

Welch's t test on ToothGrowth gives p = .061 for a difference in means of 3.70. What happens to p under Yuen's testTrimmed meanThe mean after dropping a fixed share of the smallest and largest values (often 20% each side). with 20% trimming?

Larger than .061Smaller than .061About the same
Reveal

Smaller: p = .029, for a difference in trimmed means of 5.12 (21.7 against 16.6). The estimand moved, because orange juice is left-skewed. The quantity being compared is no longer the same one.

04

The honest way to use it

Read

That smaller p is a trap. Decide which analysis is primary before seeing results, and treat the rest as sensitivity runs. Then ask:

  • Do they point the same way?
  • Did the estimand change, and does your conclusion hold for the new one?
  • If they disagree, why?

In CodeSplash, a remedy never replaces your primary analysis. It runs alongside and gets a badge: Concordant, Partly concordant or Discordant. Discordance is a reason to look closer, not a chance to pick the winner.

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.
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)))
))
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.
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})],
})
05

Beyond two groups

Read

The same idea extends to several groups: trimmed means with Welch-type degrees of freedom, and the explanatory measure of effect size ξ\xi, which here is 0.550 with p = .004.

06

Think about your own data

Reflect

Take a result you care about. Which assumption, if wrong, would change your conclusion most? A handful of outliers, a skewed outcome, or a clump of rows from one source? Which sensitivity run would show that, and what would you do if it disagreed? Writing the answer down before you run it is what separates checking from fishing.

07

Check your understanding

Checkpoint

Check yourself

What is the breakdown point of the sample median?

Show the answer

Answer: d

The median follows bad points only when they outnumber the good ones. The mean follows the first bad point that moves far enough.

Check yourself

Your planned t test gives p = .08, and a trimmed test gives p = .03. What do you report?

Show the answer

Answer: c

Both are informative. Switching primaries because one crossed .05 is a forking path.

Check yourself

Which statement about a 20% trimmed mean on skewed data is right?

Show the answer

Answer: b

Under symmetry the two targets coincide. Under skew they don't, which is a matter to state, not to hide.

08

Recap

Recap
  • Robustness asks how much bad data or wrong assumptions it takes to change your answer.
  • A robust method often changes the estimand as well as the p-value, so name what changed.
  • Fix the primary analysis first, and treat the others as sensitivity runs.

Concepts in this lesson