Skip to content

Step 3: remedies and what they change

Every remedy for a failed assumption changes something: the estimand, the scale, the power. Learn what each one costs, and use it as a sensitivity run rather than a way to find a better p-value.

Applied ~12 min8 steps

What runs in CodeSplash

You will be able to

  • Match a remedy to the assumption it addresses
  • State the estimand change each remedy brings
  • Read a concordance badge and act on discordance

Read first

01

Remedies have prices

Read

Step 3 is a menu. Each option deals with one problem and changes something else.

RemedyDeals withWhat changes
WelchUnequal variancesAlmost nothing; a little power
Mann–WhitneySkew, outliers, ordinal dataCompares distributions, not means
Trimmed means (Yuen)Heavy tails, outliersCompares trimmed means
Log transformRight skewCompares geometric means, as a ratio
PermutationNo trusted formulaExchangeability replaces normality
BootstrapNo formula for the intervalRelies on the sample's shape
Generalized modelCounts, binary, skewed outcomesA new scale for the effect
02

What changed?

Predict

Predict first

You started by comparing means. Which of these remedies moves you to a different question?

Permutation test on the mean differenceMann–WhitneyWelch's t
Reveal

Mann–Whitney. Its card reports a Hodges–Lehmann shift and a probability of superiority, not a mean difference. Welch and the permutation test on the mean difference still compare means, and only change how the p-value is calibrated.

03

One dataset, many remedies

Read

ToothGrowth, under several methods:

MethodComparesResult
Welch's tMeansp = .061
PermutationMeansp = .066
Mann–WhitneyDistributionsp = .064
Yuen20% trimmed meansp = .029

Three of these stay close together. Yuen differs, and its estimate differs too: a trimmed difference of 5.12 against a mean difference of 3.70. That is a real finding about the shape of the data, so it is worth saying, not choosing.

04

Transform, and read on the new scale

Explore

Raise the skew and try each transformation. See which one straightens the Q–Q plot. Then ask what your effect would mean on that scale.

AExplorable · The transformations workbench

Which transformation makes skewed data look normal, and what does Box–Cox suggest?

This data is right-skewed. Which simple transform will remove the most skew?

How sure?
0.90
120

Transform

0.50

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 difference in logs, back-transformed, is a ratio of geometric means: "about 1.31.3 times as large", not "3 units larger". That is often a better summary of a skewed outcome, so long as you say so.

05

Primary, then sensitivity

Read

In CodeSplash, remedies appear under the assumption checks. Running one saves a separate sensitivity analysis, and the primary result stays as it was. Each run gets a badge, and a note on the estimand when it changed.

BadgeMeansDo
ConcordantSame conclusionReport the primary; mention the check
Partly concordantSome parts agreeLook at which, and why
DiscordantDifferent conclusionDon't pick one; find the reason
Mann–Whitney U testRecorded · Python and R agreeRecorded 2026-11-21 · 15 values compared
R

U = 575.5, p = .064, r = .28

U
575.50
p
.064
Hodges–Lehmann shift (OJ − VC)
4

Effect size

  • Rank-biserial r 0.2789 · small
  • Probability of superiority 0.6394

Plots

len by suppHow do groups compare in shape, summary and individual observations at once?
View data
supplen
VC4.200
VC11.500
VC7.300
VC5.800
VC6.400
VC10
VC11.200
VC11.200
VC5.200
VC7
VC16.500
VC16.500
VC15.200
VC17.300
VC22.500
VC17.300
VC13.600
VC14.500
VC18.800
VC15.500
VC23.600
VC18.500
VC33.900
VC25.500
VC26.400
VC32.500
VC26.700
VC21.500
VC23.300
VC29.500
OJ15.200
OJ21.500
OJ17.600
OJ9.700
OJ14.500
OJ10
OJ8.200
OJ9.400
OJ16.500
OJ9.700
OJ19.700
OJ23.300
OJ23.600
OJ26.400
OJ20
OJ25.200
OJ25.800
OJ21.200
OJ14.500
OJ27.300
OJ25.500
OJ26.400
OJ22.400
OJ24.500
OJ24.800
OJ30.900
OJ26.400
OJ27.300
OJ29.400
OJ23

Assumptions

  • Comparable shapes — With similar distribution shapes the test compares medians; otherwise it compares P(first > second).

Descriptives

suppnMedianQ1Q3Mean rank
OJ3022.70015.52525.72534.683
VC3016.50011.20023.10026.317
  • Normal approximation with tie correction and continuity correction; alternative: two-sided.
  • Hodges–Lehmann shift 4, 95% Moses interval [-0.1, 8.5].
The exact R script · R R version 4.5.1 (2025-06-13)
# Mann–Whitney U test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method nonparam.mann_whitney 1.3.0 · spec 81df0c13fc07b2b5
# 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)

# %% Helpers
magnitude <- function(x, cuts, labels = c("negligible", "small", "medium", "large")) {
  # Benchmark label for an effect size (rule set named in the result)
  if (is.null(x) || !is.finite(x)) return("undetermined")
  labels[findInterval(abs(x), cuts) + 1]
}

# %% Test
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]]
if (length(unique(c(x1, x2))) < 2) cs_error("CS_E_CONSTANT", column = y)  # every rank tied: the test statistic is 0/0
n1 <- length(x1)
n2 <- length(x2)
alternative <- "two-sided"
correct <- TRUE  # continuity correction (pinned)
method <- "asymptotic"
ties <- length(unique(c(x1, x2))) < n1 + n2
if (method == "exact" && ties) {
  # Exact null distributions assume no ties: use the tie-corrected normal approximation.
  method <- "asymptotic"
  warnings <- c(warnings, "Tied values: the exact p-value is unavailable, so the tie-corrected normal approximation was used.")
}

res <- wilcox.test(x1, x2, alternative = sub("-", ".", alternative, fixed = TRUE), exact = method == "exact", correct = correct)
u <- unname(res$statistic)  # W = U for the first group
p <- res$p.value
perm_extra <- list()
if (method == "permutation") {  # Stage 12.7 option: Monte Carlo permutation p (shared Wichmann-Hill stream)
  perm <- cs_rank_sum_perm_p(x1, x2, alternative, as.integer(9999), as.integer(1))
  p <- perm$p
  perm_extra <- list(n_perm = perm$b, perm_count = perm$count)
}
r_rb <- 2 * u / (n1 * n2) - 1  # rank-biserial correlation; positive = first group tends higher
cles <- u / (n1 * n2)  # P(first > second) + 1/2 P(tie)
hl <- median(outer(x1, x2, "-"))  # Hodges-Lehmann shift (first - second)
# Moses (1953) distribution-free 95% interval for the shift; its normal-approximation SE,
# (upper - lower) / (2 z_0.975), is what the lenses below use (normal reference, df = NULL).
hlci <- cs_hodges_lehmann_ci(x1, x2, 0.95)
lens_kind <- "none"
if (is.null(lens_kind)) lens_kind <- "none"
lens <- NULL
if (lens_kind != "none") lens <- cs_lens(lens_kind, hl, hlci$se, NULL, NULL, NULL, 0.05)
med1 <- median(x1)
med2 <- median(x2)

# %% Result
alpha <- 0.05
size <- magnitude(r_rb, c(0.1, 0.3, 0.5))
significance <- if (p < alpha) {
  sprintf("The groups differ significantly (%s).", cs_fmt_p(p))
} else {
  sprintf("The data are compatible with no difference in location (%s).", cs_fmt_p(p))
}
summary <- sprintf(
  "%s tended to be %s in %s (median %.2f) than in %s (median %.2f). %s The rank-biserial correlation is %s (r = %.2f); a randomly chosen %s value exceeds a %s value with probability %.2f.",
  y, if (r_rb > 0) "higher" else "lower", levels_g[1], med1, levels_g[2], med2, significance, size, r_rb, levels_g[1], levels_g[2], cles
)
if (!is.null(lens)) summary <- paste(summary, sprintf("Lens (%s) on the Hodges–Lehmann shift: %s (%s).", gsub("_", " ", lens_kind), lens$lens_verdict, cs_fmt_p(lens$lens_p)))
ranks <- rank(c(x1, x2))
chart_rows <- unique(round(seq(1, nrow(df), length.out = min(nrow(df), 5000))))
cs_publish(list(
  method = "nonparam.mann_whitney",
  methodVersion = "1.3.0",
  title = "Mann–Whitney U test",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n1 + n2,
  summary = summary,
  apa = sprintf("U = %s, %s, r = %s", format(u), cs_fmt_p(p), cs_fmt_num(r_rb, leading_zero = FALSE)),
  statistics = c(list(
    list(key = "u", label = "U", value = u),
    list(key = "p", label = "p", value = p, format = "p"),
    list(key = "hl_shift", label = sprintf("Hodges–Lehmann shift (%s − %s)", levels_g[1], levels_g[2]), value = hl)
  ), 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 = "Descriptives",
    columns = list(list(key = "group", label = g, type = "string"), list(key = "n", label = "n", type = "integer"),
                   list(key = "median", label = "Median", type = "number"), list(key = "q1", label = "Q1", type = "number"),
                   list(key = "q3", label = "Q3", type = "number"), list(key = "mean_rank", label = "Mean rank", type = "number")),
    rows = data.frame(group = levels_g, n = c(n1, n2), median = c(med1, med2),
                      q1 = c(quantile(x1, 0.25, type = 7), quantile(x2, 0.25, type = 7)),
                      q3 = c(quantile(x1, 0.75, type = 7), quantile(x2, 0.75, type = 7)),
                      mean_rank = c(mean(ranks[seq_len(n1)]), mean(ranks[n1 + seq_len(n2)])), row.names = NULL)
  )),
  effectSizes = list(
    list(key = "rank_biserial", label = "Rank-biserial r", value = r_rb, method = "2U / (n1 n2) − 1", magnitude = size, ruleSet = "Cohen (1988), r"),
    list(key = "cles", label = "Probability of superiority", value = cles, method = "U / (n1 n2)")
  ),
  assumptions = list(list(key = "shape", label = "Comparable shapes", status = "info",
                          detail = "With similar distribution shapes the test compares medians; otherwise it compares P(first > second).")),
  warnings = warnings,
  notes = c(list(sprintf("%s; alternative: %s.", if (method == "exact") "Exact" else if (method == "permutation") sprintf("Permutation p-value (%d permutations of the group labels, (count + 1) / (B + 1))", perm_extra$n_perm) else paste0("Normal approximation with tie correction", if (correct) " and continuity correction" else ""), alternative),
                 sprintf("Hodges–Lehmann shift %.3g, 95%% Moses interval [%.3g, %.3g].", hl, hlci$ci_low, hlci$ci_high)),
            if (!is.null(lens)) list(sprintf("The lens interval [%.3g, %.3g] is the 90%% normal-approximation interval for the shift (SE from the Moses interval).",
                                             lens$lens_ci_low, lens$lens_ci_high)) else list()),
  values = c(list(u = u, p = p, n_1 = n1, n_2 = n2, rank_biserial = r_rb, cles = cles, hl_shift = hl,
                median_1 = med1, median_2 = med2, method = method, level_1 = as.character(levels_g[1]), level_2 = as.character(levels_g[2]),
                hl_ci_low = hlci$ci_low, hl_ci_high = hlci$ci_high, hl_se = hlci$se), lens, perm_extra),
  charts = list(cs_chart("distribution", "raincloud", sprintf("%s by %s", y, g),
                         list(y = cs_col(y, df[[y]][chart_rows]), group = cs_col(g, as.character(df[[g]][chart_rows]), levels = levels(df[[g]])))))
))
Python

U = 575.5, p = .064, r = .28

U
575.50
p
.064
Hodges–Lehmann shift (OJ − VC)
4.000

Effect size

  • Rank-biserial r 0.2789 · small
  • Probability of superiority 0.6394

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

Assumptions

  • Comparable shapes — With similar distribution shapes the test compares medians; otherwise it compares P(first > second).

Descriptives

suppnMedianQ1Q3Mean rank
OJ3022.70015.52525.72534.683
VC3016.50011.20023.10026.317
  • Normal approximation with tie correction and continuity correction; alternative: two-sided.
  • Hodges–Lehmann shift 4, 95% Moses interval [-0.1, 8.5].
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Mann–Whitney U test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method nonparam.mann_whitney 1.3.0 · spec 81df0c13fc07b2b5
# 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 means as csm
from codesplash.stats import rank_tests

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

# %% Helpers
def magnitude(x, cuts, labels=("negligible", "small", "medium", "large")):
    """Benchmark label for an effect size (rule set named in the result)."""
    if x is None or not np.isfinite(x):
        return "undetermined"
    for cut, label in zip(cuts, labels):
        if abs(x) < cut:
            return label
    return labels[-1]

# %% Test
y, g = "len", "supp"
levels = list(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] == levels[0], y].to_numpy(dtype=float)
x2 = df.loc[df[g] == levels[1], y].to_numpy(dtype=float)
if len(np.unique(np.concatenate([x1, x2]))) < 2:  # every rank tied: the test statistic is 0/0
    cs.cs_error("CS_E_CONSTANT", column=y)
n1, n2 = len(x1), len(x2)
alternative = "two-sided"
correct = True  # continuity correction (pinned; both engines default to True)
method = "asymptotic"
ties = len(np.unique(np.concatenate([x1, x2]))) < n1 + n2
if method == "exact" and ties:
    # Exact null distributions assume no ties (R falls back too): use the tie-corrected normal approximation.
    method = "asymptotic"
    warnings.append("Tied values: the exact p-value is unavailable, so the tie-corrected normal approximation was used.")

res = stats.mannwhitneyu(x1, x2, alternative=alternative, use_continuity=correct,
                         method="asymptotic" if method == "permutation" else method)
u, p = float(res.statistic), float(res.pvalue)  # U for the first group (= R's W)
perm_extra = {}
if method == "permutation":  # Stage 12.7 option: Monte Carlo permutation p (shared Wichmann–Hill stream)
    from codesplash.stats import stat_options as csopt
    perm = csopt.rank_sum_perm_p(x1, x2, alternative, int(9999), int(1))
    p = perm["p"]
    perm_extra = {"n_perm": perm["b"], "perm_count": perm["count"]}
p_desc = ("Exact" if method == "exact"
          else f"Permutation p-value ({perm_extra['n_perm']} permutations of the group labels, (count + 1) / (B + 1))" if method == "permutation"
          else "Normal approximation with tie correction" + (" and continuity correction" if correct else ""))
r_rb = 2 * u / (n1 * n2) - 1  # rank-biserial correlation; positive = first group tends higher
cles = u / (n1 * n2)  # P(first > second) + ½ P(tie)
hl = float(np.median(np.subtract.outer(x1, x2)))  # Hodges–Lehmann shift (first − second)
# Moses (1953) distribution-free 95% interval for the shift; its normal-approximation SE,
# (upper − lower) / (2 z₀.₉₇₅), is what the lenses below use (normal reference, df = None).
hlci = rank_tests.hodges_lehmann_ci(x1, x2, 0.95)
lens_kind = "none" or "none"
lens = None
if lens_kind != "none":
    lens = csm.lens(lens_kind, hl, hlci["se"], None, None, None, 0.05)
med1, med2 = float(np.median(x1)), float(np.median(x2))

# %% Result
alpha = 0.05
size = magnitude(r_rb, (0.1, 0.3, 0.5))
significance = (
    f"The groups differ significantly ({cs.fmt_p(p)})." if p < alpha
    else f"The data are compatible with no difference in location ({cs.fmt_p(p)})."
)
summary = (
    f"{y} tended to be {'higher' if r_rb > 0 else 'lower'} in {levels[0]} (median {med1:.2f}) than in {levels[1]} "
    f"(median {med2:.2f}). {significance} The rank-biserial correlation is {size} (r = {r_rb:.2f}); a randomly chosen "
    f"{levels[0]} value exceeds a {levels[1]} value with probability {cles:.2f}."
)
if lens:
    summary += f" Lens ({lens_kind.replace('_', ' ')}) on the Hodges–Lehmann shift: {lens['lens_verdict']} ({cs.fmt_p(lens['lens_p'])})."
chart_rows = np.unique(np.round(np.linspace(0, len(df) - 1, min(len(df), 5000))).astype(int))
cs.publish({
    "method": "nonparam.mann_whitney",
    "methodVersion": "1.3.0",
    "title": "Mann–Whitney U test",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n1 + n2,
    "summary": summary,
    "apa": f"U = {u:g}, {cs.fmt_p(p)}, r = {cs.fmt_num(r_rb, leading_zero=False)}",
    "statistics": [
        {"key": "u", "label": "U", "value": u},
        {"key": "p", "label": "p", "value": p, "format": "p"},
        {"key": "hl_shift", "label": f"Hodges–Lehmann shift ({levels[0]} − {levels[1]})", "value": hl},
    ] + ([{"key": "lens_p", "label": f"Lens p ({lens_kind.replace('_', ' ')})", "value": lens["lens_p"], "format": "p"}] if lens else []),
    "tables": [{
        "key": "descriptives", "title": "Descriptives",
        "columns": [{"key": "group", "label": g, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
                    {"key": "median", "label": "Median", "type": "number"}, {"key": "q1", "label": "Q1", "type": "number"},
                    {"key": "q3", "label": "Q3", "type": "number"}, {"key": "mean_rank", "label": "Mean rank", "type": "number"}],
        "rows": [
            {"group": str(lv), "n": len(x), "median": float(np.median(x)), "q1": float(np.quantile(x, 0.25)), "q3": float(np.quantile(x, 0.75)),
             "mean_rank": float(stats.rankdata(np.concatenate([x1, x2]))[i * n1:(n1 if i == 0 else n1 + n2)].mean())}
            for i, (lv, x) in enumerate(zip(levels, (x1, x2)))
        ],
    }],
    "effectSizes": [
        {"key": "rank_biserial", "label": "Rank-biserial r", "value": r_rb, "method": "2U / (n1 n2) − 1", "magnitude": size, "ruleSet": "Cohen (1988), r"},
        {"key": "cles", "label": "Probability of superiority", "value": cles, "method": "U / (n1 n2)"},
    ],
    "assumptions": [{"key": "shape", "label": "Comparable shapes", "status": "info",
                     "detail": "With similar distribution shapes the test compares medians; otherwise it compares P(first > second)."}],
    "warnings": warnings,
    "notes": [f"{p_desc}; alternative: {alternative}.",
              f"Hodges–Lehmann shift {hl:.3g}, 95% Moses interval [{hlci['ci_low']:.3g}, {hlci['ci_high']:.3g}]."]
             + ([f"The lens interval [{lens['lens_ci_low']:.3g}, {lens['lens_ci_high']:.3g}] is the 90% normal-approximation interval for the shift "
                 "(SE from the Moses interval)."] if lens else []),
    "values": {
        "u": u, "p": p, "n_1": n1, "n_2": n2, "rank_biserial": r_rb, "cles": cles, "hl_shift": hl,
        "median_1": med1, "median_2": med2, "method": method, "level_1": str(levels[0]), "level_2": str(levels[1]),
        "hl_ci_low": hlci["ci_low"], "hl_ci_high": hlci["ci_high"], "hl_se": hlci["se"],
        **(lens or {}),
        **perm_extra,
    },
    "charts": [cs.chart("distribution", "raincloud", f"{y} by {g}", {
        "y": cs.col(y, df[y].to_numpy(dtype=float)[chart_rows]),
        "group": cs.col(g, df[g].astype(str).to_numpy()[chart_rows], levels=[str(x) for x in df[g].cat.categories])})],
})
06

Check your understanding

Checkpoint

Check yourself

You analyzed log(income) and got a back-transformed difference of 1.2. How do you report it?

Show the answer

Answer: b

A difference in logs is a ratio. It describes geometric means, and it matches the ratio of medians only if the log scale is symmetric.

Check yourself

Your primary t test gives p = .03, and a Mann–Whitney sensitivity run gives p = .15 (badge: Discordant). What should you do?

Show the answer

Answer: c

Disagreement is information. Perhaps outliers drive the means. A reader needs to know, and a tie-breaker test only adds a fork.

Check yourself

Your outcome is a count of events per person with many zeros and a long tail. Which remedy best addresses the shape of the data?

Show the answer

Answer: c

Generalized models build the shape into the likelihood. log(0) is undefined, and deleting zeros changes the question.

Check yourself

You find an extreme value. What comes first?

Show the answer

Answer: a

Outliers can be mistakes or your most interesting data. Decide based on what the point is, not on what its removal does to the result.

07

Try a remedy

In the app

Run a t test, then look for remedies under the assumption rows. Run one and read its badge and the note on what changed. Some remedies transform in Prepare first, and then rerun on a new dataset version, so the transformation stays on record.

08

Recap

Recap
  • Each remedy fixes one thing and changes another, often the estimand.
  • Keep your primary analysis, and run remedies as labeled sensitivity checks.
  • Discordance is a reason to look harder, not a chance to pick a favorite.

Concepts in this lesson