Skip to content

ADescribe · outliers.univariate

Outliers (univariate)

Which values of a numeric variable are unusually far from the rest?

Seven rules side by side — Tukey fences, z-scores, modified z-scores (median/MAD), Grubbs' test for the most extreme value, Rosner's generalized ESD for several, Dixon's Q for small samples and Tietjen–Moore for a prespecified number of outliers — with a table of flagged rows and how many rules agree, optionally within each group. Flags are for investigation, never for automatic deletion.

Verified in Python and R Python and R agree to 10 decimals Seeded Also called Dixon's Q test, Dixon test, Tietjen-Moore test…

A real result

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

OutliersRecorded · Python and R agreeRecorded 2026-11-17 · 44 values compared
R

Grubbs' G = 4.31, p < .001

Flagged (any rule)
2
Flagged by ≥ 2 rules
2
Grubbs p
< .001
Dixon p
< .001

Plots

reading: flagged vs not flaggedWhat do all the observations look like per group, next to the group mean and its uncertainty?
View data
Statusreading
Not flagged10.200
Not flagged9.800
Not flagged10.500
Not flagged10.100
Not flagged9.600
Not flagged10.900
Not flagged10.300
Not flagged9.900
Not flagged10
Not flagged10.400
Not flagged9.700
Not flagged10.600
Not flagged10.200
Not flagged9.500
Not flagged10.800
Not flagged10.100
Not flagged9.900
Not flagged10.300
Not flagged10
Not flagged10.700
Not flagged9.800
Not flagged10.200
Not flagged10.500
Not flagged9.400
Not flagged10.100
Flagged14.900
Not flagged10
Not flagged10.300
Flagged3.100
Not flagged10.200

Rules

RuleCriterionFlagged
Tukey fences (k = 1.5)outside [9.188, 11.09]2
z-score (|z| > 3)SD with n − 11
Modified z (|M| > 3.5)median and MAD (Iglewicz & Hoaglin)2
Grubbs' testG = 4.307, p = 1.389e-061
Generalized ESD (up to 3)α = 0.052
Dixon's Q testr22: Q = 0.8312, p = 0.0001 (lowest value)1
Tietjen–Moore (k = 2)k = 2: E = 0.0502, p = 0.00012

Flagged values

RowidreadingzModified zTukeyz ruleMod. zGrubbsESDDixonT–MRules
29r293.100−4.307−19.021truetruetruetruetruetruetrue4
26r2614.9002.98812.815truefalsetruefalsetruefalsetrue3

Generalized ESD steps

iValueRλ (critical)Outlier
13.1004.3072.908true
214.9004.7982.893true
310.9002.0162.876false
  • Flag, investigate, decide: correct entry errors, set impossible values to missing, keep genuine values. Never delete automatically; compare results with and without flagged values (sensitivity analysis).
  • Grubbs, the generalized ESD, Dixon and Tietjen–Moore assume the remaining values are normal. Dixon's ratios suit 3–30 values; Tietjen–Moore tests exactly k values chosen before looking at the data.
  • Dixon and Tietjen–Moore p-values are Monte-Carlo (9,999 normal samples, seed 1); they match in Python and R.
Python

Grubbs' G = 4.31, p < .001

Flagged (any rule)
2
Flagged by ≥ 2 rules
2
Grubbs p
< .001
Dixon p
< .001

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

Rules

RuleCriterionFlagged
Tukey fences (k = 1.5)outside [9.188, 11.09]2
z-score (|z| > 3)SD with n − 11
Modified z (|M| > 3.5)median and MAD (Iglewicz & Hoaglin)2
Grubbs' testG = 4.307, p = 1.389e-061
Generalized ESD (up to 3)α = 0.052
Dixon's Q testr22: Q = 0.8312, p = 0.0001 (lowest value)1
Tietjen–Moore (k = 2)k = 2: E = 0.0502, p = 0.00012

Flagged values

RowidreadingzModified zTukeyz ruleMod. zGrubbsESDDixonT–MRules
29r293.100−4.307−19.021truetruetruetruetruetruetrue4
26r2614.9002.98812.815truefalsetruefalsetruefalsetrue3

Generalized ESD steps

iValueRλ (critical)Outlier
13.1004.3072.908true
214.9004.7982.893true
310.9002.0162.876false
  • Flag, investigate, decide: correct entry errors, set impossible values to missing, keep genuine values. Never delete automatically; compare results with and without flagged values (sensitivity analysis).
  • Grubbs, the generalized ESD, Dixon and Tietjen–Moore assume the remaining values are normal. Dixon's ratios suit 3–30 values; Tietjen–Moore tests exactly k values chosen before looking at the data.
  • Dixon and Tietjen–Moore p-values are Monte-Carlo (9,999 normal samples, seed 1); they match in Python and R.

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

  • Planteds1_outliers · label: id · variable: reading
  • Mad zeros1_outliers · variable: mostly_same
  • Mad zero lowers1_outliers · variable: mostly_same
  • Planted uppers1_outliers · label: id · variable: reading
  • Ozone missingairquality · variable: Ozone
  • Small nplantgrowth · variable: weight
  • Dixon guide r10c3_dixon · label: id · variable: reading
  • Dixon auto r22c3_dixon · variable: series

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • Outliers: boxplot IQR rule · Statistics Guide · A — Describe data
  • Outliers: z-scores > |3| · Statistics Guide · A — Describe data
  • Outliers: modified z (MAD) · Statistics Guide · A — Describe data
  • Outliers: Grubbs (one outlier, normal) · Statistics Guide · A — Describe data
  • Outliers: generalized ESD · Statistics Guide · A — Describe data
  • Outliers / influential points · Statistics Guide · Step 2 — Check assumptions
  • Outlier investigation workflow · Statistics Guide · Step 3 — If assumptions are violated
  • Automated EDA (profiling, anomaly detection) · DS & ML Decision Guide · Describe — summarize and visualize

What you need

Variablenumeric · 1 column
The numeric variable to screen.
Row labelscategorical · 0–1 column
Optional ID or name column shown next to flagged values.
Screen within groupscategorical / boolean · 0–1 column
Optional: each group is screened on its own, so values are judged against their own group.

Choices you make

statistics

Tukey fence multiplier (k)default 1.5

1.5 = inner fences, 3 = outer fences (far out).

z-score thresholddefault 3

|z| above this is flagged (3 or 3.29 are common); unused when n ≤ 10.

Modified z thresholddefault 3.5

Iglewicz & Hoaglin recommend 3.5.

Most outliers for the generalized ESDdefault 3

Rosner's test looks for up to this many outliers; set it generously but below n/2.

Dixon ratiodefault auto

Dixon's Q compares the gap next to the extreme value with the range; it is meant for 3–30 values.

  • Recommended for n (r10, r11, r21 or r22)(default) — Dixon's choice: r10 for 3–7 values, r11 for 8–10, r21 for 11–13, r22 for 14–30.
  • r10 — gap to the next value over the range — Gap to the next value over the full range; the form for about 3 to 7 values and one suspect.
  • r11 — range without the other extreme — Leaves the other extreme out of the range; the form for about 8 to 10 values.
  • r12 — range without the two other extremes — Leaves the two other extremes out of the range; pick it when the far end may also hold unusual values.
  • r20 — gap to the second value over the range — Protects against a second outlier masking the first.
  • r21 — double gap, range without the other extreme — Uses the gap to the second-nearest value; the form for about 11 to 13 values, when a neighbor may mask the suspect.
  • r22 — double gap, range without the two other extremes — Uses the double gap and leaves two extremes out of the range; the form for about 14 or more values.
Suspected outliers (Tietjen–Moore k)default 2

Tietjen–Moore tests exactly this many extreme values; fix k before looking at the data.

hypothesis

Significance level (Grubbs / ESD)default 0.05

False-alarm rate for flagging a point with Grubbs or generalized ESD. Lower flags fewer points.

Which end to test (Grubbs, Dixon, Tietjen–Moore)default two_sided

Two-sided tests the most extreme value in either direction. Choose upper or lower only if you decided which end to test before looking at the data; picking the end that looks extreme and then testing one-sided doubles false alarms.

  • Either end (two-sided)(default) — Tests the value farther from the mean; the p-value counts both directions.
  • Largest values only — Tests the largest value (Tietjen–Moore: the k largest), chosen in advance.
  • Smallest values only — Tests the smallest value (Tietjen–Moore: the k smallest), chosen in advance.

options

Monte-Carlo samplesdefault 9999

Normal samples simulated for the Dixon and Tietjen–Moore p-values (the same draws in Python and R).

Random seeddefault 1

Seed of the Monte-Carlo stream; change it to see how much the p-values move.

What it reports

n
How many independent units the analysis used; it sets precision and power.
mean
The sum divided by the count; the balance point of the data, pulled by extreme values.
sd
The typical distance of values from their mean, in the data's own units.
median
The middle value when the data are sorted; half the values lie on each side.
tukey_low
A range of effect values compatible with your data at the chosen confidence level.
tukey_high
A range of effect values compatible with your data at the chosen confidence level.
outer_low
A range of effect values compatible with your data at the chosen confidence level.
outer_high
A range of effect values compatible with your data at the chosen confidence level.
n_tukey
How many independent units the analysis used; it sets precision and power.
n_tukey_outer
How many independent units the analysis used; it sets precision and power.
n_z
An estimate in standard-error units, compared with the standard normal distribution.
z_enabled
An estimate in standard-error units, compared with the standard normal distribution.
max_abs_z
An estimate in standard-error units, compared with the standard normal distribution.
n_modz
How many independent units the analysis used; it sets precision and power.
max_abs_modz
The median distance of values from the median; a spread measure that resists outliers.
grubbs_g
Tests whether the most extreme value is an outlier, assuming the rest is normal. It finds one outlier at a time.
grubbs_p
How surprising your data would be if the null hypothesis were true, as a probability.
grubbs_value
Tests whether the most extreme value is an outlier, assuming the rest is normal. It finds one outlier at a time.
grubbs_side
Tests whether the most extreme value is an outlier, assuming the rest is normal. It finds one outlier at a time.
grubbs_row
Tests whether the most extreme value is an outlier, assuming the rest is normal. It finds one outlier at a time.
gesd_n
Extends Grubbs to find up to k outliers at once, without one outlier hiding another (Rosner 1983).
dixon_type
For 3–30 values, compares the gap between the most extreme value and its neighbor with the range of the data.
dixon_q
For 3–30 values, compares the gap between the most extreme value and its neighbor with the range of the data.
dixon_p
For 3–30 values, compares the gap between the most extreme value and its neighbor with the range of the data.
dixon_value
For 3–30 values, compares the gap between the most extreme value and its neighbor with the range of the data.
dixon_side
For 3–30 values, compares the gap between the most extreme value and its neighbor with the range of the data.
tm_k
Tests whether exactly k extreme values are outliers by how much the spread shrinks when they are removed (E close to 0 → outliers).
tm_e
Tests whether exactly k extreme values are outliers by how much the spread shrinks when they are removed (E close to 0 → outliers).
tm_p
Tests whether exactly k extreme values are outliers by how much the spread shrinks when they are removed (E close to 0 → outliers).
tm_side
Tests whether exactly k extreme values are outliers by how much the spread shrinks when they are removed (E close to 0 → outliers).
mc_reps
A p-value estimated from simulated or resampled statistics, with its own small sampling error.
n_groups
How many independent units the analysis used; it sets precision and power.
n_flagged_any
How many independent units the analysis used; it sets precision and power.
n_consensus
How many independent units the analysis used; it sets precision and power.
flagged_rows
A value far from the rest; it may be an error, a rare real case or a sign of a heavy-tailed process.

Per group, level or term: gesd_r[<step>], gesd_lambda[<step>], gesd_value[<step>], n[<group>], n_flagged[<group>], tukey_low[<group>], tukey_high[<group>], grubbs_p[<group>], dixon_p[<group>], tm_p[<group>]

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

  • Grubbs p uses the t tail and the ESD critical values t quantiles (scipy cephes vs R nmath): ~1e-13.
  • R has no Grubbs/ESD in base or recommended packages, so codesplashr has its own, checked against outliers::grubbs.test (type 10) and EnvStats::rosnerTest. Grubbs' p is the two-sided Bonferroni bound capped at 1. Where that bound reaches 1, outliers::grubbs.test reports a smaller value (0.855 on the by-site fixture).
  • Dixon and Tietjen–Moore p-values are Monte-Carlo on the shared Wichmann–Hill stream (identical draws in both engines; counts compared with a 64-ulp tolerance). The two-sided null replays the whole selection rule (the end farther from the mean); a one-sided null tests the chosen end (a lower-tail null uses the high end of the same draws, which has the same distribution). Both are exact up to simulation error; outliers::dixon.test interpolates Dixon's tables instead (Q itself agrees: 0.69231 on the guide's example). The null was checked against Rorabacher (1991): critical r10 values 0.412 / 0.466 / 0.568 for n = 10 give 0.100 / 0.050 / 0.010.
Python

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

# Outliers (univariate)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method outliers.univariate 2.0.1 · spec 7fa75b43dd4df169
# Dataset: s1_outliers (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 outliers as cso

# %% Data
df = pd.read_parquet("tests/parity/fixtures/s1_outliers.parquet", columns=["reading", "id"])
n_input = len(df)
df["id"] = pd.Categorical(df["id"], categories=["r01", "r02", "r03", "r04", "r05", "r06", "r07", "r08", "r09", "r10", "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", "r30"])  # stored level order
df = df.dropna(subset=["reading", "id"])  # listwise deletion over the analysis columns
df["id"] = df["id"].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, ["reading", "id"])  # infinite values stop the run (registry/errors.yaml)

# %% Rules
y = "reading"
label = "id" or None
group = "" or None
x_all = df[y].to_numpy(dtype=float)
rows_all = (df.index.to_numpy() + 1).astype(int)  # 1-based row numbers in the input
n = x_all.size
tukey_k = 1.5
z_cut = 3
modz_cut = 3.5
alpha = 0.05
gesd_k = int(3)
side = "two_sided"  # two_sided, upper or lower (prespecified)
dixon_type = "auto"
tm_k = int(2)
reps = int(9999)
seed = int(1)


def screen(x, rows_in, idx):
    """Every rule on one sample; positions in the result index ``x`` (``idx`` maps them to ``df`` rows)."""
    n = x.size
    lo, hi = cso.tukey_fences(x, tukey_k)
    olo, ohi = cso.tukey_fences(x, 3.0)
    flag_tukey = (x < lo) | (x > hi)
    z = cso.zscores(x)
    z_enabled = n > 10  # with n ≤ 10, |z| can never exceed (n − 1)/√n
    flag_z = (np.abs(z) > z_cut) if z_enabled else np.zeros(n, bool)
    mz = cso.modified_z(x)
    flag_modz = np.abs(mz) > modz_cut
    gr = cso.grubbs(x, side)
    flag_grubbs = np.zeros(n, bool)
    grubbs_row = None
    if np.isfinite(gr["p"]) and gr["p"] < alpha:
        pos = int(np.argmin(x)) if gr["side"] == "lowest" else int(np.argmax(x))
        flag_grubbs[pos] = True
        grubbs_row = int(rows_in[pos])
    ge = cso.gesd(x, gesd_k, alpha)
    flag_gesd = np.zeros(n, bool)
    for st in ge["steps"]:
        if st["outlier"]:
            flag_gesd[st["row"]] = True
    dx = cso.dixon(x, dixon_type, side, reps, seed)
    flag_dixon = np.zeros(n, bool)
    if np.isfinite(dx["p"]) and dx["p"] < alpha:
        flag_dixon[int(np.argmin(x)) if dx["side"] == "lowest" else int(np.argmax(x))] = True
    tm = cso.tietjen_moore(x, tm_k, side, reps, seed)
    flag_tm = np.zeros(n, bool)
    if np.isfinite(tm["p"]) and tm["p"] < alpha:
        flag_tm[tm["rows"]] = True
    count = flag_tukey.astype(int) + flag_z.astype(int) + flag_modz.astype(int) + flag_gesd.astype(int)
    any_flag = (count > 0) | flag_grubbs | flag_dixon | flag_tm
    return {"n": n, "x": x, "rows_in": rows_in, "idx": idx, "lo": lo, "hi": hi, "olo": olo, "ohi": ohi, "z": z, "z_enabled": z_enabled,
            "mz": mz, "gr": gr, "grubbs_row": grubbs_row, "ge": ge, "dx": dx, "tm": tm, "count": count, "any": any_flag,
            "flags": {"tukey": flag_tukey, "z_rule": flag_z, "modz_rule": flag_modz, "grubbs": flag_grubbs, "gesd": flag_gesd,
                      "dixon": flag_dixon, "tm": flag_tm}}


def num(v):
    return None if v is None or not np.isfinite(v) else float(v)


if not group and n < 3:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="Outlier screening", min=3, n=n)
if n >= 1 and np.ptp(x_all) == 0:  # no variation: SD and MAD are 0, so no rule can flag anything
    cs.cs_error("CS_E_CONSTANT", column=y)
if group:
    levels = [str(lv) for lv in df[group].cat.categories]
    g_all = df[group].astype(str).to_numpy()
    samples = []
    for lv in levels:
        m = g_all == lv
        if m.sum() < 3:
            warnings.append(f"{group} = {lv} has fewer than 3 values and was not screened.")
            continue
        samples.append((lv, screen(x_all[m], rows_all[m], np.flatnonzero(m))))
    if not samples:
        cs.cs_error("CS_E_UNDEFINED", what="Outlier screening", reason=f"no group of {group} has at least 3 values")
else:
    samples = [(None, screen(x_all, rows_all, np.arange(n)))]

# %% Result
flagged = []
for lv, s in samples:
    for i in np.flatnonzero(s["any"]):
        flagged.append({
            "row": int(s["rows_in"][i]), **({"group": lv} if group else {}),
            **({"label": str(df[label].iloc[int(s["idx"][i])])} if label else {}),
            "value": float(s["x"][i]), "z": num(s["z"][i]), "modz": float(s["mz"][i]),
            **{k: bool(f[i]) for k, f in s["flags"].items()}, "rules": int(s["count"][i]),
        })
flagged.sort(key=lambda r: (-r["rules"], r["row"]))
any_rows = sorted(int(r) for _, s in samples for r in s["rows_in"][s["any"]])
n_any = sum(int(s["any"].sum()) for _, s in samples)
n_cons = sum(int((s["count"] >= 2).sum()) for _, s in samples)
values = {"n": n, "mean": float(x_all.mean()), "sd": float(x_all.std(ddof=1)), "median": float(np.median(x_all)),
          "n_flagged_any": n_any, "n_consensus": n_cons, "flagged_rows": any_rows, "n_groups": len(samples) if group else 0,
          "mc_reps": reps, "tm_k": tm_k}
single_keys = ["tukey_low", "tukey_high", "outer_low", "outer_high", "n_tukey", "n_tukey_outer", "n_z", "z_enabled", "max_abs_z",
               "n_modz", "max_abs_modz", "grubbs_g", "grubbs_p", "grubbs_value", "grubbs_side", "grubbs_row", "gesd_n",
               "dixon_type", "dixon_q", "dixon_p", "dixon_value", "dixon_side", "tm_e", "tm_p", "tm_side"]
tables = []
if not group:
    s = samples[0][1]
    x, gr, ge, dx, tm, f = s["x"], s["gr"], s["ge"], s["dx"], s["tm"], s["flags"]
    values.update({
        "tukey_low": s["lo"], "tukey_high": s["hi"], "outer_low": s["olo"], "outer_high": s["ohi"],
        "n_tukey": int(f["tukey"].sum()), "n_tukey_outer": int(((x < s["olo"]) | (x > s["ohi"])).sum()),
        "n_z": int(f["z_rule"].sum()), "z_enabled": bool(s["z_enabled"]),
        "max_abs_z": float(np.nanmax(np.abs(s["z"]))) if s["z_enabled"] else None,
        "n_modz": int(f["modz_rule"].sum()), "max_abs_modz": float(np.max(np.abs(s["mz"]))),
        "grubbs_g": gr["g"], "grubbs_p": gr["p"], "grubbs_value": gr["value"], "grubbs_side": gr["side"], "grubbs_row": s["grubbs_row"],
        "gesd_n": int(ge["n_outliers"]),
        "dixon_type": dx["type"] if np.isfinite(dx["q"]) else None, "dixon_q": num(dx["q"]), "dixon_p": num(dx["p"]), "dixon_value": num(dx["value"]),
        "dixon_side": dx["side"] or None, "tm_e": num(tm["e"]), "tm_p": num(tm["p"]), "tm_side": tm["side"] or None,
    })
    for st in ge["steps"]:
        values[f"gesd_r[{st['i']}]"] = st["r"]
        values[f"gesd_lambda[{st['i']}]"] = st["lambda"]
        values[f"gesd_value[{st['i']}]"] = st["value"]
    dixon_crit = (f"{dx['type']}: Q = {dx['q']:.4g}, p = {dx['p']:.4g} ({dx['side']} value)" if np.isfinite(dx["q"])
                  else "not used: Dixon's ratios cover 3–30 values")
    tm_crit = (f"k = {tm_k}: E = {tm['e']:.4g}, p = {tm['p']:.4g}" if np.isfinite(tm["e"]) else f"not used: needs more than {tm_k + 1} values")
    methods = [
        {"method": f"Tukey fences (k = {tukey_k:g})", "criterion": f"outside [{s['lo']:.4g}, {s['hi']:.4g}]", "flagged": int(f["tukey"].sum())},
        {"method": f"z-score (|z| > {z_cut:g})", "criterion": "SD with n − 1" if s["z_enabled"] else "not used: n ≤ 10", "flagged": int(f["z_rule"].sum())},
        {"method": f"Modified z (|M| > {modz_cut:g})", "criterion": "median and MAD (Iglewicz & Hoaglin)", "flagged": int(f["modz_rule"].sum())},
        {"method": "Grubbs' test", "criterion": f"G = {gr['g']:.3f}, p = {gr['p']:.4g}", "flagged": int(f["grubbs"].sum())},
        {"method": f"Generalized ESD (up to {gesd_k})", "criterion": f"α = {alpha:g}", "flagged": int(f["gesd"].sum())},
        {"method": "Dixon's Q test", "criterion": dixon_crit, "flagged": int(f["dixon"].sum())},
        {"method": f"Tietjen–Moore (k = {tm_k})", "criterion": tm_crit, "flagged": int(f["tm"].sum())},
    ]
    tables.append({"key": "rules", "title": "Rules", "columns": [{"key": "method", "label": "Rule", "type": "string"},
                   {"key": "criterion", "label": "Criterion", "type": "string"}, {"key": "flagged", "label": "Flagged", "type": "integer"}],
                   "rows": methods})
else:
    for k in single_keys:
        values[k] = None
    grows = []
    for lv, s in samples:
        values[f"n[{lv}]"] = int(s["n"])
        values[f"n_flagged[{lv}]"] = int(s["any"].sum())
        values[f"tukey_low[{lv}]"] = s["lo"]
        values[f"tukey_high[{lv}]"] = s["hi"]
        values[f"grubbs_p[{lv}]"] = num(s["gr"]["p"])
        values[f"dixon_p[{lv}]"] = num(s["dx"]["p"])
        values[f"tm_p[{lv}]"] = num(s["tm"]["p"])
        grows.append({"group": lv, "n": int(s["n"]), "flagged": int(s["any"].sum()), "tukey_low": s["lo"], "tukey_high": s["hi"],
                      "grubbs_p": num(s["gr"]["p"]), "gesd_n": int(s["ge"]["n_outliers"]), "dixon_p": num(s["dx"]["p"]), "tm_p": num(s["tm"]["p"])})
    tables.append({"key": "groups", "title": f"Rules within each {group}", "columns": [
        {"key": "group", "label": group, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
        {"key": "flagged", "label": "Flagged", "type": "integer"}, {"key": "tukey_low", "label": "Lower fence", "type": "number"},
        {"key": "tukey_high", "label": "Upper fence", "type": "number"}, {"key": "grubbs_p", "label": "Grubbs p", "type": "p"},
        {"key": "gesd_n", "label": "ESD outliers", "type": "integer"}, {"key": "dixon_p", "label": "Dixon p", "type": "p"},
        {"key": "tm_p", "label": "Tietjen–Moore p", "type": "p"}], "rows": grows})
flag_cols = ([{"key": "row", "label": "Row", "type": "integer"}] + ([{"key": "group", "label": group, "type": "string"}] if group else [])
             + ([{"key": "label", "label": label, "type": "string"}] if label else []) + [
    {"key": "value", "label": y, "type": "number"}, {"key": "z", "label": "z", "type": "number"}, {"key": "modz", "label": "Modified z", "type": "number"},
    {"key": "tukey", "label": "Tukey", "type": "string"}, {"key": "z_rule", "label": "z rule", "type": "string"},
    {"key": "modz_rule", "label": "Mod. z", "type": "string"}, {"key": "grubbs", "label": "Grubbs", "type": "string"},
    {"key": "gesd", "label": "ESD", "type": "string"}, {"key": "dixon", "label": "Dixon", "type": "string"},
    {"key": "tm", "label": "T–M", "type": "string"}, {"key": "rules", "label": "Rules", "type": "integer"},
])
tables.append({"key": "flagged", "title": "Flagged values", "columns": flag_cols, "rows": flagged})
if not group:
    s = samples[0][1]
    tables.append({"key": "gesd", "title": "Generalized ESD steps",
                   "columns": [{"key": "i", "label": "i", "type": "integer"}, {"key": "value", "label": "Value", "type": "number"},
                               {"key": "r", "label": "R", "type": "number"}, {"key": "lambda", "label": "λ (critical)", "type": "number"},
                               {"key": "outlier", "label": "Outlier", "type": "string"}],
                   "rows": [{**st, "row": int(s["rows_in"][st["row"]])} for st in s["ge"]["steps"]]})
any_mask = np.zeros(n, bool)
for _, s in samples:
    any_mask[s["idx"][s["any"]]] = True
chart_rows = np.unique(np.round(np.linspace(0, n - 1, min(n, 5000))).astype(int))
status = np.where(any_mask, "Flagged", "Not flagged")
small_n = (not group) and not samples[0][1]["z_enabled"]
gr0 = samples[0][1]["gr"]
cs.publish({
    "method": "outliers.univariate",
    "methodVersion": "2.0.1",
    "title": "Outliers",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": f"{y}: {n_any} of {n} values flagged by at least one rule, {n_cons} by two or more"
    + (f" (each {group} screened on its own)." if group else "."),
    "apa": "" if group else f"Grubbs' G = {cs.fmt_num(gr0['g'])}, {cs.fmt_p(gr0['p'])}",
    "statistics": [{"key": "n_flagged_any", "label": "Flagged (any rule)", "value": n_any},
                   {"key": "n_consensus", "label": "Flagged by ≥ 2 rules", "value": n_cons}]
    + ([] if group else [{"key": "grubbs_p", "label": "Grubbs p", "value": gr0["p"], "format": "p"},
                         {"key": "dixon_p", "label": "Dixon p", "value": values["dixon_p"], "format": "p"}]),
    "tables": tables,
    "effectSizes": [],
    "assumptions": [],
    "warnings": warnings + (["With 10 or fewer values the z rule cannot flag anything; it is not used."] if small_n else []),
    "notes": ["Flag, investigate, decide: correct entry errors, set impossible values to missing, keep genuine values. "
              "Never delete automatically; compare results with and without flagged values (sensitivity analysis).",
              "Grubbs, the generalized ESD, Dixon and Tietjen–Moore assume the remaining values are normal. Dixon's ratios suit 3–30 values; "
              "Tietjen–Moore tests exactly k values chosen before looking at the data.",
              f"Dixon and Tietjen–Moore p-values are Monte-Carlo ({reps:,} normal samples, seed {seed}); they match in Python and R."],
    "charts": [cs.chart("values", "strip", f"{y}: flagged vs not flagged", {
        "y": cs.col(y, x_all[chart_rows]), "group": cs.col("Status", status[chart_rows], levels=["Not flagged", "Flagged"])},
        controls={"interval": "none"})],
    "values": values,
})
R

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

# Outliers (univariate)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method outliers.univariate 2.0.1 · spec 7fa75b43dd4df169
# Dataset: s1_outliers (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/s1_outliers.parquet", col_select = c("reading", "id")))
n_input <- nrow(df)
df[["id"]] <- factor(df[["id"]], levels = c("r01", "r02", "r03", "r04", "r05", "r06", "r07", "r08", "r09", "r10", "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", "r30"))  # stored level order
df <- df[stats::complete.cases(df[c("reading", "id")]), , 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("reading", "id"))  # infinite values stop the run (registry/errors.yaml)

# %% Rules
y <- "reading"
label <- "id"
if (!nzchar(label)) label <- NULL
group <- ""
if (!nzchar(group)) group <- NULL
x_all <- as.numeric(df[[y]])
rows_all <- as.integer(rownames(df))  # 1-based row numbers in the input
n <- length(x_all)
tukey_k <- 1.5
z_cut <- 3
modz_cut <- 3.5
alpha <- 0.05
gesd_k <- as.integer(3)
side <- "two_sided"  # two_sided, upper or lower (prespecified)
dixon_type <- "auto"
tm_k <- as.integer(2)
reps <- as.integer(9999)
seed <- as.integer(1)

num_or_null <- function(v) if (is.null(v) || length(v) == 0 || !is.finite(v)) NULL else v

# Every rule on one sample; `idx` maps positions in x to rows of df.
screen <- function(x, rows_in, idx) {
  n <- length(x)
  fences <- cs_tukey_fences(x, tukey_k)
  outer <- cs_tukey_fences(x, 3)
  flag_tukey <- x < fences[1] | x > fences[2]
  z <- cs_zscores(x)
  z_enabled <- n > 10  # with n <= 10, |z| can never exceed (n - 1) / sqrt(n)
  flag_z <- if (z_enabled) abs(z) > z_cut else rep(FALSE, n)
  mz <- cs_modified_z(x)
  flag_modz <- abs(mz) > modz_cut
  gr <- cs_grubbs(x, side)
  flag_grubbs <- rep(FALSE, n)
  grubbs_row <- NULL
  if (is.finite(gr$p) && gr$p < alpha) {
    pos <- if (gr$side == "lowest") which.min(x) else which.max(x)
    flag_grubbs[pos] <- TRUE
    grubbs_row <- rows_in[pos]
  }
  ge <- cs_gesd(x, gesd_k, alpha)
  flag_gesd <- rep(FALSE, n)
  if (nrow(ge$steps)) flag_gesd[ge$steps$row[ge$steps$outlier]] <- TRUE
  dx <- cs_dixon(x, dixon_type, side, reps, seed)
  flag_dixon <- rep(FALSE, n)
  if (is.finite(dx$p) && dx$p < alpha) flag_dixon[if (dx$side == "lowest") which.min(x) else which.max(x)] <- TRUE
  tm <- cs_tietjen_moore(x, tm_k, side, reps, seed)
  flag_tm <- rep(FALSE, n)
  if (is.finite(tm$p) && tm$p < alpha) flag_tm[tm$rows] <- TRUE
  count <- flag_tukey + flag_z + flag_modz + flag_gesd
  any_flag <- count > 0 | flag_grubbs | flag_dixon | flag_tm
  list(n = n, x = x, rows_in = rows_in, idx = idx, fences = fences, outer = outer, z = z, z_enabled = z_enabled, mz = mz,
       gr = gr, grubbs_row = grubbs_row, ge = ge, dx = dx, tm = tm, count = count, any = any_flag,
       flags = list(tukey = flag_tukey, z_rule = flag_z, modz_rule = flag_modz, grubbs = flag_grubbs, gesd = flag_gesd,
                    dixon = flag_dixon, tm = flag_tm))
}

if (is.null(group) && n < 3) cs_error("CS_E_TOO_FEW_ROWS", what = "Outlier screening", min = 3, n = n)
if (n >= 1 && diff(range(x_all)) == 0) cs_error("CS_E_CONSTANT", column = y)  # no variation: SD and MAD are 0
if (!is.null(group)) {
  levels_g <- levels(df[[group]])
  g_all <- as.character(df[[group]])
  samples <- list()
  for (lv in levels_g) {
    m <- g_all == lv
    if (sum(m) < 3) {
      warnings <- c(warnings, sprintf("%s = %s has fewer than 3 values and was not screened.", group, lv))
      next
    }
    samples[[length(samples) + 1]] <- list(level = lv, s = screen(x_all[m], rows_all[m], which(m)))
  }
  if (!length(samples)) cs_error("CS_E_UNDEFINED", what = "Outlier screening", reason = sprintf("no group of %s has at least 3 values", group))
} else {
  samples <- list(list(level = NULL, s = screen(x_all, rows_all, seq_len(n))))
}

# %% Result
flagged <- list()
for (smp in samples) {
  s <- smp$s
  for (i in which(s$any)) {
    flagged[[length(flagged) + 1]] <- c(
      list(row = s$rows_in[i]), if (!is.null(group)) list(group = smp$level),
      if (!is.null(label)) list(label = as.character(df[[label]][s$idx[i]])),
      list(value = s$x[i], z = num_or_null(s$z[i]), modz = s$mz[i]),
      lapply(s$flags, function(f) f[i]), list(rules = s$count[i]))
  }
}
if (length(flagged)) {
  o <- order(-vapply(flagged, function(r) r$rules, numeric(1)), vapply(flagged, function(r) r$row, numeric(1)))
  flagged <- flagged[o]
}
any_rows <- sort(unlist(lapply(samples, function(smp) smp$s$rows_in[smp$s$any])))
n_any <- sum(vapply(samples, function(smp) sum(smp$s$any), numeric(1)))
n_cons <- sum(vapply(samples, function(smp) sum(smp$s$count >= 2), numeric(1)))
values <- list(n = n, mean = mean(x_all), sd = stats::sd(x_all), median = stats::median(x_all),
               n_flagged_any = n_any, n_consensus = n_cons, flagged_rows = I(as.integer(any_rows)),
               n_groups = if (is.null(group)) 0L else length(samples), mc_reps = reps, tm_k = tm_k)
single_keys <- c("tukey_low", "tukey_high", "outer_low", "outer_high", "n_tukey", "n_tukey_outer", "n_z", "z_enabled", "max_abs_z",
                 "n_modz", "max_abs_modz", "grubbs_g", "grubbs_p", "grubbs_value", "grubbs_side", "grubbs_row", "gesd_n",
                 "dixon_type", "dixon_q", "dixon_p", "dixon_value", "dixon_side", "tm_e", "tm_p", "tm_side")
tables <- list()
if (is.null(group)) {
  s <- samples[[1]]$s
  x <- s$x; gr <- s$gr; ge <- s$ge; dx <- s$dx; tm <- s$tm; f <- s$flags
  values$tukey_low <- s$fences[1]
  values$tukey_high <- s$fences[2]
  values$outer_low <- s$outer[1]
  values$outer_high <- s$outer[2]
  values$n_tukey <- sum(f$tukey)
  values$n_tukey_outer <- sum(x < s$outer[1] | x > s$outer[2])
  values$n_z <- sum(f$z_rule)
  values$z_enabled <- s$z_enabled
  values["max_abs_z"] <- list(if (s$z_enabled) max(abs(s$z), na.rm = TRUE) else NULL)
  values$n_modz <- sum(f$modz_rule)
  values$max_abs_modz <- max(abs(s$mz))
  values$grubbs_g <- gr$g
  values$grubbs_p <- gr$p
  values$grubbs_value <- gr$value
  values$grubbs_side <- gr$side
  values["grubbs_row"] <- list(s$grubbs_row)
  values$gesd_n <- ge$n_outliers
  values["dixon_type"] <- list(if (is.finite(dx$q)) dx$type else NULL)
  values["dixon_q"] <- list(num_or_null(dx$q))
  values["dixon_p"] <- list(num_or_null(dx$p))
  values["dixon_value"] <- list(num_or_null(dx$value))
  values["dixon_side"] <- list(if (nzchar(dx$side)) dx$side else NULL)
  values["tm_e"] <- list(num_or_null(tm$e))
  values["tm_p"] <- list(num_or_null(tm$p))
  values["tm_side"] <- list(if (nzchar(tm$side)) tm$side else NULL)
  for (j in seq_len(nrow(ge$steps))) {
    values[[sprintf("gesd_r[%d]", ge$steps$i[j])]] <- ge$steps$r[j]
    values[[sprintf("gesd_lambda[%d]", ge$steps$i[j])]] <- ge$steps$lambda[j]
    values[[sprintf("gesd_value[%d]", ge$steps$i[j])]] <- ge$steps$value[j]
  }
  dixon_crit <- if (is.finite(dx$q)) sprintf("%s: Q = %.4g, p = %.4g (%s value)", dx$type, dx$q, dx$p, dx$side) else "not used: Dixon's ratios cover 3–30 values"
  tm_crit <- if (is.finite(tm$e)) sprintf("k = %d: E = %.4g, p = %.4g", tm_k, tm$e, tm$p) else sprintf("not used: needs more than %d values", tm_k + 1)
  methods <- list(
    list(method = sprintf("Tukey fences (k = %s)", format(tukey_k)), criterion = sprintf("outside [%.4g, %.4g]", s$fences[1], s$fences[2]), flagged = sum(f$tukey)),
    list(method = sprintf("z-score (|z| > %s)", format(z_cut)), criterion = if (s$z_enabled) "SD with n − 1" else "not used: n ≤ 10", flagged = sum(f$z_rule)),
    list(method = sprintf("Modified z (|M| > %s)", format(modz_cut)), criterion = "median and MAD (Iglewicz & Hoaglin)", flagged = sum(f$modz_rule)),
    list(method = "Grubbs' test", criterion = sprintf("G = %.3f, p = %.4g", gr$g, gr$p), flagged = sum(f$grubbs)),
    list(method = sprintf("Generalized ESD (up to %d)", gesd_k), criterion = sprintf("α = %s", format(alpha)), flagged = sum(f$gesd)),
    list(method = "Dixon's Q test", criterion = dixon_crit, flagged = sum(f$dixon)),
    list(method = sprintf("Tietjen–Moore (k = %d)", tm_k), criterion = tm_crit, flagged = sum(f$tm))
  )
  tables[[length(tables) + 1]] <- list(key = "rules", title = "Rules", columns = list(
    list(key = "method", label = "Rule", type = "string"), list(key = "criterion", label = "Criterion", type = "string"),
    list(key = "flagged", label = "Flagged", type = "integer")), rows = methods)
} else {
  for (k in single_keys) values[k] <- list(NULL)
  grows <- list()
  for (smp in samples) {
    lv <- smp$level
    s <- smp$s
    values[[sprintf("n[%s]", lv)]] <- s$n
    values[[sprintf("n_flagged[%s]", lv)]] <- sum(s$any)
    values[[sprintf("tukey_low[%s]", lv)]] <- s$fences[1]
    values[[sprintf("tukey_high[%s]", lv)]] <- s$fences[2]
    values[sprintf("grubbs_p[%s]", lv)] <- list(num_or_null(s$gr$p))
    values[sprintf("dixon_p[%s]", lv)] <- list(num_or_null(s$dx$p))
    values[sprintf("tm_p[%s]", lv)] <- list(num_or_null(s$tm$p))
    grows[[length(grows) + 1]] <- list(group = lv, n = s$n, flagged = sum(s$any), tukey_low = s$fences[1], tukey_high = s$fences[2],
                                       grubbs_p = num_or_null(s$gr$p), gesd_n = s$ge$n_outliers, dixon_p = num_or_null(s$dx$p),
                                       tm_p = num_or_null(s$tm$p))
  }
  tables[[length(tables) + 1]] <- list(key = "groups", title = sprintf("Rules within each %s", group), columns = list(
    list(key = "group", label = group, type = "string"), list(key = "n", label = "n", type = "integer"),
    list(key = "flagged", label = "Flagged", type = "integer"), list(key = "tukey_low", label = "Lower fence", type = "number"),
    list(key = "tukey_high", label = "Upper fence", type = "number"), list(key = "grubbs_p", label = "Grubbs p", type = "p"),
    list(key = "gesd_n", label = "ESD outliers", type = "integer"), list(key = "dixon_p", label = "Dixon p", type = "p"),
    list(key = "tm_p", label = "Tietjen–Moore p", type = "p")), rows = grows)
}
flag_cols <- c(list(list(key = "row", label = "Row", type = "integer")),
               if (!is.null(group)) list(list(key = "group", label = group, type = "string")),
               if (!is.null(label)) list(list(key = "label", label = label, type = "string")),
               list(list(key = "value", label = y, type = "number"), list(key = "z", label = "z", type = "number"),
                    list(key = "modz", label = "Modified z", type = "number"), list(key = "tukey", label = "Tukey", type = "string"),
                    list(key = "z_rule", label = "z rule", type = "string"), list(key = "modz_rule", label = "Mod. z", type = "string"),
                    list(key = "grubbs", label = "Grubbs", type = "string"), list(key = "gesd", label = "ESD", type = "string"),
                    list(key = "dixon", label = "Dixon", type = "string"), list(key = "tm", label = "T–M", type = "string"),
                    list(key = "rules", label = "Rules", type = "integer")))
tables[[length(tables) + 1]] <- list(key = "flagged", title = "Flagged values", columns = flag_cols, rows = flagged)
if (is.null(group)) {
  s <- samples[[1]]$s
  gesd_rows <- if (nrow(s$ge$steps)) {
    steps <- s$ge$steps
    steps$row <- s$rows_in[steps$row]
    steps
  } else list()
  tables[[length(tables) + 1]] <- list(key = "gesd", title = "Generalized ESD steps",
    columns = list(list(key = "i", label = "i", type = "integer"), list(key = "value", label = "Value", type = "number"),
                   list(key = "r", label = "R", type = "number"), list(key = "lambda", label = "λ (critical)", type = "number"),
                   list(key = "outlier", label = "Outlier", type = "string")),
    rows = gesd_rows)
}
any_mask <- rep(FALSE, n)
for (smp in samples) any_mask[smp$s$idx[smp$s$any]] <- TRUE
chart_rows <- unique(round(seq(1, n, length.out = min(n, 5000))))
status <- ifelse(any_mask, "Flagged", "Not flagged")
small_n <- is.null(group) && !samples[[1]]$s$z_enabled
gr0 <- samples[[1]]$s$gr
cs_publish(list(
  method = "outliers.univariate",
  methodVersion = "2.0.1",
  title = "Outliers",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = paste0(sprintf("%s: %d of %d values flagged by at least one rule, %d by two or more", y, n_any, n, n_cons),
                   if (!is.null(group)) sprintf(" (each %s screened on its own).", group) else "."),
  apa = if (!is.null(group)) "" else sprintf("Grubbs' G = %s, %s", cs_fmt_num(gr0$g), cs_fmt_p(gr0$p)),
  statistics = c(list(list(key = "n_flagged_any", label = "Flagged (any rule)", value = n_any),
                      list(key = "n_consensus", label = "Flagged by ≥ 2 rules", value = n_cons)),
                 if (is.null(group)) list(list(key = "grubbs_p", label = "Grubbs p", value = gr0$p, format = "p"),
                                          list(key = "dixon_p", label = "Dixon p", value = values$dixon_p, format = "p"))),
  tables = tables,
  effectSizes = list(),
  assumptions = list(),
  warnings = c(warnings, if (small_n) list("With 10 or fewer values the z rule cannot flag anything; it is not used.")),
  notes = list(paste("Flag, investigate, decide: correct entry errors, set impossible values to missing, keep genuine values.",
                     "Never delete automatically; compare results with and without flagged values (sensitivity analysis)."),
               paste("Grubbs, the generalized ESD, Dixon and Tietjen–Moore assume the remaining values are normal. Dixon's ratios suit 3–30 values;",
                     "Tietjen–Moore tests exactly k values chosen before looking at the data."),
               sprintf("Dixon and Tietjen–Moore p-values are Monte-Carlo (%s normal samples, seed %d); they match in Python and R.",
                       format(reps, big.mark = ","), seed)),
  charts = list(cs_chart("values", "strip", sprintf("%s: flagged vs not flagged", y), list(
    y = cs_col(y, x_all[chart_rows]), group = cs_col("Status", status[chart_rows], levels = c("Not flagged", "Flagged"))),
    controls = list(interval = "none"))),
  values = values
))

Sources

  • Tukey, J. W. (1977). Exploratory data analysis.
  • Iglewicz, B., & Hoaglin, D. C. (1993). How to detect and handle outliers. ASQC Quality Press.
  • Grubbs, F. E. (1969). Procedures for detecting outlying observations in samples. Technometrics, 11, 1–21.
  • Rosner, B. (1983). Percentage points for a generalized ESD many-outlier procedure. Technometrics, 25, 165–172.
  • Dixon, W. J. (1950). Analysis of extreme values. Annals of Mathematical Statistics, 21, 488–506; (1953) Processing data for outliers. Biometrics, 9, 74–89.
  • Rorabacher, D. B. (1991). Statistical treatment for rejection of deviant values: critical values of Dixon's Q parameter. Analytical Chemistry, 63, 139–146.
  • Tietjen, G. L., & Moore, R. H. (1972). Some Grubbs-type statistics for the detection of several outliers. Technometrics, 14, 583–597.

From the CodeSplash method registry · outliers.univariate v2.0.1.