ADescribe · variance.levene
Equal spread tests
Do two or more groups have the same spread?
Tests whether groups share the same variance or scale: robust ANOVA on absolute deviations (Brown–Forsythe, Levene, trimmed mean), normal-theory tests (F ratio, Bartlett, Hartley F-max, Cochran's C) and rank scale tests (Fligner–Killeen, Conover, Ansari–Bradley, Mood, Siegel–Tukey, Klotz), with group SDs and the largest/smallest SD ratio.
A real result
Example “Brown forsythe”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
F(2, 27) = 1.12, p = .341
- F
- 1.119
- df1
- 2
- df2
- 27
- p
- .341
Effect size
- SD ratio (largest / smallest) 1.793
Plots
View data
| group | weight |
|---|---|
| ctrl | 4.170 |
| ctrl | 5.580 |
| ctrl | 5.180 |
| ctrl | 6.110 |
| ctrl | 4.500 |
| ctrl | 4.610 |
| ctrl | 5.170 |
| ctrl | 4.530 |
| ctrl | 5.330 |
| ctrl | 5.140 |
| trt1 | 4.810 |
| trt1 | 4.170 |
| trt1 | 4.410 |
| trt1 | 3.590 |
| trt1 | 5.870 |
| trt1 | 3.830 |
| trt1 | 6.030 |
| trt1 | 4.890 |
| trt1 | 4.320 |
| trt1 | 4.690 |
| trt2 | 6.310 |
| trt2 | 5.120 |
| trt2 | 5.540 |
| trt2 | 5.500 |
| trt2 | 5.370 |
| trt2 | 5.290 |
| trt2 | 4.920 |
| trt2 | 6.150 |
| trt2 | 5.800 |
| trt2 | 5.260 |
Assumptions
- Normality within groups — Not required: the Brown–Forsythe test does not assume normal groups.
Spread by group
| group | n | Median | SD | Variance |
|---|---|---|---|---|
| ctrl | 10 | 5.155 | 0.5831 | 0.3400 |
| trt1 | 10 | 4.550 | 0.7937 | 0.6299 |
| trt2 | 10 | 5.435 | 0.4426 | 0.1959 |
- Brown–Forsythe test: one-way ANOVA on absolute deviations from each group's median.
F(2, 27) = 1.12, p = .341
- F
- 1.119
- df1
- 2
- df2
- 27
- p
- .341
Effect size
- SD ratio (largest / smallest) 1.793
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Normality within groups — Not required: the Brown–Forsythe test does not assume normal groups.
Spread by group
| group | n | Median | SD | Variance |
|---|---|---|---|---|
| ctrl | 10 | 5.155 | 0.5831 | 0.3400 |
| trt1 | 10 | 4.550 | 0.7937 | 0.6299 |
| trt2 | 10 | 5.435 | 0.4426 | 0.1959 |
- Brown–Forsythe test: one-way ANOVA on absolute deviations from each group's median.
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
- Brown forsytheplantgrowth · group: group · outcome: weight
- Levene meanchickwts · group: feed · outcome: weight
- Two groupstoothgrowth · group: supp · outcome: len
- Levene guidec3_rank3 · group: group · outcome: value
- Trimmedchickwts · group: feed · outcome: weight
- F two variancesc3_scale2 · group: group · outcome: value
- F one sided ratiotoothgrowth · group: supp · outcome: len
- Bartlett guidec3_rank3 · group: group · outcome: value
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Assess variance: Levene, Brown–Forsythe · Statistics Guide · A — Describe data
- Equal variance · Statistics Guide · Step 2 — Check assumptions
What you need
- Outcomenumeric · 1 column
- The measurement whose spread is compared across groups.
- Groupscategorical / boolean · 1 column · 2–30 levels
- The grouping column; two-group tests (F ratio and the rank scale tests) need exactly two levels.
Choices you make
statistics
- Testdefault brown_forsythe
Brown–Forsythe is the robust default; normal-theory tests are sharper with normal data but mislead with skewed groups.
- Brown–Forsythe (median-centered Levene)(default) — ANOVA on distances from each group's median; robust to skew and heavy tails. The recommended default.
- Levene's original (mean-centered) — ANOVA on distances from each group's mean; less robust than Brown–Forsythe when groups are skewed.
- Trimmed-mean Levene — Centers each group at its trimmed mean, a compromise between the mean and the median.
- F test for two variances — Ratio of the two sample variances; exact for normal data, badly affected by non-normality.
- Bartlett's test — Likelihood-ratio test of equal variances; powerful for normal groups but sensitive to non-normality.
- Hartley F-max — Largest over smallest group variance; p-value simulated under normality for your group sizes.
- Cochran's C — Largest variance over the sum of variances; flags one group with unusually large variance.
- Fligner–Killeen — Normal scores of ranked distances from group medians; robust and works for many groups.
- Conover squared ranks — Squared ranks of distances from group means; a rank analogue of Levene's test.
- Ansari–Bradley — Two-group rank test of scale; assumes both groups share a median.
- Mood scale test — Squared distances of ranks from the middle; more powerful than Ansari–Bradley for normal-like data.
- Siegel–Tukey — Ranks assigned alternately from both ends, then a Wilcoxon rank-sum test; assumes equal medians.
- Klotz normal scores — Squared normal scores of the ranks; efficient for normal-like data.
- Trim per taildefault 0.1
Share of each group's smallest and largest values left out of its center (0.1 = 10% from each end).
Advanced
- Center (older analyses)default median
Kept so analyses saved before the test list still run; choose the test above instead.
- Median (Brown–Forsythe)(default) — Distances from each group's median.
- Mean (Levene's original) — Distances from each group's mean; same as choosing Levene's original test.
- Variance ratio under the nulldefault 1
The ratio of the first group's variance to the second's that the null hypothesis assumes (usually 1).
hypothesis
- Alternative hypothesisdefault two-sided
Decide the direction before looking at the data; one-sided tests refer to the first group's spread.
- The spreads differ(default) — Either group may be more spread out.
- First group more spread out — One-sided; the first level of the grouping has the larger spread.
- First group less spread out — One-sided; the first level of the grouping has the smaller spread.
- Confidence leveldefault 0.95
Confidence level of the interval for the variance ratio.
options
- p-valuedefault auto
How the rank test's p-value is computed.
- Automatic(default) — Exact for Ansari–Bradley and Siegel–Tukey with no ties and fewer than 50 per group; otherwise asymptotic.
- Asymptotic (normal / chi-square) — Large-sample reference using the exact permutation variance, so ties are handled correctly.
- Exact — Exact null distribution of the score sum; needs no ties.
- Monte Carlo permutation — Shuffles group labels many times; reproducible with the analysis seed.
- Monte Carlo permutationsdefault 9999
More permutations give a steadier p-value.
- Simulated samplesdefault 9999
Normal samples of your group sizes drawn to calibrate the p-value; reproducible with the analysis seed.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Normality within groups
Shapiro–Wilk per group; only the normal-theory tests (F, Bartlett, Hartley, Cochran) need it.
- If violated → Brown–Forsythe test — Compares distances from group medians, so it keeps its error rate with skewed or heavy-tailed groups.
- If violated → Fligner–Killeen test — Uses ranks of distances from group medians, so it does not depend on normality.
Common location
Ansari–Bradley, Mood, Siegel–Tukey and Klotz assume both groups share a median; otherwise a location shift looks like a scale difference.
Independent observations
Each value belongs to one group; for paired measurements use the paired variance test.
What it reports
- test
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- statistic
- One test of "every component null holds" from several independent tests' p-values.
- p
- How surprising your data would be if the null hypothesis were true, as a probability.
- n
- How many independent units the analysis used; it sets precision and power.
- k
- How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
- sd_ratio
- Largest group variance divided by the smallest; a quick check of equal variances.
- sd_max
- The typical distance of values from their mean, in the data's own units.
- sd_min
- The typical distance of values from their mean, in the data's own units.
- sd_max_group
- The group with the largest standard deviation.
- sd_min_group
- The group with the smallest standard deviation.
- method_label
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- stat_symbol
- Symbol of the statistic in the APA line: F for Levene and Brown–Forsythe, others for the alternatives.
Per group, level or term: sd[<group>], n[<group>], df, df1, df2, z, f (F-type tests), var_ratio, ratio_null, ci_low, ci_high (the F test of two variances), n_sim (tests simulated under normality: Hartley, Cochran), calibration (rank tests), max_var_group (Cochran's C and Hartley's F-max), min_var_group (Hartley's F-max)
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
- R has no base Levene function; both engines compute the one-way ANOVA on absolute deviations that car::leveneTest does.
- Mood's test averages the scores of tied values and uses the exact permutation variance, so with ties it equals coin::mood_test(ties.method = 'average-scores'); stats::mood.test approximates the tie correction and coin's default scores mid-ranks (z differs in the third digit). Without ties all agree.
- Hartley's F-max and Cochran's C are calibrated by simulating the normal-theory null for the observed group sizes from the shared Wichmann–Hill stream, so Python and R count the same draws; published Hartley/Cochran tables cover only equal group sizes.
- scipy.stats.ansari uses a different tie-free exact algorithm; the exact p-values here follow R's ansari.test (two-sided: twice the smaller tail from R's center).
The exact script CodeSplash ran for example “Brown forsythe” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Equal spread tests
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method variance.levene 2.0.1 · spec 2a2647217cd9040e
# Dataset: plantgrowth (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import spread
# %% Data
df = pd.read_parquet("tests/parity/fixtures/plantgrowth.parquet", columns=["weight", "group"])
n_input = len(df)
df["group"] = pd.Categorical(df["group"], categories=["ctrl", "trt1", "trt2"]) # stored level order
df = df.dropna(subset=["weight", "group"]) # listwise deletion over the analysis columns
df["group"] = df["group"].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, ["weight", "group"]) # infinite values stop the run (registry/errors.yaml)
# %% Options
y, g = "weight", "group"
test = "brown_forsythe" or "brown_forsythe"
center = "median" or "median"
if test == "brown_forsythe" and center == "mean":
test = "levene" # analyses saved before the test list chose Levene's original through `center`
trim = float(0.1 or 0.1)
alternative = "two-sided" or "two-sided"
ratio = float(1 or 1.0)
conf_level = float(0.95 or 0.95)
calibration = "auto" or "auto"
n_perm = int(9999 or 9999)
n_sim = int(9999 or 9999)
seed = 42 # shared Wichmann–Hill stream: R draws the same permutations / simulated samples
# %% Test
levels = [str(lv) for lv in df[g].cat.categories]
k = len(levels)
if k < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=g, min=2, k=k)
yv = df[y].to_numpy(dtype=float)
if len(np.unique(yv)) < 2: # no variation: every spread statistic is 0/0
cs.cs_error("CS_E_CONSTANT", column=y)
gi = df[g].cat.codes.to_numpy().astype(np.int64)
draws = n_sim if test in spread.SIMULATED else n_perm
res = spread.spread_test(yv, gi, test, trim=trim, ratio=ratio, alternative=alternative, calibration=calibration,
b=draws, seed=seed, conf_level=conf_level)
warnings.extend(res["warnings"])
groups = [yv[gi == j] for j in range(k)]
ns = np.array([len(x) for x in groups])
N = int(ns.sum())
sds = np.array([x.std(ddof=1) for x in groups])
sd_ratio = float(sds.max() / sds.min())
stat, p, symbol, name = float(res["statistic"]), float(res["p"]), res["symbol"], res["label"]
# %% Assumptions
assumptions = []
if test in spread.NORMAL_THEORY:
sw = [(lv, stats.shapiro(x).pvalue) for lv, x in zip(levels, groups) if 3 <= len(x) <= 5000]
bad = [lv for lv, pv in sw if pv < 0.05]
if len(sw) < k:
status, detail = "info", "Too few (or too many) values in a group for Shapiro–Wilk; inspect the distributions."
elif bad:
status, detail = "warn", f"Shapiro–Wilk p < .05 in {', '.join(bad)}; {name} is sensitive to non-normality, so prefer Brown–Forsythe or Fligner–Killeen."
else:
status, detail = "pass", "Shapiro–Wilk p ≥ .05 in every group."
assumptions.append({"key": "normality", "label": "Normality within groups", "status": status, "detail": detail})
else:
assumptions.append({"key": "normality", "label": "Normality within groups", "status": "info",
"detail": f"Not required: the {name} does not assume normal groups."})
if test in ("ansari", "mood", "siegel_tukey", "klotz"):
meds = [float(np.median(x)) for x in groups]
assumptions.append({"key": "common_location", "label": "Common location", "status": "info",
"detail": f"Medians {levels[0]} = {meds[0]:.4g}, {levels[1]} = {meds[1]:.4g}. The test assumes a shared median; center the groups first if they differ in location."})
# %% Result
alpha = 0.05
verdict = (
f"The spreads differ significantly ({cs.fmt_p(p)}); prefer methods that do not assume equal variances (Welch's t-test / ANOVA)." if p < alpha
else f"No evidence that the spreads differ ({cs.fmt_p(p)})."
)
summary = f"Group SDs of {y} range from {sds.min():.2f} to {sds.max():.2f} (largest / smallest = {sd_ratio:.2f}). {name}: {verdict}"
values = {"test": test, "statistic": stat, "stat_symbol": symbol, "p": p, "sd_ratio": sd_ratio, "n": N, "k": k}
for key in ("f", "df1", "df2", "df", "z", "var_ratio", "ratio_null", "ci_low", "ci_high", "n_sim", "n_perm"):
v = res.get(key)
if v is not None and not (isinstance(v, float) and math.isinf(v)):
values[key] = float(v) if isinstance(v, float) else v
if test in spread.RANK_TESTS:
values["calibration"] = res["calibration"]
if test == "cochran_c":
values["max_var_group"] = levels[res["max_var_group"]]
if test == "hartley":
values["max_var_group"] = levels[res["max_var_group"]]
values["min_var_group"] = levels[res["min_var_group"]]
for lv, s, n in zip(levels, sds, ns):
values[f"sd[{lv}]"] = float(s)
values[f"n[{lv}]"] = int(n)
imax, imin = int(np.argmax(sds)), int(np.argmin(sds))
values.update({"sd_max": float(sds[imax]), "sd_min": float(sds[imin]), "sd_max_group": levels[imax], "sd_min_group": levels[imin], "method_label": name})
if "df1" in res:
apa = f"F({res['df1']:g}, {res['df2']:g}) = {cs.fmt_num(stat)}, {cs.fmt_p(p)}"
statistics = [{"key": "f", "label": "F", "value": stat}, {"key": "df1", "label": "df1", "value": res["df1"]},
{"key": "df2", "label": "df2", "value": res["df2"]}]
elif "df" in res:
apa = f"{symbol}({res['df']:g}) = {cs.fmt_num(stat)}, {cs.fmt_p(p)}"
statistics = [{"key": "statistic", "label": symbol, "value": stat}, {"key": "df", "label": "df", "value": res["df"]}]
elif "z" in res:
apa = f"{symbol} = {cs.fmt_num(stat)}, z = {cs.fmt_num(res['z'])}, {cs.fmt_p(p)}"
statistics = [{"key": "statistic", "label": symbol, "value": stat}, {"key": "z", "label": "z", "value": res["z"]}]
else:
apa = f"{symbol} = {cs.fmt_num(stat)}, {cs.fmt_p(p)}"
statistics = [{"key": "statistic", "label": symbol, "value": stat}]
statistics.append({"key": "p", "label": "p", "value": p, "format": "p"})
effects = [{"key": "sd_ratio", "label": "SD ratio (largest / smallest)", "value": sd_ratio, "method": "max SD / min SD"}]
if test == "f":
eff = {"key": "var_ratio", "label": f"Variance ratio ({levels[0]} / {levels[1]})", "value": float(res["var_ratio"]),
"method": "s₁² / s₂²"}
if math.isfinite(res["ci_low"]) and math.isfinite(res["ci_high"]):
eff.update({"ciLow": float(res["ci_low"]), "ciHigh": float(res["ci_high"]), "ciLevel": conf_level})
effects.append(eff)
notes = []
if test in spread.DEVIATION_TESTS:
center_name = {"brown_forsythe": "median", "levene": "mean", "trimmed": f"{trim:g}-trimmed mean"}[test]
notes.append(f"{name}: one-way ANOVA on absolute deviations from each group's {center_name}.")
elif test in spread.SIMULATED:
notes.append(f"{name}: p-value from {res['n_sim']} samples simulated under normality for these group sizes (seed {seed}).")
elif test in spread.RANK_TESTS:
how = {"exact": "the exact null distribution", "asymptotic": "the large-sample reference with the exact permutation variance",
"permutation": f"{n_perm} Monte Carlo permutations (seed {seed})"}[res["calibration"]]
notes.append(f"{name}: p-value from {how}.")
if test in spread.TWO_GROUP and alternative != "two-sided":
notes.append(f"One-sided: the alternative is that {levels[0]} is {'more' if alternative == 'greater' else 'less'} spread out than {levels[1]}.")
chart_rows = np.unique(np.round(np.linspace(0, len(df) - 1, min(len(df), 5000))).astype(int))
charts = [cs.chart("spread", "box-violin", 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=levels),
})]
cs.publish({
"method": "variance.levene",
"methodVersion": "2.0.1",
"title": name,
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": N,
"summary": summary,
"apa": apa,
"statistics": statistics,
"tables": [{
"key": "spread", "title": "Spread by group",
"columns": [{"key": "group", "label": g, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "median", "label": "Median", "type": "number"},
{"key": "sd", "label": "SD", "type": "number"}, {"key": "variance", "label": "Variance", "type": "number"}],
"rows": [{"group": lv, "n": int(n), "median": float(np.median(x)), "sd": float(s), "variance": float(s**2)}
for lv, n, x, s in zip(levels, ns, groups, sds)],
}],
"effectSizes": effects,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"charts": charts,
"values": values,
})
The exact script CodeSplash ran for example “Brown forsythe” · R version 4.5.1 (2025-06-13)
# Equal spread tests
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method variance.levene 2.0.1 · spec 2a2647217cd9040e
# Dataset: plantgrowth (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/plantgrowth.parquet", col_select = c("weight", "group")))
n_input <- nrow(df)
df[["group"]] <- factor(df[["group"]], levels = c("ctrl", "trt1", "trt2")) # stored level order
df <- df[stats::complete.cases(df[c("weight", "group")]), , 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("weight", "group")) # infinite values stop the run (registry/errors.yaml)
# %% Options
y <- "weight"
g <- "group"
`%||%` <- function(a, b) if (is.null(a)) b else a
test <-"brown_forsythe" %||% "brown_forsythe"
center <- "median" %||% "median"
if (test == "brown_forsythe" && center == "mean") test <- "levene" # analyses saved before the test list chose Levene's original through `center`
trim <- as.double(0.1 %||% 0.1)
alternative <- "two-sided" %||% "two-sided"
ratio <- as.double(1 %||% 1)
conf_level <- as.double(0.95 %||% 0.95)
calibration <- "auto" %||% "auto"
n_perm <- as.integer(9999 %||% 9999)
n_sim <- as.integer(9999 %||% 9999)
seed <- 42 # shared Wichmann-Hill stream: Python draws the same permutations / simulated samples
# %% Test
levels_g <- levels(df[[g]])
k <- length(levels_g)
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = g, min = 2, k = k)
yv <- as.double(df[[y]])
if (length(unique(yv)) < 2) cs_error("CS_E_CONSTANT", column = y) # no variation: every spread statistic is 0/0
gi <- as.integer(df[[g]]) - 1L
simulated <- c("hartley", "cochran_c")
rank_tests <- c("fligner", "conover", "ansari", "mood", "siegel_tukey", "klotz")
normal_theory <- c("f", "bartlett", "hartley", "cochran_c")
draws <- if (test %in% simulated) n_sim else n_perm
res <- cs_spread_test(yv, gi, test, trim = trim, ratio = ratio, alternative = alternative, calibration = calibration,
b = draws, seed = seed, conf_level = conf_level)
warnings <- c(warnings, res$warnings)
groups <- lapply(seq_len(k) - 1L, function(j) yv[gi == j])
ns <- vapply(groups, length, integer(1))
N <- sum(ns)
sds <- vapply(groups, stats::sd, numeric(1))
sd_ratio <- max(sds) / min(sds)
stat <- res$statistic
p <- res$p
symbol <- res$symbol
name <- res$label
# %% Assumptions
assumptions <- list()
if (test %in% normal_theory) {
ok <- vapply(groups, function(x) length(x) >= 3 && length(x) <= 5000, logical(1))
sw <- vapply(groups[ok], function(x) stats::shapiro.test(x)$p.value, numeric(1))
bad <- levels_g[ok][sw < 0.05]
if (!all(ok)) {
status <- "info"
detail <- "Too few (or too many) values in a group for Shapiro–Wilk; inspect the distributions."
} else if (length(bad)) {
status <- "warn"
detail <- sprintf("Shapiro–Wilk p < .05 in %s; %s is sensitive to non-normality, so prefer Brown–Forsythe or Fligner–Killeen.",
paste(bad, collapse = ", "), name)
} else {
status <- "pass"
detail <- "Shapiro–Wilk p ≥ .05 in every group."
}
assumptions <- c(assumptions, list(list(key = "normality", label = "Normality within groups", status = status, detail = detail)))
} else {
assumptions <- c(assumptions, list(list(key = "normality", label = "Normality within groups", status = "info",
detail = sprintf("Not required: the %s does not assume normal groups.", name))))
}
if (test %in% c("ansari", "mood", "siegel_tukey", "klotz")) {
meds <- vapply(groups, stats::median, numeric(1))
assumptions <- c(assumptions, list(list(key = "common_location", label = "Common location", status = "info",
detail = sprintf("Medians %s = %s, %s = %s. The test assumes a shared median; center the groups first if they differ in location.",
levels_g[1], formatC(meds[1], digits = 4, format = "g"), levels_g[2], formatC(meds[2], digits = 4, format = "g")))))
}
# %% Result
alpha <- 0.05
verdict <- if (p < alpha) {
sprintf("The spreads differ significantly (%s); prefer methods that do not assume equal variances (Welch's t-test / ANOVA).", cs_fmt_p(p))
} else {
sprintf("No evidence that the spreads differ (%s).", cs_fmt_p(p))
}
summary <- sprintf("Group SDs of %s range from %.2f to %.2f (largest / smallest = %.2f). %s: %s", y, min(sds), max(sds), sd_ratio, name, verdict)
values <- list(test = test, statistic = stat, stat_symbol = symbol, p = p, sd_ratio = sd_ratio, n = N, k = k)
for (key in c("f", "df1", "df2", "df", "z", "var_ratio", "ratio_null", "ci_low", "ci_high", "n_sim", "n_perm")) {
v <- res[[key]]
if (!is.null(v) && !is.infinite(v)) values[[key]] <- v
}
if (test %in% rank_tests) values$calibration <- res$calibration
if (test %in% c("hartley", "cochran_c")) values$max_var_group <- levels_g[res$max_var_group + 1L]
if (test == "hartley") values$min_var_group <- levels_g[res$min_var_group + 1L]
for (i in seq_len(k)) {
values[[sprintf("sd[%s]", levels_g[i])]] <- sds[i]
values[[sprintf("n[%s]", levels_g[i])]] <- ns[i]
}
imax <- which.max(sds)
imin <- which.min(sds)
values$sd_max <- sds[imax]
values$sd_min <- sds[imin]
values$sd_max_group <- levels_g[imax]
values$sd_min_group <- levels_g[imin]
values$method_label <- name
if (!is.null(res$df1)) {
apa <- sprintf("F(%s, %s) = %s, %s", format(res$df1), format(res$df2), cs_fmt_num(stat), cs_fmt_p(p))
statistics <- list(list(key = "f", label = "F", value = stat), list(key = "df1", label = "df1", value = res$df1),
list(key = "df2", label = "df2", value = res$df2))
} else if (!is.null(res$df)) {
apa <- sprintf("%s(%s) = %s, %s", symbol, format(res$df), cs_fmt_num(stat), cs_fmt_p(p))
statistics <- list(list(key = "statistic", label = symbol, value = stat), list(key = "df", label = "df", value = res$df))
} else if (!is.null(res$z)) {
apa <- sprintf("%s = %s, z = %s, %s", symbol, cs_fmt_num(stat), cs_fmt_num(res$z), cs_fmt_p(p))
statistics <- list(list(key = "statistic", label = symbol, value = stat), list(key = "z", label = "z", value = res$z))
} else {
apa <- sprintf("%s = %s, %s", symbol, cs_fmt_num(stat), cs_fmt_p(p))
statistics <- list(list(key = "statistic", label = symbol, value = stat))
}
statistics <- c(statistics, list(list(key = "p", label = "p", value = p, format = "p")))
effects <- list(list(key = "sd_ratio", label = "SD ratio (largest / smallest)", value = sd_ratio, method = "max SD / min SD"))
if (test == "f") {
eff <- list(key = "var_ratio", label = sprintf("Variance ratio (%s / %s)", levels_g[1], levels_g[2]), value = res$var_ratio,
method = "s₁² / s₂²")
if (is.finite(res$ci_low) && is.finite(res$ci_high)) {
eff$ciLow <- res$ci_low
eff$ciHigh <- res$ci_high
eff$ciLevel <- conf_level
}
effects <- c(effects, list(eff))
}
notes <- list()
if (test %in% c("brown_forsythe", "levene", "trimmed")) {
center_name <- switch(test, brown_forsythe = "median", levene = "mean", trimmed = sprintf("%s-trimmed mean", format(trim)))
notes <- c(notes, list(sprintf("%s: one-way ANOVA on absolute deviations from each group's %s.", name, center_name)))
} else if (test %in% simulated) {
notes <- c(notes, list(sprintf("%s: p-value from %d samples simulated under normality for these group sizes (seed %s).",
name, res$n_sim, format(seed))))
} else if (test %in% rank_tests) {
how <- switch(res$calibration,
exact = "the exact null distribution",
asymptotic = "the large-sample reference with the exact permutation variance",
permutation = sprintf("%d Monte Carlo permutations (seed %s)", n_perm, format(seed))
)
notes <- c(notes, list(sprintf("%s: p-value from %s.", name, how)))
}
if (test %in% c("f", "ansari", "mood", "siegel_tukey", "klotz") && alternative != "two-sided") {
notes <- c(notes, list(sprintf("One-sided: the alternative is that %s is %s spread out than %s.", levels_g[1],
if (alternative == "greater") "more" else "less", levels_g[2])))
}
chart_rows <- unique(round(seq(1, nrow(df), length.out = min(nrow(df), 5000))))
charts <- list(cs_chart("spread", "box-violin", 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_g)
)))
cs_publish(list(
method = "variance.levene",
methodVersion = "2.0.1",
title = name,
engine = cs_engine_info("stats", "nanoparquet"),
n = N,
summary = summary,
apa = apa,
statistics = statistics,
tables = list(list(
key = "spread", title = "Spread by group",
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 = "sd", label = "SD", type = "number"), list(key = "variance", label = "Variance", type = "number")),
rows = data.frame(group = levels_g, n = ns, median = vapply(groups, stats::median, numeric(1)), sd = sds, variance = sds^2)
)),
effectSizes = effects,
assumptions = assumptions,
warnings = warnings,
notes = notes,
charts = charts,
values = values
))
Sources
- Brown, M. B., & Forsythe, A. B. (1974). Robust tests for the equality of variances. JASA, 69, 364–367.
- Levene, H. (1960). Robust tests for equality of variances. In Contributions to Probability and Statistics.
- Bartlett, M. S. (1937). Properties of sufficiency and statistical tests. Proc. R. Soc. A, 160, 268–282.
- Hartley, H. O. (1950). The maximum F-ratio as a short-cut test for heterogeneity of variance. Biometrika, 37, 308–312.
- Cochran, W. G. (1941). The distribution of the largest of a set of estimated variances as a fraction of their total. Ann. Eugen., 11, 47–52.
- Fligner, M. A., & Killeen, T. J. (1976). Distribution-free two-sample tests for scale. JASA, 71, 210–213.
- Conover, W. J., Johnson, M. E., & Johnson, M. M. (1981). A comparative study of tests for homogeneity of variances. Technometrics, 23, 351–361.
- Ansari, A. R., & Bradley, R. A. (1960). Rank-sum tests for dispersions. Ann. Math. Stat., 31, 1174–1189.
- Mood, A. M. (1954). On the asymptotic efficiency of certain nonparametric two-sample tests. Ann. Math. Stat., 25, 514–522.
- Siegel, S., & Tukey, J. W. (1960). A nonparametric sum of ranks procedure for relative spread. JASA, 55, 429–445.
- Klotz, J. (1962). Nonparametric tests for scale. Ann. Math. Stat., 33, 498–512.
From the CodeSplash method registry · variance.levene v2.0.1.