ADirections & cycles · circular.groups
Comparing directions between groups (Watson–Williams, U², Wheeler, Wallraff, Rao)
Do two or more groups differ in their typical direction, their spread, or the whole distribution of directions?
Two- and k-sample tests for angles: Watson–Williams F for a common mean direction, Watson's two-sample U² and the Mardia–Watson–Wheeler uniform-scores test for any difference, Wallraff's test for equal angular spread, and Rao's tests for equal polar vectors and dispersions — with permutation p-values.
A real result
Example “Watson williams pigeons”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Watson–Williams: F(2, 63) = 13.90, p < .001
- Watson–Williams F
- 13.903
- 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
- Concentrated angles (κ ≥ 2) — Pooled κ = 2.05.
- Equal concentration — Wallraff test of equal dispersion p = .003; the groups differ in spread, so a mean-direction F test is unreliable.
- 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. Watson–Williams uses K = 1 + 3/(8κ̂) with κ̂ the von Mises MLE of the combined sample.
Watson–Williams: F(2, 63) = 13.90, p < .001
- Watson–Williams F
- 13.903
- p
- < .001
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Concentrated angles (κ ≥ 2) — Pooled κ = 2.05.
- Equal concentration — Wallraff test of equal dispersion p = .003; the groups differ in spread, so a mean-direction F test is unreliable.
- 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. Watson–Williams uses K = 1 + 3/(8κ̂) with κ̂ the von Mises MLE of the combined sample.
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
- Watson williams pigeonsci_pigeons · angle: bearing · group: group
- Watson williams permutationci_pigeons · angle: bearing · group: group
- Watson u2 seasonsci_wind · angle: direction · group: season
- Watson u2 permutationci_wind · angle: direction · group: season
- Wheeler pigeonsci_pigeons · angle: bearing · group: group
- Wheeler two groupsci_hours · angle: hour · group: channel
- Wallraff pigeonsci_pigeons · angle: bearing · group: group
- Wallraff home 90ci_pigeons · angle: bearing · group: group
In the guides
Tests from the statistics guide this method runs
What you need
- Direction or timenumeric / temporal · 1 column
- Angles, clock times, weekdays, months or timestamps.
- Groupscategorical / boolean · 1 column · 2–12 levels
- The groups to compare (e.g. treatment, season, site).
Choices you make
hypothesis
- Testdefault watson_williams
Watson–Williams compares mean directions (needs similar spread); the others also detect differences in spread or shape.
- Watson–Williams (mean direction)(default) — The circular analogue of one-way ANOVA: von Mises samples with equal, fairly high concentration (κ ≥ 2).
- Rao (polar vectors and dispersions) — Large-sample tests that allow each group its own spread; also tests equal dispersions.
- Watson two-sample U² — Nonparametric, two groups: any difference in location or shape.
- Mardia–Watson–Wheeler (uniform scores) — Rank-based, any number of groups; no von Mises assumption.
- Wallraff (angular spread) — Compares how far each angle lies from its group's mean direction (Kruskal–Wallis on the distances).
- Common direction for distancesdefault —
Measure spread around a stated direction (e.g. home) instead of each group's own mean.
options
- Angles are indefault degrees
How the column measures direction. Timestamps are placed in their daily, weekly or yearly cycle (UTC).
- Degrees (0–360)(default) — Compass bearings, wind directions, orientations.
- Radians (0–2π) — Reads values as radians from 0 to 2π; pick it for angles from math libraries.
- Hours of the day (0–24) — Clock times as decimal hours; 23:30 and 00:30 are an hour apart.
- Day of the week (1 = Monday … 7) — Reads values as weekdays, 1 = Monday to 7; pick it for weekly cycles.
- Month (1–12) — December and January are neighbors.
- Day of the year (1–366) — Reads values as day of the year, 1 to 366; pick it for seasonal cycles.
- Another cycle (set the period) — Any repeating scale: phase of a 28-day cycle, tide hours …
- Time of day — Position within the day (UTC).
- Day and time of the week — Monday 00:00 is the start of the cycle (UTC).
- Time of year — Fraction of the calendar year (leap years have 366 days).
- Value of one full turndefault 28
The scale value that brings you back to the start (e.g. 28 for a 28-day cycle).
- Axial data (0° and 180° are the same)default off
Orientations without a head or tail: angles are doubled before testing.
statistics
- p-valuedefault approximate
How the p-value is computed: a large-sample formula, or by permutation or simulation (slower, fewer assumptions).
- Asymptotic(default) — F, χ² or the limiting U² distribution.
- Permutation — Shuffles the group labels — reliable with small groups (exchangeable groups assumed).
- Permutationsdefault 9999
Number of random permutations behind the p-value. More gives a more precise p-value; results are seeded.
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.
Concentrated angles (κ ≥ 2)
Watson–Williams' F approximation needs fairly concentrated von Mises samples.
- If violated → Uniform-scores test — The Mardia–Watson–Wheeler test uses only the order of the angles round the circle, so it needs no von Mises shape or concentration. Changes the question: Tests any difference between the distributions, not only the mean direction.
Equal concentration
Watson–Williams compares mean directions assuming a common κ (Wallraff test).
- If violated → Rao's test of polar vectors — Gives each group its own covariance of (cos θ, sin θ), so unequal spreads do not distort the comparison of directions.
Independent angles
One angle per subject; groups independent.
What it reports
- Tests: The groups differ in direction
- 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.
- 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.
- df1
- How much independent information is left to estimate variability after fitting the model.
- df2
- How much independent information is left to estimate variability after fitting the model.
- kappa_pooled
- The von Mises distribution's concentration; 0 is uniform, about 2 is moderately clustered, above 10 very tight.
- correction
- Small-sample factor K = 1 + 3/(8κ̂) that multiplies the Watson–Williams F. Empty for the other tests.
- dispersion_q
- Rao's χ² statistic for equal dispersions across groups, on k − 1 df. Larger means the spreads differ more; empty for other tests.
- dispersion_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- p_asymptotic
- How surprising your data would be if the null hypothesis were true, as a probability.
- n_perm
- How many independent units the analysis used; it sets precision and power.
- center
- The stated direction Wallraff's test measures distances from, in the data's units. Empty when each group's own mean is used.
Per group, level or term: mean_direction[<group>], rbar[<group>], n[<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
- Watson–Williams uses the exact von Mises MLE of κ from the combined sample; R's circular::watson.williams.test uses the closed-form approximation of A₁⁻¹, so F differs in the third or fourth digit.
- The Watson two-sample U² p-value comes from the limiting distribution (or permutation); circular::watson.two.test reports a range from Zar's table.
The exact script CodeSplash ran for example “Watson williams pigeons” · 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 632d4b7419c12a5a
# 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 = "watson_williams"
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)],
})
The exact script CodeSplash ran for example “Watson williams pigeons” · 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 632d4b7419c12a5a
# 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 <- "watson_williams"
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))
))
Sources
- Mardia, K. V., & Jupp, P. E. (2000). Directional Statistics. Wiley, §7.4, §8.3.
- Zar, J. H. (2010). Biostatistical Analysis (5th ed.), ch. 27.
- Wallraff, H. G. (1979). Goal-oriented and compass-oriented movements of displaced homing pigeons after confinement in differentially shielded aviaries. Behavioral Ecology and Sociobiology, 5, 201–225.
- Rao, J. S. (1967). Large sample tests for the homogeneity of angular data. Sankhyā B, 28, 172–174.
From the CodeSplash method registry · circular.groups v1.0.1.