Comparing directions between groups
Watson–Williams for mean direction, Watson's U² and Mardia–Watson–Wheeler for any difference, Wallraff for spread, and Rao for both.
What runs in CodeSplash
- STAT263Watson two sample U squared test Runs in CodeSplash
- STAT264Watson–Williams test Runs in CodeSplash
- STAT265Mardia–Watson–Wheeler test Runs in CodeSplash
- STAT266Wallraff test Runs in CodeSplash
- STAT267Rao circular homogeneity tests Runs in CodeSplash
- Comparing directions between groups (Watson–Williams, U², Wheeler, Wallraff, Rao) Verified in Python and R
You will be able to
- Choose a two- or k-sample circular test for the question you are asking
- Say what Watson–Williams assumes and what to use when that fails
- Separate a difference in direction from a difference in spread
Read first
Do pigeons with magnets fly differently?
ReadThree groups of simulated pigeons, 66 birds in all, released at one site. Do they differ, and if so, how: in direction, in spread, or both?
| Question | Test |
|---|---|
| Same mean direction? | Watson–WilliamsWatson–Williams testF test of a common mean direction across groups of von Mises angles with equal, fairly high concentration. |
| Same distribution, anything? | Watson two-sample U² (two groups) |
| Same distribution, any number of groups? | Mardia–Watson–Wheeler (uniform scores) |
| Same angular spread? | Wallraff |
| Same polar vector and dispersion? | Rao |
Watson–Williams is the circular ANOVA
ExploreIt compares the sum of the group resultants with the overall resultant, and multiplies by a correction based on .
Move the group directions apart, then lower the concentration. See how the F statistic and its correction change.
BExplorable · Watson–Williams test
Do two groups share the same mean direction?
Your data
Drag a point or use ↑/↓ to change itIf H₀ were true
- The reference: how F varies across samples when H₀ is true.
- Your statistic, from the data above.
- The p-value: the area at least as extreme as yours (p = .006).
- The hatched rejection region at α = .050: statistics landing here reject H₀.
The formula
With your numbers
- resultant lengths of each group and of the pooled sample
- von Mises concentration (maximum likelihood, pooled sample)
- Stephens' correction factor
The verdict
F(1, 38) = 8.29, p = .006
p ≤ α = .050: reject H₀
The circular one-way ANOVA: assumes von Mises data with a common, not too small concentration.
- Statistic
- 8.295
- p-value
- 0.0065
Watson–Williams test on Group 1 (°): n = 20; Group 2 (°): n = 20: F(1, 38) = 8.29, p = .006. The p-value is below α = .050, so the data are hard to reconcile with H₀.
How strong is the difference?
PredictPredict first
You run Watson–Williams twice on the pigeons: with the F approximation, then with 999 permutations.
Which p-value will be smaller?
Reveal
Asymptotic: p < .001. Permutation: p = .001.
A permutation p-value can't go below , so with so few permutations its floor is about 0.001.
What the test assumes
ReadWatson–Williams assumes von Mises groups with a common concentration that isn't too small. Rough guide: of about 2 or above.
The pooled here is 2.05, and the correction factor is 1.18. That is near the boundary, so check it.
When groups have visibly different concentrations, or the data aren't von Mises:
- Set p-value to Permutation, or
- Use the Mardia–Watson–Wheeler test, which works on ranks around the circle.
Three more views of the same birds
ReadMardia–Watson–Wheeler: W(4) = 21.87, p < .001
- Mardia–Watson–Wheeler W
- 21.868
- p
- < .001
Plots
View data
| bearing | group |
|---|---|
| 92.400 | control |
| 127.20 | control |
| 49.300 | control |
| 52.300 | control |
| 105.30 | control |
| 80.500 | control |
| 96.800 | control |
| 100.70 | control |
| 75.600 | control |
| 84.300 | control |
| 95.800 | control |
| 105.90 | control |
| 130.90 | control |
| 130.70 | control |
| 38.100 | control |
| 128.60 | control |
| 114.50 | control |
| 96.900 | control |
| 61 | control |
| 93.800 | control |
| 108.50 | control |
| 89.900 | control |
| 116.20 | control |
| 144.20 | control |
| 97.100 | magnet |
| 159.20 | magnet |
| 195.10 | magnet |
| 40.400 | magnet |
| 171.30 | magnet |
| 136.30 | magnet |
| 142.20 | magnet |
| 70.200 | magnet |
| 176.20 | magnet |
| 121.40 | magnet |
| 168 | magnet |
| 157.70 | magnet |
| 127.10 | magnet |
| 161.60 | magnet |
| 129.10 | magnet |
| 65 | magnet |
| 193.40 | magnet |
| 128.20 | magnet |
| 188.60 | magnet |
| 134.60 | magnet |
| 172.90 | magnet |
| 181 | magnet |
| 0.3000 | anosmic |
| 27.700 | anosmic |
| 59.300 | anosmic |
| 82.200 | anosmic |
| 29.200 | anosmic |
| 116 | anosmic |
| 120.90 | anosmic |
| 98.900 | anosmic |
| 36.900 | anosmic |
| 120.40 | anosmic |
| 117.10 | anosmic |
| 106.20 | anosmic |
| 206.80 | anosmic |
| 63.700 | anosmic |
First 60 of 66 rows.
View data
| bearing | group |
|---|---|
| 92.400 | control |
| 127.20 | control |
| 49.300 | control |
| 52.300 | control |
| 105.30 | control |
| 80.500 | control |
| 96.800 | control |
| 100.70 | control |
| 75.600 | control |
| 84.300 | control |
| 95.800 | control |
| 105.90 | control |
| 130.90 | control |
| 130.70 | control |
| 38.100 | control |
| 128.60 | control |
| 114.50 | control |
| 96.900 | control |
| 61 | control |
| 93.800 | control |
| 108.50 | control |
| 89.900 | control |
| 116.20 | control |
| 144.20 | control |
| 97.100 | magnet |
| 159.20 | magnet |
| 195.10 | magnet |
| 40.400 | magnet |
| 171.30 | magnet |
| 136.30 | magnet |
| 142.20 | magnet |
| 70.200 | magnet |
| 176.20 | magnet |
| 121.40 | magnet |
| 168 | magnet |
| 157.70 | magnet |
| 127.10 | magnet |
| 161.60 | magnet |
| 129.10 | magnet |
| 65 | magnet |
| 193.40 | magnet |
| 128.20 | magnet |
| 188.60 | magnet |
| 134.60 | magnet |
| 172.90 | magnet |
| 181 | magnet |
| 0.3000 | anosmic |
| 27.700 | anosmic |
| 59.300 | anosmic |
| 82.200 | anosmic |
| 29.200 | anosmic |
| 116 | anosmic |
| 120.90 | anosmic |
| 98.900 | anosmic |
| 36.900 | anosmic |
| 120.40 | anosmic |
| 117.10 | anosmic |
| 106.20 | anosmic |
| 206.80 | anosmic |
| 63.700 | anosmic |
First 60 of 66 rows.
Assumptions
- Independent angles — One angle per subject in each group.
Directions by group
| Group | n | Mean direction | Mean (degrees) | R̄ | κ | Circular SD (degrees) |
|---|---|---|---|---|---|---|
| control | 24 | 97.1° | 97.065 | 0.8947 | 5.058 | 27.028 |
| magnet | 22 | 145.2° | 145.18 | 0.7686 | 2.534 | 41.564 |
| anosmic | 20 | 81.2° | 81.233 | 0.6745 | 1.866 | 50.850 |
- p-value: asymptotic. Uniform scores use average ranks for ties.
The exact R script · R R version 4.5.1 (2025-06-13)
# Comparing directions between groups (Watson–Williams, U², Wheeler, Wallraff, Rao)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method circular.groups 1.0.1 · spec 28a641eb070e2eb7
# Dataset: ci_pigeons (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/ci_pigeons.parquet", col_select = c("bearing", "group")))
n_input <- nrow(df)
df[["group"]] <- factor(df[["group"]], levels = c("control", "magnet", "anosmic")) # stored level order
df <- df[stats::complete.cases(df[c("bearing", "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("bearing", "group")) # infinite values stop the run (registry/errors.yaml)
# %% Angles
# Angles become radians in [0, 2*pi): numeric values in the chosen unit, or a timestamp's position in
# its daily / weekly / yearly cycle (UTC). Axial data (0° = 180°) are doubled before testing.
units <- "degrees"
period <- NULL
disp_units <- switch(units, time_of_day = "hours", day_of_week = "weekday", day_of_year = "doy", units)
axial <- FALSE
a_name <- "bearing"
theta <- cs_circ_angles(df[[a_name]], units, period)
work <- if (axial) cs_circ_wrap(2 * theta) else theta
turn <- 2 * pi * (if (axial) 0.5 else 1)
unit_scale <- (if (disp_units == "custom") period else switch(disp_units, degrees = 360, radians = 2 * pi, hours = 24, weekday = 7, month = 12, doy = 365.25)) / (2 * pi)
show <- function(rad) cs_circ_from_radians(rad %% turn, disp_units, period)
lab <- function(rad) cs_circ_label(rad %% turn, units, period)
chart_angles <- cs_circ_from_radians(theta, disp_units, period)
chart_controls <- list(units = if (disp_units != "custom") disp_units else "radians",
orientation = if (disp_units %in% c("degrees", "hours")) "compass" else "math")
if (disp_units == "custom") chart_angles <- theta
# %% Test
g_name <- "group"
levels <- levels(df[[g_name]])
labels <- as.character(df[[g_name]])
test <- "wheeler"
calibration <- "approximate"
seed <- 42 # shared Wichmann-Hill stream: Python draws the same label permutations
center_value <- NULL
center <- NULL # Wallraff: distances to each group's own mean direction
# Inputs the tests can't handle stop with a catalog message (registry/errors.yaml), the same in Python:
# at least two groups (exactly two for U²), more angles than groups, and angles that vary.
cs_check_rows(length(labels), 3, "Comparing directions between groups")
cs_check_groups(labels, g_name, minimum = 2, exactly = if (test == "watson_u2") 2 else NULL)
cs_check_rows(length(labels), length(unique(labels)) + 1, "Comparing directions between groups")
if (test == "rao") {
for (lv in levels) { # each group's covariance of cosines and sines needs two angles
n_lv <- sum(labels == lv)
if (n_lv == 1) cs_error("CS_E_SMALL_GROUP", min = 2, group = lv, n = n_lv)
}
}
cs_check_not_constant(theta, a_name)
r <- cs_circ_groups(work, labels, test = test, calibration = calibration, n_perm = 9999, seed = seed, center = center, levels = levels)
sp <- cs_circ_split(theta, labels, levels)
samples <- sp$samples
kept <- sp$levels
n <- sum(lengths(samples))
k <- length(samples)
per_group <- lapply(seq_along(samples), function(i) {
x <- samples[[i]]
dg <- cs_circ_describe(x, axial = axial)
list(group = kept[i], n = length(x), mean = show(dg$mean), label = lab(dg$mean), rbar = dg$rbar, kappa = dg$kappa,
circ_sd = dg$circ_sd * unit_scale)
})
# %% Assumptions
assumptions <- list()
if (test == "watson_williams") {
kap <- r$kappa_pooled
status <- if (kap >= 2) "pass" else if (kap >= 1) "warn" else "fail"
assumptions[[length(assumptions) + 1]] <- list(key = "concentration", label = "Concentrated angles (κ ≥ 2)", status = status, statistic = kap,
detail = paste0(sprintf("Pooled κ = %.2f", kap), if (kap >= 2) "." else "; the F approximation is poor for dispersed angles — use the uniform-scores test or a permutation p."))
wal <- cs_circ_wallraff(lapply(samples, function(x) if (axial) cs_circ_wrap(2 * x) else x))
assumptions[[length(assumptions) + 1]] <- list(key = "equal_concentration", label = "Equal concentration", status = if (wal$p >= 0.05) "pass" else "warn",
statistic = wal$h, p = wal$p,
detail = paste0(sprintf("Wallraff test of equal dispersion %s", cs_fmt_p(wal$p)), if (wal$p >= 0.05) "." else "; the groups differ in spread, so a mean-direction F test is unreliable."))
}
assumptions[[length(assumptions) + 1]] <- list(key = "independence", label = "Independent angles", status = "info", detail = "One angle per subject in each group.")
small <- vapply(Filter(function(g) g$n < 10, per_group), function(g) g$group, character(1))
if (length(small)) warnings <- c(warnings, sprintf("Fewer than 10 angles in %s; prefer permutation p-values.", paste(small, collapse = ", ")))
# %% Result
NAMES <- list(watson_williams = c("Watson–Williams", "F"), watson_u2 = c("Watson two-sample U²", "U²"), wheeler = c("Mardia–Watson–Wheeler", "W"),
wallraff = c("Wallraff", "H"), rao = c("Rao homogeneity (polar vectors)", "Q"))
name <- NAMES[[test]][1]
symbol <- NAMES[[test]][2]
p <- r$p
values <- list(n = n, k = k, test = test, statistic = r$statistic, p = p, df1 = r$df1, df2 = r$df2,
kappa_pooled = r$kappa_pooled, correction = r$correction, dispersion_q = r$dispersion_q,
dispersion_p = r$dispersion_p, p_asymptotic = r$p_asymptotic, n_perm = r$n_perm, center = center_value)
for (g in per_group) {
values[[sprintf("mean_direction[%s]", g$group)]] <- g$mean
values[[sprintf("rbar[%s]", g$group)]] <- g$rbar
values[[sprintf("n[%s]", g$group)]] <- g$n
}
what <- c(watson_williams = "mean directions", watson_u2 = "distributions", wheeler = "distributions", wallraff = "angular spreads", rao = "polar vectors")[[test]]
how <- if (calibration == "permutation") sprintf("permutation (%d label shuffles, seed %d)", as.integer(r$n_perm), as.integer(seed)) else "asymptotic"
dfs <- if (test == "watson_williams") sprintf("(%d, %d)", as.integer(r$df1), as.integer(r$df2)) else if (!is.null(r$df1)) sprintf("(%d)", as.integer(r$df1)) else ""
means <- paste(vapply(per_group, function(g) paste(g$group, g$label), character(1)), collapse = "; ")
summary <- paste0(sprintf("%s test across %d groups of %s (n = %d): %s%s = %.3f, %s. ", name, k, g_name, n, symbol, dfs, r$statistic, cs_fmt_p(p)),
if (p < 0.05) sprintf("The %s differ", what) else sprintf("No evidence that the %s differ", what), sprintf(". Mean directions: %s.", means))
if (test == "rao") summary <- paste0(summary, sprintf(" Dispersions: Q = %.3f, %s.", r$dispersion_q, cs_fmt_p(r$dispersion_p)))
take <- seq_len(min(nrow(df), 5000))
chart_roles <- list(angle = cs_col(a_name, chart_angles[take], "numeric"), group = cs_col(g_name, labels[take], levels = levels))
cs_publish(list(
method = "circular.groups",
methodVersion = "1.0.1",
title = "Comparing directions between groups",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("%s: %s%s = %s, %s", name, symbol, dfs, cs_fmt_num(r$statistic), cs_fmt_p(p)),
statistics = list(list(key = "statistic", label = paste(name, symbol), value = r$statistic),
list(key = "p", label = "p", value = p, format = "p")),
tables = list(list(key = "groups", title = "Directions by group",
columns = list(list(key = "group", label = "Group", type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "label", label = "Mean direction", type = "string"), list(key = "mean", label = sprintf("Mean (%s)", disp_units), type = "number"),
list(key = "rbar", label = "R̄", type = "number"), list(key = "kappa", label = "κ", type = "number"),
list(key = "circ_sd", label = sprintf("Circular SD (%s)", disp_units), type = "number")),
rows = per_group)),
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(sprintf("p-value: %s.", how),
if (test == "watson_williams") " Watson–Williams uses K = 1 + 3/(8κ̂) with κ̂ the von Mises MLE of the combined sample." else "",
if (test == "wheeler") " Uniform scores use average ranks for ties." else "")),
values = values,
charts = list(cs_chart("rose", "rose-diagram", paste(a_name, "by", g_name), chart_roles, chart_controls),
cs_chart("dots", "circular-dot", paste(a_name, "by", g_name), chart_roles, chart_controls))
))
Mardia–Watson–Wheeler: W(4) = 21.87, p < .001
- Mardia–Watson–Wheeler W
- 21.868
- p
- < .001
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Independent angles — One angle per subject in each group.
Directions by group
| Group | n | Mean direction | Mean (degrees) | R̄ | κ | Circular SD (degrees) |
|---|---|---|---|---|---|---|
| control | 24 | 97.1° | 97.065 | 0.8947 | 5.058 | 27.028 |
| magnet | 22 | 145.2° | 145.18 | 0.7686 | 2.534 | 41.564 |
| anosmic | 20 | 81.2° | 81.233 | 0.6745 | 1.866 | 50.850 |
- p-value: asymptotic. Uniform scores use average ranks for ties.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Comparing directions between groups (Watson–Williams, U², Wheeler, Wallraff, Rao)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method circular.groups 1.0.1 · spec 28a641eb070e2eb7
# Dataset: ci_pigeons (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.errors import check_groups, check_not_constant
from codesplash.stats import circular
# %% Data
df = pd.read_parquet("tests/parity/fixtures/ci_pigeons.parquet", columns=["bearing", "group"])
n_input = len(df)
df["group"] = pd.Categorical(df["group"], categories=["control", "magnet", "anosmic"]) # stored level order
df = df.dropna(subset=["bearing", "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, ["bearing", "group"]) # infinite values stop the run (registry/errors.yaml)
# %% Angles
# Angles become radians in [0, 2π): numeric values in the chosen unit, or a timestamp's position in its
# daily / weekly / yearly cycle (UTC). Axial data (0° ≡ 180°) are doubled before testing.
units = "degrees"
period = None
disp_units = {"time_of_day": "hours", "day_of_week": "weekday", "day_of_year": "doy"}.get(units, units)
axial = False
a_name = "bearing"
theta = circular.angles(df[a_name] if units in circular.CYCLES else df[a_name].to_numpy(dtype=float), units, period)
work = circular.wrap(2.0 * theta) if axial else theta
turn = 2.0 * np.pi * (0.5 if axial else 1.0)
unit_scale = circular.period_of(disp_units, period)[0] / (2.0 * np.pi) # radians → display units
def show(rad):
"""A direction in the user's units (axial: halved back to the axis)."""
return float(circular.from_radians(np.mod(rad, turn), disp_units, period))
def lab(rad):
return circular.label(np.mod(rad, turn), units, period)
chart_angles = circular.from_radians(theta, disp_units, period) # what the charts draw
chart_controls = {"units": disp_units if disp_units != "custom" else "radians", "orientation": "compass" if disp_units in ("degrees", "hours") else "math"}
if disp_units == "custom":
chart_angles = theta
# %% Test
g_name = "group"
levels = [str(x) for x in df[g_name].cat.categories]
labels = df[g_name].astype(str).to_numpy()
test = "wheeler"
calibration = "approximate"
seed = 42 # shared Wichmann–Hill stream: R draws the same label permutations
center_value, center = None, None # Wallraff: distances to each group's own mean direction
# Inputs the tests can't handle stop with a catalog message (registry/errors.yaml), the same in R:
# at least two groups (exactly two for U²), more angles than groups, and angles that vary.
cs.check_rows(len(labels), 3, "Comparing directions between groups")
check_groups(labels, g_name, minimum=2, exactly=2 if test == "watson_u2" else None)
cs.check_rows(len(labels), len(set(labels)) + 1, "Comparing directions between groups")
if test == "rao":
for lv in levels: # each group's covariance of cosines and sines needs two angles
n_lv = int(np.sum(labels == lv))
if n_lv == 1:
cs.cs_error("CS_E_SMALL_GROUP", min=2, group=lv, n=n_lv)
check_not_constant(theta, a_name)
r = circular.groups(work, labels, test=test, calibration=calibration, n_perm=int(9999), seed=seed, center=center, levels=levels)
samples, kept = circular._split(theta, labels, levels)
n = int(sum(len(x) for x in samples))
k = len(samples)
per_group = []
for lv, x in zip(kept, samples):
dg = circular.describe(x, axial=axial)
per_group.append({"group": lv, "n": len(x), "mean": show(dg["mean"]), "label": lab(dg["mean"]), "rbar": dg["rbar"], "kappa": dg["kappa"],
"circ_sd": dg["circ_sd"] * unit_scale})
# %% Assumptions
assumptions = []
if test == "watson_williams":
kap = r["kappa_pooled"]
status = "pass" if kap >= 2 else ("warn" if kap >= 1 else "fail")
assumptions.append({"key": "concentration", "label": "Concentrated angles (κ ≥ 2)", "status": status, "statistic": kap,
"detail": f"Pooled κ = {kap:.2f}" + ("." if kap >= 2 else "; the F approximation is poor for dispersed angles — use the uniform-scores test or a permutation p.")})
wal = circular.wallraff([circular.wrap(2.0 * x) if axial else x for x in samples])
assumptions.append({"key": "equal_concentration", "label": "Equal concentration", "status": "pass" if wal["p"] >= 0.05 else "warn",
"statistic": wal["h"], "p": wal["p"],
"detail": f"Wallraff test of equal dispersion {cs.fmt_p(wal['p'])}" + ("." if wal["p"] >= 0.05 else "; the groups differ in spread, so a mean-direction F test is unreliable.")})
assumptions.append({"key": "independence", "label": "Independent angles", "status": "info", "detail": "One angle per subject in each group."})
small = [g["group"] for g in per_group if g["n"] < 10]
if small:
warnings.append(f"Fewer than 10 angles in {', '.join(small)}; prefer permutation p-values.")
# %% Result
NAMES = {"watson_williams": ("Watson–Williams", "F"), "watson_u2": ("Watson two-sample U²", "U²"), "wheeler": ("Mardia–Watson–Wheeler", "W"),
"wallraff": ("Wallraff", "H"), "rao": ("Rao homogeneity (polar vectors)", "Q")}
name, symbol = NAMES[test]
p = r["p"]
values = {"n": n, "k": k, "test": test, "statistic": r["statistic"], "p": p, "df1": r.get("df1"), "df2": r.get("df2"),
"kappa_pooled": r.get("kappa_pooled"), "correction": r.get("correction"), "dispersion_q": r.get("dispersion_q"),
"dispersion_p": r.get("dispersion_p"), "p_asymptotic": r.get("p_asymptotic"), "n_perm": r.get("n_perm"), "center": center_value}
for g in per_group:
values[f"mean_direction[{g['group']}]"] = g["mean"]
values[f"rbar[{g['group']}]"] = g["rbar"]
values[f"n[{g['group']}]"] = g["n"]
what = {"watson_williams": "mean directions", "watson_u2": "distributions", "wheeler": "distributions", "wallraff": "angular spreads", "rao": "polar vectors"}[test]
how = f"permutation ({r['n_perm']} label shuffles, seed {seed})" if calibration == "permutation" else "asymptotic"
dfs = f"({r['df1']}, {r['df2']})" if test == "watson_williams" else (f"({r['df1']})" if r.get("df1") is not None else "")
means = "; ".join(f"{g['group']} {g['label']}" for g in per_group)
summary = (f"{name} test across {k} groups of {g_name} (n = {n}): {symbol}{dfs} = {r['statistic']:.3f}, {cs.fmt_p(p)}. "
+ (f"The {what} differ" if p < 0.05 else f"No evidence that the {what} differ") + f". Mean directions: {means}.")
if test == "rao":
summary += f" Dispersions: Q = {r['dispersion_q']:.3f}, {cs.fmt_p(r['dispersion_p'])}."
chart_roles = {"angle": cs.col(a_name, np.asarray(chart_angles)[:5000], "numeric"),
"group": cs.col(g_name, labels[:5000], levels=levels)}
cs.publish({
"method": "circular.groups",
"methodVersion": "1.0.1",
"title": "Comparing directions between groups",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"{name}: {symbol}{dfs} = {cs.fmt_num(r['statistic'])}, {cs.fmt_p(p)}",
"statistics": [{"key": "statistic", "label": f"{name} {symbol}", "value": r["statistic"]},
{"key": "p", "label": "p", "value": p, "format": "p"}],
"tables": [{"key": "groups", "title": "Directions by group",
"columns": [{"key": "group", "label": "Group", "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "label", "label": "Mean direction", "type": "string"}, {"key": "mean", "label": f"Mean ({disp_units})", "type": "number"},
{"key": "rbar", "label": "R̄", "type": "number"}, {"key": "kappa", "label": "κ", "type": "number"},
{"key": "circ_sd", "label": f"Circular SD ({disp_units})", "type": "number"}],
"rows": per_group}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"p-value: {how}."
+ (" Watson–Williams uses K = 1 + 3/(8κ̂) with κ̂ the von Mises MLE of the combined sample." if test == "watson_williams" else "")
+ (" Uniform scores use average ranks for ties." if test == "wheeler" else "")],
"values": values,
"charts": [cs.chart("rose", "rose-diagram", f"{a_name} by {g_name}", chart_roles, chart_controls),
cs.chart("dots", "circular-dot", f"{a_name} by {g_name}", chart_roles, chart_controls)],
})
- Mardia–Watson–Wheeler: W = 21.9, p < .001. Some difference in distribution.
- Wallraff compares each bird's angular distance from the group mean: p = .003. The groups differ in spread as well.
So "the magnets changed direction" isn't the whole story, and a difference in means with unequal spreads calls for caution.
Two groups and two cycles
Read- Wind direction by season, Watson U²: 1.39, p < .001.
- Order hour by channel, Rao's polar test: p < .001; dispersion test p < .001.
Rao homogeneity (polar vectors): Q(1) = 56.12, p < .001
- Rao homogeneity (polar vectors) Q
- 56.119
- p
- < .001
Plots
View data
| hour | channel |
|---|---|
| 10.498 | store |
| 18.395 | web |
| 20.048 | web |
| 11.985 | store |
| 19.361 | web |
| 18.519 | web |
| 12.777 | store |
| 22.198 | web |
| 10.546 | store |
| 9.366 | store |
| 20.269 | web |
| 19.236 | web |
| 10.476 | store |
| 12.035 | store |
| 12.550 | store |
| 18.450 | web |
| 10.687 | store |
| 21.640 | web |
| 15.376 | store |
| 21.986 | web |
| 17.463 | web |
| 14.976 | store |
| 20.936 | web |
| 13.225 | store |
| 18.181 | web |
| 16.543 | web |
| 22.579 | web |
| 23.692 | web |
| 14.532 | web |
| 11.943 | store |
| 20.543 | web |
| 17.847 | web |
| 22.978 | web |
| 15.664 | web |
| 23.667 | web |
| 20.776 | web |
| 14.455 | store |
| 12.651 | store |
| 13.586 | store |
| 21.875 | web |
| 18.900 | store |
| 23.229 | web |
| 20.853 | web |
| 16.826 | web |
| 15.308 | web |
| 17.155 | web |
| 20.045 | web |
| 13.359 | store |
| 3.332 | web |
| 23.565 | web |
| 11.042 | store |
| 23.398 | web |
| 17.720 | web |
| 9.948 | store |
| 14.957 | store |
| 23.017 | web |
| 22.943 | web |
| 20.799 | web |
| 10.847 | store |
| 13.674 | store |
First 60 of 300 rows.
View data
| hour | channel |
|---|---|
| 10.498 | store |
| 18.395 | web |
| 20.048 | web |
| 11.985 | store |
| 19.361 | web |
| 18.519 | web |
| 12.777 | store |
| 22.198 | web |
| 10.546 | store |
| 9.366 | store |
| 20.269 | web |
| 19.236 | web |
| 10.476 | store |
| 12.035 | store |
| 12.550 | store |
| 18.450 | web |
| 10.687 | store |
| 21.640 | web |
| 15.376 | store |
| 21.986 | web |
| 17.463 | web |
| 14.976 | store |
| 20.936 | web |
| 13.225 | store |
| 18.181 | web |
| 16.543 | web |
| 22.579 | web |
| 23.692 | web |
| 14.532 | web |
| 11.943 | store |
| 20.543 | web |
| 17.847 | web |
| 22.978 | web |
| 15.664 | web |
| 23.667 | web |
| 20.776 | web |
| 14.455 | store |
| 12.651 | store |
| 13.586 | store |
| 21.875 | web |
| 18.900 | store |
| 23.229 | web |
| 20.853 | web |
| 16.826 | web |
| 15.308 | web |
| 17.155 | web |
| 20.045 | web |
| 13.359 | store |
| 3.332 | web |
| 23.565 | web |
| 11.042 | store |
| 23.398 | web |
| 17.720 | web |
| 9.948 | store |
| 14.957 | store |
| 23.017 | web |
| 22.943 | web |
| 20.799 | web |
| 10.847 | store |
| 13.674 | store |
First 60 of 300 rows.
Assumptions
- Independent angles — One angle per subject in each group.
Directions by group
| Group | n | Mean direction | Mean (hours) | R̄ | κ | Circular SD (hours) |
|---|---|---|---|---|---|---|
| store | 128 | 12:18 | 12.303 | 0.8353 | 3.392 | 2.292 |
| web | 172 | 20:11 | 20.186 | 0.6966 | 1.993 | 3.248 |
- p-value: asymptotic.
The exact R script · R R version 4.5.1 (2025-06-13)
# Comparing directions between groups (Watson–Williams, U², Wheeler, Wallraff, Rao)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method circular.groups 1.0.1 · spec 36fe2739d3382af5
# Dataset: ci_hours (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/ci_hours.parquet", col_select = c("hour", "channel")))
n_input <- nrow(df)
df[["channel"]] <- factor(df[["channel"]], levels = c("store", "web")) # stored level order
df <- df[stats::complete.cases(df[c("hour", "channel")]), , 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("hour", "channel")) # infinite values stop the run (registry/errors.yaml)
# %% Angles
# Angles become radians in [0, 2*pi): numeric values in the chosen unit, or a timestamp's position in
# its daily / weekly / yearly cycle (UTC). Axial data (0° = 180°) are doubled before testing.
units <- "hours"
period <- NULL
disp_units <- switch(units, time_of_day = "hours", day_of_week = "weekday", day_of_year = "doy", units)
axial <- FALSE
a_name <- "hour"
theta <- cs_circ_angles(df[[a_name]], units, period)
work <- if (axial) cs_circ_wrap(2 * theta) else theta
turn <- 2 * pi * (if (axial) 0.5 else 1)
unit_scale <- (if (disp_units == "custom") period else switch(disp_units, degrees = 360, radians = 2 * pi, hours = 24, weekday = 7, month = 12, doy = 365.25)) / (2 * pi)
show <- function(rad) cs_circ_from_radians(rad %% turn, disp_units, period)
lab <- function(rad) cs_circ_label(rad %% turn, units, period)
chart_angles <- cs_circ_from_radians(theta, disp_units, period)
chart_controls <- list(units = if (disp_units != "custom") disp_units else "radians",
orientation = if (disp_units %in% c("degrees", "hours")) "compass" else "math")
if (disp_units == "custom") chart_angles <- theta
# %% Test
g_name <- "channel"
levels <- levels(df[[g_name]])
labels <- as.character(df[[g_name]])
test <- "rao"
calibration <- "approximate"
seed <- 42 # shared Wichmann-Hill stream: Python draws the same label permutations
center_value <- NULL
center <- NULL # Wallraff: distances to each group's own mean direction
# Inputs the tests can't handle stop with a catalog message (registry/errors.yaml), the same in Python:
# at least two groups (exactly two for U²), more angles than groups, and angles that vary.
cs_check_rows(length(labels), 3, "Comparing directions between groups")
cs_check_groups(labels, g_name, minimum = 2, exactly = if (test == "watson_u2") 2 else NULL)
cs_check_rows(length(labels), length(unique(labels)) + 1, "Comparing directions between groups")
if (test == "rao") {
for (lv in levels) { # each group's covariance of cosines and sines needs two angles
n_lv <- sum(labels == lv)
if (n_lv == 1) cs_error("CS_E_SMALL_GROUP", min = 2, group = lv, n = n_lv)
}
}
cs_check_not_constant(theta, a_name)
r <- cs_circ_groups(work, labels, test = test, calibration = calibration, n_perm = 9999, seed = seed, center = center, levels = levels)
sp <- cs_circ_split(theta, labels, levels)
samples <- sp$samples
kept <- sp$levels
n <- sum(lengths(samples))
k <- length(samples)
per_group <- lapply(seq_along(samples), function(i) {
x <- samples[[i]]
dg <- cs_circ_describe(x, axial = axial)
list(group = kept[i], n = length(x), mean = show(dg$mean), label = lab(dg$mean), rbar = dg$rbar, kappa = dg$kappa,
circ_sd = dg$circ_sd * unit_scale)
})
# %% Assumptions
assumptions <- list()
if (test == "watson_williams") {
kap <- r$kappa_pooled
status <- if (kap >= 2) "pass" else if (kap >= 1) "warn" else "fail"
assumptions[[length(assumptions) + 1]] <- list(key = "concentration", label = "Concentrated angles (κ ≥ 2)", status = status, statistic = kap,
detail = paste0(sprintf("Pooled κ = %.2f", kap), if (kap >= 2) "." else "; the F approximation is poor for dispersed angles — use the uniform-scores test or a permutation p."))
wal <- cs_circ_wallraff(lapply(samples, function(x) if (axial) cs_circ_wrap(2 * x) else x))
assumptions[[length(assumptions) + 1]] <- list(key = "equal_concentration", label = "Equal concentration", status = if (wal$p >= 0.05) "pass" else "warn",
statistic = wal$h, p = wal$p,
detail = paste0(sprintf("Wallraff test of equal dispersion %s", cs_fmt_p(wal$p)), if (wal$p >= 0.05) "." else "; the groups differ in spread, so a mean-direction F test is unreliable."))
}
assumptions[[length(assumptions) + 1]] <- list(key = "independence", label = "Independent angles", status = "info", detail = "One angle per subject in each group.")
small <- vapply(Filter(function(g) g$n < 10, per_group), function(g) g$group, character(1))
if (length(small)) warnings <- c(warnings, sprintf("Fewer than 10 angles in %s; prefer permutation p-values.", paste(small, collapse = ", ")))
# %% Result
NAMES <- list(watson_williams = c("Watson–Williams", "F"), watson_u2 = c("Watson two-sample U²", "U²"), wheeler = c("Mardia–Watson–Wheeler", "W"),
wallraff = c("Wallraff", "H"), rao = c("Rao homogeneity (polar vectors)", "Q"))
name <- NAMES[[test]][1]
symbol <- NAMES[[test]][2]
p <- r$p
values <- list(n = n, k = k, test = test, statistic = r$statistic, p = p, df1 = r$df1, df2 = r$df2,
kappa_pooled = r$kappa_pooled, correction = r$correction, dispersion_q = r$dispersion_q,
dispersion_p = r$dispersion_p, p_asymptotic = r$p_asymptotic, n_perm = r$n_perm, center = center_value)
for (g in per_group) {
values[[sprintf("mean_direction[%s]", g$group)]] <- g$mean
values[[sprintf("rbar[%s]", g$group)]] <- g$rbar
values[[sprintf("n[%s]", g$group)]] <- g$n
}
what <- c(watson_williams = "mean directions", watson_u2 = "distributions", wheeler = "distributions", wallraff = "angular spreads", rao = "polar vectors")[[test]]
how <- if (calibration == "permutation") sprintf("permutation (%d label shuffles, seed %d)", as.integer(r$n_perm), as.integer(seed)) else "asymptotic"
dfs <- if (test == "watson_williams") sprintf("(%d, %d)", as.integer(r$df1), as.integer(r$df2)) else if (!is.null(r$df1)) sprintf("(%d)", as.integer(r$df1)) else ""
means <- paste(vapply(per_group, function(g) paste(g$group, g$label), character(1)), collapse = "; ")
summary <- paste0(sprintf("%s test across %d groups of %s (n = %d): %s%s = %.3f, %s. ", name, k, g_name, n, symbol, dfs, r$statistic, cs_fmt_p(p)),
if (p < 0.05) sprintf("The %s differ", what) else sprintf("No evidence that the %s differ", what), sprintf(". Mean directions: %s.", means))
if (test == "rao") summary <- paste0(summary, sprintf(" Dispersions: Q = %.3f, %s.", r$dispersion_q, cs_fmt_p(r$dispersion_p)))
take <- seq_len(min(nrow(df), 5000))
chart_roles <- list(angle = cs_col(a_name, chart_angles[take], "numeric"), group = cs_col(g_name, labels[take], levels = levels))
cs_publish(list(
method = "circular.groups",
methodVersion = "1.0.1",
title = "Comparing directions between groups",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("%s: %s%s = %s, %s", name, symbol, dfs, cs_fmt_num(r$statistic), cs_fmt_p(p)),
statistics = list(list(key = "statistic", label = paste(name, symbol), value = r$statistic),
list(key = "p", label = "p", value = p, format = "p")),
tables = list(list(key = "groups", title = "Directions by group",
columns = list(list(key = "group", label = "Group", type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "label", label = "Mean direction", type = "string"), list(key = "mean", label = sprintf("Mean (%s)", disp_units), type = "number"),
list(key = "rbar", label = "R̄", type = "number"), list(key = "kappa", label = "κ", type = "number"),
list(key = "circ_sd", label = sprintf("Circular SD (%s)", disp_units), type = "number")),
rows = per_group)),
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(sprintf("p-value: %s.", how),
if (test == "watson_williams") " Watson–Williams uses K = 1 + 3/(8κ̂) with κ̂ the von Mises MLE of the combined sample." else "",
if (test == "wheeler") " Uniform scores use average ranks for ties." else "")),
values = values,
charts = list(cs_chart("rose", "rose-diagram", paste(a_name, "by", g_name), chart_roles, chart_controls),
cs_chart("dots", "circular-dot", paste(a_name, "by", g_name), chart_roles, chart_controls))
))
Rao homogeneity (polar vectors): Q(1) = 56.12, p < .001
- Rao homogeneity (polar vectors) Q
- 56.119
- p
- < .001
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Independent angles — One angle per subject in each group.
Directions by group
| Group | n | Mean direction | Mean (hours) | R̄ | κ | Circular SD (hours) |
|---|---|---|---|---|---|---|
| store | 128 | 12:18 | 12.303 | 0.8353 | 3.392 | 2.292 |
| web | 172 | 20:11 | 20.186 | 0.6966 | 1.993 | 3.248 |
- p-value: asymptotic.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Comparing directions between groups (Watson–Williams, U², Wheeler, Wallraff, Rao)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method circular.groups 1.0.1 · spec 36fe2739d3382af5
# Dataset: ci_hours (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.errors import check_groups, check_not_constant
from codesplash.stats import circular
# %% Data
df = pd.read_parquet("tests/parity/fixtures/ci_hours.parquet", columns=["hour", "channel"])
n_input = len(df)
df["channel"] = pd.Categorical(df["channel"], categories=["store", "web"]) # stored level order
df = df.dropna(subset=["hour", "channel"]) # listwise deletion over the analysis columns
df["channel"] = df["channel"].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, ["hour", "channel"]) # infinite values stop the run (registry/errors.yaml)
# %% Angles
# Angles become radians in [0, 2π): numeric values in the chosen unit, or a timestamp's position in its
# daily / weekly / yearly cycle (UTC). Axial data (0° ≡ 180°) are doubled before testing.
units = "hours"
period = None
disp_units = {"time_of_day": "hours", "day_of_week": "weekday", "day_of_year": "doy"}.get(units, units)
axial = False
a_name = "hour"
theta = circular.angles(df[a_name] if units in circular.CYCLES else df[a_name].to_numpy(dtype=float), units, period)
work = circular.wrap(2.0 * theta) if axial else theta
turn = 2.0 * np.pi * (0.5 if axial else 1.0)
unit_scale = circular.period_of(disp_units, period)[0] / (2.0 * np.pi) # radians → display units
def show(rad):
"""A direction in the user's units (axial: halved back to the axis)."""
return float(circular.from_radians(np.mod(rad, turn), disp_units, period))
def lab(rad):
return circular.label(np.mod(rad, turn), units, period)
chart_angles = circular.from_radians(theta, disp_units, period) # what the charts draw
chart_controls = {"units": disp_units if disp_units != "custom" else "radians", "orientation": "compass" if disp_units in ("degrees", "hours") else "math"}
if disp_units == "custom":
chart_angles = theta
# %% Test
g_name = "channel"
levels = [str(x) for x in df[g_name].cat.categories]
labels = df[g_name].astype(str).to_numpy()
test = "rao"
calibration = "approximate"
seed = 42 # shared Wichmann–Hill stream: R draws the same label permutations
center_value, center = None, None # Wallraff: distances to each group's own mean direction
# Inputs the tests can't handle stop with a catalog message (registry/errors.yaml), the same in R:
# at least two groups (exactly two for U²), more angles than groups, and angles that vary.
cs.check_rows(len(labels), 3, "Comparing directions between groups")
check_groups(labels, g_name, minimum=2, exactly=2 if test == "watson_u2" else None)
cs.check_rows(len(labels), len(set(labels)) + 1, "Comparing directions between groups")
if test == "rao":
for lv in levels: # each group's covariance of cosines and sines needs two angles
n_lv = int(np.sum(labels == lv))
if n_lv == 1:
cs.cs_error("CS_E_SMALL_GROUP", min=2, group=lv, n=n_lv)
check_not_constant(theta, a_name)
r = circular.groups(work, labels, test=test, calibration=calibration, n_perm=int(9999), seed=seed, center=center, levels=levels)
samples, kept = circular._split(theta, labels, levels)
n = int(sum(len(x) for x in samples))
k = len(samples)
per_group = []
for lv, x in zip(kept, samples):
dg = circular.describe(x, axial=axial)
per_group.append({"group": lv, "n": len(x), "mean": show(dg["mean"]), "label": lab(dg["mean"]), "rbar": dg["rbar"], "kappa": dg["kappa"],
"circ_sd": dg["circ_sd"] * unit_scale})
# %% Assumptions
assumptions = []
if test == "watson_williams":
kap = r["kappa_pooled"]
status = "pass" if kap >= 2 else ("warn" if kap >= 1 else "fail")
assumptions.append({"key": "concentration", "label": "Concentrated angles (κ ≥ 2)", "status": status, "statistic": kap,
"detail": f"Pooled κ = {kap:.2f}" + ("." if kap >= 2 else "; the F approximation is poor for dispersed angles — use the uniform-scores test or a permutation p.")})
wal = circular.wallraff([circular.wrap(2.0 * x) if axial else x for x in samples])
assumptions.append({"key": "equal_concentration", "label": "Equal concentration", "status": "pass" if wal["p"] >= 0.05 else "warn",
"statistic": wal["h"], "p": wal["p"],
"detail": f"Wallraff test of equal dispersion {cs.fmt_p(wal['p'])}" + ("." if wal["p"] >= 0.05 else "; the groups differ in spread, so a mean-direction F test is unreliable.")})
assumptions.append({"key": "independence", "label": "Independent angles", "status": "info", "detail": "One angle per subject in each group."})
small = [g["group"] for g in per_group if g["n"] < 10]
if small:
warnings.append(f"Fewer than 10 angles in {', '.join(small)}; prefer permutation p-values.")
# %% Result
NAMES = {"watson_williams": ("Watson–Williams", "F"), "watson_u2": ("Watson two-sample U²", "U²"), "wheeler": ("Mardia–Watson–Wheeler", "W"),
"wallraff": ("Wallraff", "H"), "rao": ("Rao homogeneity (polar vectors)", "Q")}
name, symbol = NAMES[test]
p = r["p"]
values = {"n": n, "k": k, "test": test, "statistic": r["statistic"], "p": p, "df1": r.get("df1"), "df2": r.get("df2"),
"kappa_pooled": r.get("kappa_pooled"), "correction": r.get("correction"), "dispersion_q": r.get("dispersion_q"),
"dispersion_p": r.get("dispersion_p"), "p_asymptotic": r.get("p_asymptotic"), "n_perm": r.get("n_perm"), "center": center_value}
for g in per_group:
values[f"mean_direction[{g['group']}]"] = g["mean"]
values[f"rbar[{g['group']}]"] = g["rbar"]
values[f"n[{g['group']}]"] = g["n"]
what = {"watson_williams": "mean directions", "watson_u2": "distributions", "wheeler": "distributions", "wallraff": "angular spreads", "rao": "polar vectors"}[test]
how = f"permutation ({r['n_perm']} label shuffles, seed {seed})" if calibration == "permutation" else "asymptotic"
dfs = f"({r['df1']}, {r['df2']})" if test == "watson_williams" else (f"({r['df1']})" if r.get("df1") is not None else "")
means = "; ".join(f"{g['group']} {g['label']}" for g in per_group)
summary = (f"{name} test across {k} groups of {g_name} (n = {n}): {symbol}{dfs} = {r['statistic']:.3f}, {cs.fmt_p(p)}. "
+ (f"The {what} differ" if p < 0.05 else f"No evidence that the {what} differ") + f". Mean directions: {means}.")
if test == "rao":
summary += f" Dispersions: Q = {r['dispersion_q']:.3f}, {cs.fmt_p(r['dispersion_p'])}."
chart_roles = {"angle": cs.col(a_name, np.asarray(chart_angles)[:5000], "numeric"),
"group": cs.col(g_name, labels[:5000], levels=levels)}
cs.publish({
"method": "circular.groups",
"methodVersion": "1.0.1",
"title": "Comparing directions between groups",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"{name}: {symbol}{dfs} = {cs.fmt_num(r['statistic'])}, {cs.fmt_p(p)}",
"statistics": [{"key": "statistic", "label": f"{name} {symbol}", "value": r["statistic"]},
{"key": "p", "label": "p", "value": p, "format": "p"}],
"tables": [{"key": "groups", "title": "Directions by group",
"columns": [{"key": "group", "label": "Group", "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "label", "label": "Mean direction", "type": "string"}, {"key": "mean", "label": f"Mean ({disp_units})", "type": "number"},
{"key": "rbar", "label": "R̄", "type": "number"}, {"key": "kappa", "label": "κ", "type": "number"},
{"key": "circ_sd", "label": f"Circular SD ({disp_units})", "type": "number"}],
"rows": per_group}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"p-value: {how}."
+ (" Watson–Williams uses K = 1 + 3/(8κ̂) with κ̂ the von Mises MLE of the combined sample." if test == "watson_williams" else "")
+ (" Uniform scores use average ranks for ties." if test == "wheeler" else "")],
"values": values,
"charts": [cs.chart("rose", "rose-diagram", f"{a_name} by {g_name}", chart_roles, chart_controls),
cs.chart("dots", "circular-dot", f"{a_name} by {g_name}", chart_roles, chart_controls)],
})
What did you actually learn?
ReflectSuppose Watson–Williams is significant, Wallraff is significant too, and rose diagrams show one group wide and flat.
What would you tell a colleague who says "the groups fly in different directions"? Draft two sentences: one for direction, one for spread.
Check your understanding
CheckpointCheck yourself
Your two groups have very different concentrations. What should you do with Watson–Williams?
Show the answer
Answer: b
The F approximation assumes a common concentration. A rank-based test sidesteps that, and spread is often part of the finding.
Check yourself
You want to know whether one group is more scattered than another, not whether it points elsewhere. Which test fits?
Show the answer
Answer: c
Wallraff compares angular distances from each group's own direction, or from a common direction you set.
Check yourself
With 999 permutations, what is the smallest p-value you can get from ? Give three decimals.
Show the answer
Answer: 0.001
. Set more permutations when you need finer resolution.
Do it in CodeSplash
In the appIn Analyze, search for "Comparing directions". Choose Test for your question, and look at the rose diagram for each group before you read any p-value.
Recap
Recap- Match the test to the question: direction, spread or the whole distribution.
- Watson–Williams assumes common, reasonably high concentration.
- Report direction and spread together, since a difference in one can pose as the other.
Concepts in this lesson