Skip to content

BCompare groups · nonparam.friedman

Friedman test (repeated measures, ranks)

Do three or more conditions measured on the same subjects differ in location?

Ranks the conditions within each subject and tests whether the mean ranks differ (tie-corrected χ², plus the Iman–Davenport F). Reports Kendall's W and pairwise comparisons by Conover's test or Wilcoxon signed-rank tests with a multiple-comparison adjustment. Data in long format. The same dialog runs the rest of the blocked-design family: Quade's test, Page's L for an expected order, Durbin's test for balanced incomplete blocks, Skillings–Mack for subjects with missing conditions, and Mack–Skillings or Gore when cells hold several observations.

Verified in Python and R Python and R agree to 10 decimals Seeded Also called Quade test, Page test, Page's L test…

A real result

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

Friedman testRecorded · Python and R agreeRecorded 2026-11-25 · 38 values compared
R

χ²(2, N = 22) = 11.14, p = .004, W = .25

χ²
11.143
df
2
p
.004
Iman–Davenport F
7.122
p (Iman–Davenport)
.002

Effect size

  • Kendall's W 0.2532

Plots

time by base method per playerHow did each subject change across conditions or time points?
View data
base methodplayertime
Round Outp015.400
Narrow Anglep015.500
Wide Anglep015.550
Round Outp025.850
Narrow Anglep025.700
Wide Anglep025.750
Round Outp035.200
Narrow Anglep035.600
Wide Anglep035.500
Round Outp045.550
Narrow Anglep045.500
Wide Anglep045.400
Round Outp055.900
Narrow Anglep055.850
Wide Anglep055.700
Round Outp065.450
Narrow Anglep065.550
Wide Anglep065.600
Round Outp075.400
Narrow Anglep075.400
Wide Anglep075.350
Round Outp085.450
Narrow Anglep085.500
Wide Anglep085.350
Round Outp095.250
Narrow Anglep095.150
Wide Anglep095
Round Outp105.850
Narrow Anglep105.800
Wide Anglep105.700
Round Outp115.250
Narrow Anglep115.200
Wide Anglep115.100
Round Outp125.650
Narrow Anglep125.550
Wide Anglep125.450
Round Outp135.600
Narrow Anglep135.350
Wide Anglep135.450
Round Outp145.050
Narrow Anglep145
Wide Anglep144.950
Round Outp155.500
Narrow Anglep155.500
Wide Anglep155.400
Round Outp165.450
Narrow Anglep165.550
Wide Anglep165.500
Round Outp175.550
Narrow Anglep175.550
Wide Anglep175.350
Round Outp185.450
Narrow Anglep185.500
Wide Anglep185.550
Round Outp195.500
Narrow Anglep195.450
Wide Anglep195.250
Round Outp205.650
Narrow Anglep205.600
Wide Anglep205.400

First 60 of 66 rows.

Assumptions

  • Complete subjects — 22 subjects have a value for every condition.
  • Ties within subjects — 4 subject(s) have tied values; the statistic is tie-corrected.
  • Design layout — Complete design: 22 subjects × 3 conditions, one value per cell.

Mean ranks

base methodnMedianMean rank
Round Out225.5002.409
Narrow Angle225.5252.136
Wide Angle225.4501.455

Pairwise comparisons (Conover)

ContrastConover tpp adj.
Round Out - Narrow Angle1.047.301.301
Round Out - Wide Angle3.664< .001.002
Narrow Angle - Wide Angle2.617.012.025
  • 3 conditions of base method ranked within each of 22 subjects (Friedman test).
Python

χ²(2, N = 22) = 11.14, p = .004, W = .25

χ²
11.143
df
2
p
.004
Iman–Davenport F
7.122
p (Iman–Davenport)
.002

Effect size

  • Kendall's W 0.2532

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

Assumptions

  • Complete subjects — 22 subjects have a value for every condition.
  • Ties within subjects — 4 subject(s) have tied values; the statistic is tie-corrected.
  • Design layout — Complete design: 22 subjects × 3 conditions, one value per cell.

Mean ranks

base methodnMedianMean rank
Round Out225.5002.409
Narrow Angle225.5252.136
Wide Angle225.4501.455

Pairwise comparisons (Conover)

ContrastConover tpp adj.
Round Out - Narrow Angle1.047.301.301
Round Out - Wide Angle3.664< .001.002
Narrow Angle - Wide Angle2.617.012.025
  • 3 conditions of base method ranked within each of 22 subjects (Friedman test).

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

  • Roundingrounding_times · condition: base method · outcome: time · subject: player
  • Co2 wilcoxonco2_long · condition: conc · outcome: uptake · subject: plant
  • Messy no posthocrounding_messy · condition: base method · outcome: time · subject: player
  • Nemenyic3_page · condition: dose · outcome: response · subject: subject
  • Exact pairsc3_page · condition: dose · outcome: response · subject: subject
  • Quade storesc3_store_brand · condition: brand · outcome: sold · subject: store
  • Quade permutationc3_store_brand · condition: brand · outcome: sold · subject: store
  • Page exactc3_page · condition: dose · outcome: response · subject: subject

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • More than two repeated measures: RM ANOVA, Friedman · Statistics Guide · B — Compare groups
  • Robust, permutation and exact methods · Statistics Guide · Step 3 — If assumptions are violated
  • Multiple comparisons · Statistics Guide · Additional considerations
  • Non-parametric alternatives · Statistics Guide · Additional considerations

What you need

Subject IDcategorical · 1 column
Identifies the subject (or block) measured under every condition.
Condition (within)categorical · 1 column · 3–20 levels
The within-subject factor: each subject is measured under every condition.
Outcomenumeric · 1 column
The numeric variable you are analyzing.

Choices you make

hypothesis

Testdefault friedman

Which blocked-design rank test to run. Automatic picks from the layout: complete or incomplete subjects, one or several values per cell.

  • Automatic (from the design) — Friedman for complete subjects, Durbin for a balanced incomplete design, Skillings–Mack for other gaps, Mack–Skillings or Gore when cells hold several values.
  • Friedman(default) — Ranks within each subject; every subject has every condition once.
  • Quade — Weights each subject by how spread out its values are; often more powerful than Friedman with few conditions.
  • Durbin — Balanced incomplete design: every subject sees the same number of conditions, every condition the same number of subjects.
  • Skillings–Mack — Any pattern of missing conditions; keeps subjects with at least two conditions.
  • Mack–Skillings — Every subject × condition cell holds the same number of replicate measurements.
  • Gore — Cells hold different numbers of replicates (at least one each); large-sample χ².
Alternativedefault any

An expected order turns the test into Page's L trend test, which is more powerful when the order was stated before seeing the data.

  • Any difference(default) — Tests whether any condition differs; keep it unless you stated an expected order before seeing the data.
  • Increasing in the order below (Page's L) — One-sided: outcomes rise across the conditions in the stated order.
  • Decreasing in the order below (Page's L) — One-sided: outcomes fall across the conditions in the stated order.
Expected order (first → last)default —

Drag the conditions into the order you expected before looking at the data. Empty = the column's level order.

statistics

p-valuedefault auto

How the p-value is computed. Permutation reshuffles values within each subject using a seeded random stream (same result in Python and R).

  • Exact where available(default) — Exact for Page's L without ties (up to 12 conditions), large-sample otherwise.
  • Large-sample (χ², F or normal) — Uses the χ², F or normal approximation; fast, and fine with many subjects.
  • Exact (Page's L) — Page's exact distribution; falls back to large-sample with ties or more than 12 conditions.
  • Within-subject permutation (Monte Carlo) — Reshuffles values within each subject with a seeded stream; pick it for few subjects, and it matches in Python and R.
Permutationsdefault 1999

Monte Carlo reshuffles; more gives a more precise p-value (its standard error is about √(p(1−p)/n)).

posthoc

Pairwise comparisonsdefault on

After the overall test, compare each pair of groups, with p-values adjusted for the number of comparisons.

Pairwise testdefault conover

Follow-up comparisons of every pair of conditions. A choice that does not fit the test actually run is replaced by the one that does (noted on the result).

  • Conover (t on rank sums)(default) — Uses the Friedman residual variance; the usual choice after a Friedman test.
  • Nemenyi (studentized range, single step) — Compares mean ranks against the studentized range; controls the familywise error rate by itself.
  • Exact rank-sum differences (Eisinga) — Exact p-values for differences of rank sums (no ties); then the adjustment below.
  • Wilcoxon signed-rank (normal approximation) — One paired test per pair, using the subjects that have both conditions.
  • Quade t comparisons — Conover's pairwise t on Quade's weighted rank sums.
  • Durbin t comparisons — Conover's pairwise t on rank sums in a balanced incomplete design.
Adjustmentdefault holm

How p-values are corrected for making several comparisons. Holm limits any false alarm; BH limits the share of false discoveries.

  • Holm(default) — Controls the chance of any false positive and always finds at least as much as Bonferroni; a good default.
  • Bonferroni — Multiplies each p by the number of tests; the plainest and strictest control, best for a few comparisons.
  • Benjamini–Hochberg (FDR) — Controls the expected share of false positives among the findings; pick it when screening many comparisons.
  • None — Reports raw p-values; use it for one planned comparison, or say plainly that the results are exploratory.

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.

  • Complete subjects

    Subjects missing a condition are left out by Friedman, Quade and Page; duplicate cells are averaged.

    • If violated → Skillings–Mack test — Keeps every subject with at least two conditions instead of dropping subjects with a missing condition.
  • Ties within subjects

    Tied values share their mean rank; the statistic is tie-corrected. Exact p-values assume no ties.

  • Design layout

    Which layout the data has (complete, incomplete, replicated) and whether the chosen test fits it.

What it reports

  • Tests: Differences among conditions (ranks)
chi2
A sum of squared, scaled differences between observed and expected counts or estimates.
df
How much independent information is left to estimate variability after fitting the model.
p
How surprising your data would be if the null hypothesis were true, as a probability.
f_id
The ratio of explained to unexplained variance, used by ANOVA and regression tests.
df1_id
How much independent information is left to estimate variability after fitting the model.
df2_id
How much independent information is left to estimate variability after fitting the model.
p_id
How surprising your data would be if the null hypothesis were true, as a probability.
kendall_w
Agreement among several raters' rankings, or the effect size for Friedman's test, from 0 to 1.
n_subjects
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.
n_dropped_subjects
How many independent units the analysis used; it sets precision and power.
test_used
Which test ran: friedman, quade, page, durbin, skillings_mack, mack_skillings or gore. Automatic picks one by the layout.
statistic
One test of "every component null holds" from several independent tests' p-values.
p_asymptotic
How surprising your data would be if the null hypothesis were true, as a probability.
f
The ratio of explained to unexplained variance, used by ANOVA and regression tests.
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.
page_l
Tests that outcomes rise (or fall) across conditions in an order stated in advance — a one-sided trend test for repeated measures.
page_z
An estimate in standard-error units, compared with the standard normal distribution.
page_method
Tests that outcomes rise (or fall) across conditions in an order stated in advance — a one-sided trend test for repeated measures.
durbin_f
The ratio of explained to unexplained variance, used by ANOVA and regression tests.
durbin_df2
How much independent information is left to estimate variability after fitting the model.
durbin_p_f
The ratio of explained to unexplained variance, used by ANOVA and regression tests.
replicates
Observations in each subject × condition cell for the Mack–Skillings test. Empty for the other tests.
n_obs
How many independent units the analysis used; it sets precision and power.
n_blocks_used
How many independent units the analysis used; it sets precision and power.
n_perm
How many independent units the analysis used; it sets precision and power.
perm_count
Builds the null distribution by reshuffling group labels, so it needs no distributional assumption.
missing_share
Values that were not recorded; how they went missing decides which fixes are safe.

Per group, level or term: mean_rank[<condition>], stat[<a> - <b>], p_adj[<a> - <b>]

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.

Python

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

# Friedman test (repeated measures, ranks)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method nonparam.friedman 1.1.2 · spec 18585f075e3cc9ae
# Dataset: rounding_times (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd
from scipy import stats

import codesplash as cs
from codesplash.stats import anova as csa
from codesplash.stats import blocked as blk
from codesplash.stats.padjust import p_adjust

# %% Data
df = pd.read_parquet("tests/parity/fixtures/rounding_times.parquet", columns=["player", "base method", "time"])
n_input = len(df)
df["player"] = pd.Categorical(df["player"], categories=["p01", "p02", "p03", "p04", "p05", "p06", "p07", "p08", "p09", "p10", "p11", "p12", "p13", "p14", "p15", "p16", "p17", "p18", "p19", "p20", "p21", "p22"])  # stored level order
df["base method"] = pd.Categorical(df["base method"], categories=["Round Out", "Narrow Angle", "Wide Angle"])  # stored level order
df = df.dropna(subset=["player", "base method", "time"])  # listwise deletion over the analysis columns
df["player"] = df["player"].cat.remove_unused_categories()
df["base method"] = df["base method"].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, ["player", "base method", "time"])  # infinite values stop the run (registry/errors.yaml)

# %% Layout: subjects (blocks) × conditions
subj, cond, y = "player", "base method", "time"
alternative = "any"
calibration = "auto"
seed = 42  # shared Wichmann–Hill stream: R draws the same permutations
design = blk.design(df[subj].cat.codes.to_numpy(np.int64), df[cond].cat.codes.to_numpy(np.int64),
                    len(df[subj].cat.categories), len(df[cond].cat.categories))
test = blk.choose("friedman", alternative, design)
label = blk.LABELS[test]
cells = df.groupby([subj, cond], observed=True)[y].size()
n_dup = int((cells > 1).sum())
wide = df.pivot_table(index=subj, columns=cond, values=y, aggfunc="mean", observed=False)
wide = wide.reindex(index=df[subj].cat.categories, columns=df[cond].cat.categories)
if n_dup and test not in ("mack_skillings", "gore"):
    warnings.append(f"{n_dup} subject × condition cell(s) had more than one value; their mean was used.")
n_dropped_subjects = 0
if test in ("friedman", "quade", "page"):
    complete = wide.dropna()
    n_dropped_subjects = int(wide.notna().any(axis=1).sum() - len(complete))
    if n_dropped_subjects:
        warnings.append(f"{n_dropped_subjects} subject(s) without a value for every condition were left out.")
    W = complete.to_numpy(dtype=float)
    subjects = [str(s) for s in complete.index]
else:
    W = wide.to_numpy(dtype=float)
    subjects = [str(s) for s in wide.index]
conditions = [str(c) for c in wide.columns]
n_subj, k = W.shape
if n_subj < 2:
    whom = "subjects with a value for every condition" if test in ("friedman", "quade", "page") else "subjects"
    cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"The {label} ({whom})", min=2, n=n_subj)
if k < 3:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=cond, min=3, k=k)
if len(np.unique(df[y].to_numpy(dtype=float))) < 2:  # every rank tied: the test statistic is 0/0
    cs.cs_error("CS_E_CONSTANT", column=y)
obs = ~np.isnan(W)
Y = W  # complete designs: no missing cells
# Long rows the permutation reshuffles within each subject (cell means; raw values for replicated designs)
if test in ("mack_skillings", "gore"):
    pb = df[subj].cat.codes.to_numpy(np.int64)
    pt = df[cond].cat.codes.to_numpy(np.int64)
    pv = df[y].to_numpy(dtype=float)
else:
    pb, pt = np.nonzero(obs)
    pv = W[pb, pt]
n_obs = int(len(pv))

# %% Test
chi2 = dfc = f_id = df1_id = df2_id = p_id = kendall_w = None
f = df1 = df2 = page_l = page_z = page_method = durbin_f = durbin_df2 = durbin_p_f = replicates = n_blocks_used = None
order_idx = None
if test in ("friedman", "quade", "page"):
    res = stats.friedmanchisquare(*Y.T)  # tie-corrected χ² (R: friedman.test)
    fr_chi2 = float(res.statistic)
    kendall_w = fr_chi2 / (n_subj * (k - 1))
if test == "friedman":
    chi2, p_asym = fr_chi2, float(res.pvalue)
    dfc = k - 1
    df1_id, df2_id = k - 1, (k - 1) * (n_subj - 1)
    f_id = (n_subj - 1) * chi2 / (n_subj * (k - 1) - chi2)  # Iman–Davenport
    p_id = float(stats.f.sf(f_id, df1_id, df2_id))
    statistic = chi2
elif test == "quade":
    q = blk.quade(Y)
    f, df1, df2, p_asym = q["f"], q["df1"], q["df2"], q["p"]
    statistic = f
elif test == "page":
    order_names = None or conditions
    order_idx = [conditions.index(c) for c in order_names if c in conditions]
    order_idx += [j for j in range(k) if j not in order_idx]
    pg = blk.page(Y, order_idx, alternative, "asymptotic" if calibration == "permutation" else calibration)
    page_l, page_z, page_method = pg["l"], pg["z"], pg["method"]
    statistic = page_l
    p_asym = float(stats.norm.sf(page_z))
    p_page = pg["p"]
elif test == "durbin":
    du = blk.durbin(W)
    chi2, dfc, p_asym = du["chi2"], du["df"], du["p"]
    durbin_f, durbin_df2, durbin_p_f = du["f"], du["df2"], du["p_f"]
    statistic = chi2
elif test == "skillings_mack":
    sm = blk.skillings_mack(W)
    chi2, dfc, p_asym = sm["chi2"], sm["df"], sm["p"]
    n_blocks_used = sm["n_blocks_used"]
    statistic = chi2
else:
    fn = blk.mack_skillings if test == "mack_skillings" else blk.gore
    rr = fn(pb, pt, pv, len(df[subj].cat.categories), k)
    chi2, dfc, p_asym = rr["chi2"], rr["df"], rr["p"]
    replicates = rr.get("replicates")
    statistic = chi2
p = p_page if test == "page" else p_asym
n_perm = perm_count = None
if calibration == "permutation":
    pr = blk.permutation_p(test, pb, pt, pv, len(df[subj].cat.categories), k, int(1999), seed, order_idx, alternative)
    p, n_perm, perm_count = pr["p"], pr["n_perm"], pr["count"]
    page_method = "permutation" if test == "page" else page_method

# Mean within-subject ranks (joint ranks within the subject for replicated designs)
rank_sum = np.zeros(k)
rank_n = np.zeros(k)
for i in range(W.shape[0]):
    if test in ("mack_skillings", "gore"):
        m = pb == i
        if not m.any():
            continue
        np.add.at(rank_sum, pt[m], stats.rankdata(pv[m]))
        np.add.at(rank_n, pt[m], 1.0)
    else:
        o = np.flatnonzero(obs[i])
        rank_sum[o] += stats.rankdata(W[i, o])
        rank_n[o] += 1.0
mean_ranks = rank_sum / rank_n
ties = int(sum(len(np.unique(W[i, obs[i]])) < int(obs[i].sum()) for i in range(W.shape[0])))

# %% Pairwise comparisons
posthoc_requested = "conover"
posthoc_method = blk.pairwise_for(test, posthoc_requested) if True else None
pairs = []
if posthoc_method == "conover":
    _, _, conover = csa.friedman_conover(Y)  # Conover (1999): t on rank sums, df (n − 1)(k − 1)
    for i, j, t, dfe, praw in conover:
        pairs.append({"contrast": f"{conditions[i]} - {conditions[j]}", "stat": t, "df": dfe, "p": praw})
elif posthoc_method == "wilcoxon":
    for i in range(k):
        for j in range(i + 1, k):
            d = W[:, i] - W[:, j]
            d = d[~np.isnan(d)]  # subjects with both conditions
            nz = d[d != 0]  # zero differences dropped (R's default)
            if len(nz) == 0:
                pairs.append({"contrast": f"{conditions[i]} - {conditions[j]}", "stat": 0.0, "df": None, "p": 1.0})
                continue
            w = stats.wilcoxon(nz, zero_method="wilcox", correction=True, method="approx")  # tie-corrected normal
            v = float(stats.rankdata(np.abs(nz))[nz > 0].sum())  # V = sum of positive ranks (R's statistic)
            pairs.append({"contrast": f"{conditions[i]} - {conditions[j]}", "stat": v, "df": None, "p": float(w.pvalue)})
elif posthoc_method == "nemenyi":
    for i, j, qv, pv_ in blk.nemenyi(Y):
        pairs.append({"contrast": f"{conditions[i]} - {conditions[j]}", "stat": qv, "df": None, "p": pv_})
elif posthoc_method == "exact":
    for i, j, dv, pv_ in blk.exact_pairs(Y):
        pairs.append({"contrast": f"{conditions[i]} - {conditions[j]}", "stat": dv, "df": None, "p": pv_})
elif posthoc_method in ("quade_conover", "durbin_conover"):
    rows = blk.quade_pairs(Y) if posthoc_method == "quade_conover" else blk.durbin_pairs(W)
    for i, j, tv, dfe, pv_ in rows:
        pairs.append({"contrast": f"{conditions[i]} - {conditions[j]}", "stat": tv, "df": dfe, "p": pv_})
adjust = "single-step" if posthoc_method == "nemenyi" else "holm"
for row, pa in zip(pairs, [x["p"] for x in pairs] if posthoc_method == "nemenyi" else p_adjust([x["p"] for x in pairs], adjust)):
    row["p_adj"] = float(pa)
notes = []
if True and posthoc_method != posthoc_requested:
    notes.append(f"No standard pairwise follow-up exists for the {label}; no pairs were compared." if posthoc_method is None
                 else f"Pairwise comparisons use the test that fits the {label} ({posthoc_method.replace('_', ' ')}) instead of {posthoc_requested.replace('_', ' ')}.")

# %% Assumptions
if test in ("friedman", "quade", "page"):
    complete_row = {"key": "complete", "label": "Complete subjects", "status": "warn" if n_dropped_subjects else "pass",
                    "detail": f"{n_subj} subjects have a value for every condition" + (f"; {n_dropped_subjects} were left out." if n_dropped_subjects else ".")}
elif test in ("durbin", "skillings_mack"):
    complete_row = {"key": "complete", "label": "Complete subjects", "status": "pass",
                    "detail": f"Subjects with missing conditions are kept: {design['n_empty_cells']} empty subject × condition cell(s)."}
else:
    complete_row = {"key": "complete", "label": "Complete subjects", "status": "pass",
                    "detail": "Every subject has every condition (several values per cell)."}
exact_used = (test == "page" and page_method == "exact") or posthoc_method == "exact"
if ties:
    ties_row = {"key": "ties", "label": "Ties within subjects", "status": "warn" if posthoc_method == "exact" else "info",
                "detail": f"{ties} subject(s) have tied values; the statistic is tie-corrected."
                + (" The exact pairwise p-values assume no ties." if posthoc_method == "exact" else "")
                + (" Page's exact distribution assumes no ties, so the large-sample p-value is used." if test == "page" and calibration == "exact" else "")}
else:
    ties_row = {"key": "ties", "label": "Ties within subjects", "status": "pass", "detail": "No ties within subjects."}
if test in ("mack_skillings", "gore"):
    layout_detail = (f"Replicated complete design: {n_subj} subjects × {k} conditions, {replicates} values per cell." if test == "mack_skillings"
                     else f"Replicated complete design with unequal replicates ({n_obs} values); the Gore statistic is large-sample.")
elif test in ("durbin", "skillings_mack"):
    layout_detail = ("Balanced incomplete design: every subject has " if design["balanced_incomplete"] else "Incomplete design: ") + \
        (f"{du['block_size']} of {k} conditions; each condition appears in {du['replications']} subjects." if test == "durbin"
         else f"{n_blocks_used} of {n_subj} subjects have at least two conditions.")
else:
    layout_detail = f"Complete design: {n_subj} subjects × {k} conditions, one value per cell."
choice_note = f" Chosen automatically: {label}." if "friedman" == "auto" else ""
assumptions = [complete_row, ties_row, {"key": "layout", "label": "Design layout", "status": "pass", "detail": layout_detail + choice_note}]

# %% Result
values = {"chi2": chi2, "df": dfc, "p": p, "f_id": f_id, "df1_id": df1_id, "df2_id": df2_id, "p_id": p_id, "kendall_w": kendall_w,
          "n_subjects": n_subj, "k": k, "n_dropped_subjects": n_dropped_subjects, "test_used": test, "statistic": statistic,
          "p_asymptotic": p_asym, "f": f, "df1": df1, "df2": df2, "page_l": page_l, "page_z": page_z, "page_method": page_method,
          "durbin_f": durbin_f, "durbin_df2": durbin_df2, "durbin_p_f": durbin_p_f, "replicates": replicates, "n_obs": n_obs,
          "n_blocks_used": n_blocks_used, "n_perm": n_perm, "perm_count": perm_count}
for c, mr in zip(conditions, mean_ranks):
    values[f"mean_rank[{c}]"] = float(mr)
for row in pairs:
    values[f"stat[{row['contrast']}]"] = row["stat"]
    values[f"p_adj[{row['contrast']}]"] = row["p_adj"]
medians = [float(np.median(pv[pt == j])) for j in range(k)]
tables = [{"key": "descriptives", "title": "Mean ranks", "columns": [
    {"key": "condition", "label": cond, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
    {"key": "median", "label": "Median", "type": "number"}, {"key": "mean_rank", "label": "Mean rank", "type": "number"}],
    "rows": [{"condition": c, "n": int(rank_n[j]), "median": medians[j], "mean_rank": float(mean_ranks[j])} for j, c in enumerate(conditions)]}]
if pairs:
    stat_label = {"conover": "Conover t", "wilcoxon": "Wilcoxon V", "nemenyi": "q", "exact": "D (rank-sum difference)",
                  "quade_conover": "Quade t", "durbin_conover": "Durbin t"}[posthoc_method]
    title_m = {"conover": "Conover", "wilcoxon": "Wilcoxon signed-rank", "nemenyi": "Nemenyi, single step", "exact": "exact rank-sum differences",
               "quade_conover": "Quade t", "durbin_conover": "Durbin t"}[posthoc_method]
    tables.append({"key": "posthoc", "title": f"Pairwise comparisons ({title_m})",
                   "columns": [{"key": "contrast", "label": "Contrast", "type": "string"}, {"key": "stat", "label": stat_label, "type": "number"},
                               {"key": "p", "label": "p", "type": "pvalue"}, {"key": "p_adj", "label": "p adj.", "type": "pvalue"}],
                   "rows": pairs})
if test == "quade":
    stat_items = [{"key": "f", "label": "Quade F", "value": f}, {"key": "df1", "label": "df1", "value": df1}, {"key": "df2", "label": "df2", "value": df2}]
    summary = f"Quade F({df1}, {df2}) = {f:.2f}, {cs.fmt_p(p)}; Kendall's W = {kendall_w:.3f}."
    apa = f"F({df1}, {df2}) = {cs.fmt_num(f)}, {cs.fmt_p(p)}, W = {cs.fmt_num(kendall_w, leading_zero=False)}"
elif test == "page":
    stat_items = [{"key": "page_l", "label": "Page's L", "value": page_l}, {"key": "page_z", "label": "z", "value": page_z}]
    summary = f"Page's L = {page_l:.0f}, z = {page_z:.2f}, {cs.fmt_p(p)} ({page_method}); Kendall's W = {kendall_w:.3f}."
    apa = f"L = {page_l:.0f}, z = {cs.fmt_num(page_z)}, {cs.fmt_p(p)}, W = {cs.fmt_num(kendall_w, leading_zero=False)}"
else:
    stat_items = [{"key": "chi2", "label": "χ²", "value": chi2}, {"key": "df", "label": "df", "value": dfc}]
    summary = f"{label.replace(' test', '')} χ²({dfc}) = {chi2:.2f}, {cs.fmt_p(p)}" + (f"; Kendall's W = {kendall_w:.3f}." if kendall_w is not None else ".")
    apa = f"χ²({dfc}, N = {n_subj}) = {cs.fmt_num(chi2)}, {cs.fmt_p(p)}" + (f", W = {cs.fmt_num(kendall_w, leading_zero=False)}" if kendall_w is not None else "")
stat_items.append({"key": "p", "label": "p" + (" (permutation)" if calibration == "permutation" else " (exact)" if page_method == "exact" else ""), "value": p, "format": "p"})
if calibration == "permutation" or page_method == "exact":
    stat_items.append({"key": "p_asymptotic", "label": "p (large-sample)", "value": p_asym, "format": "p"})
if test == "friedman":
    stat_items += [{"key": "f_id", "label": "Iman–Davenport F", "value": f_id}, {"key": "p_id", "label": "p (Iman–Davenport)", "value": p_id, "format": "p"}]
if test == "durbin":
    stat_items += [{"key": "durbin_f", "label": "Durbin F", "value": durbin_f}, {"key": "durbin_p_f", "label": "p (F)", "value": durbin_p_f, "format": "p"}]
if n_perm:
    stat_items.append({"key": "n_perm", "label": "Permutations", "value": n_perm, "format": "integer"})
    notes.append(f"p-value from {n_perm} within-subject permutations (seed {seed}).")
if test == "page":
    notes.append(f"Expected order: {' → '.join(conditions[j] for j in order_idx)}, outcomes {alternative}.")
if calibration == "exact" and test != "page":
    notes.append(f"Exact p-values are available for Page's L only; the {label} uses its large-sample p-value.")
notes.insert(0, f"{k} conditions of {cond} ranked within each of {n_subj} subjects ({label}).")
effect_sizes = [{"key": "kendall_w", "label": "Kendall's W", "value": kendall_w, "method": "Friedman χ² / (n (k − 1)), tie-corrected"}] if kendall_w is not None else []
long_rows = [(subjects[i], conditions[j], W[i, j]) for i in range(W.shape[0]) for j in range(k) if obs[i, j]][:5000]
values["missing_share"] = n_dropped / n_input if n_input else 0.0  # consult-a-statistician input
cs.publish({
    "method": "nonparam.friedman",
    "methodVersion": "1.1.2",
    "title": label,
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n_subj,
    "summary": summary,
    "apa": apa,
    "statistics": stat_items,
    "tables": tables,
    "effectSizes": effect_sizes,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": notes,
    "values": values,
    "charts": [cs.chart("profiles", "paired-lines", f"{y} by {cond} per {subj}", {
        "subject": cs.col(subj, [x[0] for x in long_rows], "categorical"),
        "condition": cs.col(cond, [x[1] for x in long_rows], "categorical", levels=conditions),
        "value": cs.col(y, [float(x[2]) for x in long_rows], "numeric")}, controls={"means": False})],
})
R

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

# Friedman test (repeated measures, ranks)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method nonparam.friedman 1.1.2 · spec 18585f075e3cc9ae
# Dataset: rounding_times (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/rounding_times.parquet", col_select = c("player", "base method", "time")))
n_input <- nrow(df)
df[["player"]] <- factor(df[["player"]], levels = c("p01", "p02", "p03", "p04", "p05", "p06", "p07", "p08", "p09", "p10", "p11", "p12", "p13", "p14", "p15", "p16", "p17", "p18", "p19", "p20", "p21", "p22"))  # stored level order
df[["base method"]] <- factor(df[["base method"]], levels = c("Round Out", "Narrow Angle", "Wide Angle"))  # stored level order
df <- df[stats::complete.cases(df[c("player", "base method", "time")]), , 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("player", "base method", "time"))  # infinite values stop the run (registry/errors.yaml)

# %% Layout: subjects (blocks) x conditions
subj <- "player"
cond <- "base method"
y <- "time"
alternative <- "any"
calibration <- "auto"
seed <- 42  # shared Wichmann-Hill stream: Python draws the same permutations
design <- cs_blk_design(as.integer(df[[subj]]), as.integer(df[[cond]]), nlevels(df[[subj]]), nlevels(df[[cond]]))
test <- cs_blk_choose("friedman", alternative, design)
label <- cs_blk_labels[[test]]
cells <- table(df[[subj]], df[[cond]])
n_dup <- sum(cells > 1)
agg <- stats::aggregate(df[[y]], by = list(s = df[[subj]], c = df[[cond]]), FUN = mean)
wide <- matrix(NA_real_, nlevels(df[[subj]]), nlevels(df[[cond]]), dimnames = list(levels(df[[subj]]), levels(df[[cond]])))
wide[cbind(as.character(agg$s), as.character(agg$c))] <- agg$x
if (n_dup > 0 && !(test %in% c("mack_skillings", "gore"))) {
  warnings <- c(warnings, sprintf("%d subject × condition cell(s) had more than one value; their mean was used.", n_dup))
}
n_dropped_subjects <- 0L
if (test %in% c("friedman", "quade", "page")) {
  complete <- wide[stats::complete.cases(wide), , drop = FALSE]
  n_dropped_subjects <- sum(rowSums(!is.na(wide)) > 0) - nrow(complete)
  if (n_dropped_subjects > 0) warnings <- c(warnings, sprintf("%d subject(s) without a value for every condition were left out.", n_dropped_subjects))
  W <- unname(complete)
  subjects <- rownames(complete)
} else {
  W <- unname(wide)
  subjects <- rownames(wide)
}
conditions <- colnames(wide)
n_subj <- nrow(W)
k <- ncol(W)
if (n_subj < 2) {
  whom <- if (test %in% c("friedman", "quade", "page")) "subjects with a value for every condition" else "subjects"
  cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("The %s (%s)", label, whom), min = 2, n = n_subj)
}
if (k < 3) cs_error("CS_E_TOO_FEW_GROUPS", column = cond, min = 3, k = k)
if (length(unique(as.numeric(df[[y]]))) < 2) cs_error("CS_E_CONSTANT", column = y)  # every rank tied: the test statistic is 0/0
obs <- !is.na(W)
Y <- W
# Long rows the permutation reshuffles within each subject (cell means; raw values for replicated designs)
if (test %in% c("mack_skillings", "gore")) {
  pb <- as.integer(df[[subj]])
  pt <- as.integer(df[[cond]])
  pv <- as.numeric(df[[y]])
} else {
  idx <- which(t(obs), arr.ind = TRUE)  # row-major order, as Python's np.nonzero
  pb <- idx[, 2]
  pt <- idx[, 1]
  pv <- W[cbind(pb, pt)]
}
n_obs <- length(pv)

# %% Test
chi2 <- dfc <- f_id <- df1_id <- df2_id <- p_id <- kendall_w <- NA_real_
f <- df1 <- df2 <- page_l <- page_z <- durbin_f <- durbin_df2 <- durbin_p_f <- replicates <- n_blocks_used <- NA_real_
page_method <- NA_character_
order_idx <- NULL
if (test %in% c("friedman", "quade", "page")) {
  res <- friedman.test(Y)  # tie-corrected chi-squared
  fr_chi2 <- unname(res$statistic)
  kendall_w <- fr_chi2 / (n_subj * (k - 1))
}
if (test == "friedman") {
  chi2 <- fr_chi2
  p_asym <- res$p.value
  dfc <- k - 1
  df1_id <- k - 1
  df2_id <- (k - 1) * (n_subj - 1)
  f_id <- (n_subj - 1) * chi2 / (n_subj * (k - 1) - chi2)  # Iman-Davenport
  p_id <- pf(f_id, df1_id, df2_id, lower.tail = FALSE)
  statistic <- chi2
} else if (test == "quade") {
  q <- cs_blk_quade(Y)
  f <- q$f
  df1 <- q$df1
  df2 <- q$df2
  p_asym <- q$p
  statistic <- f
} else if (test == "page") {
  order_names <- NULL
  if (is.null(order_names) || !length(order_names)) order_names <- conditions
  order_idx <- match(order_names[order_names %in% conditions], conditions)
  order_idx <- c(order_idx, setdiff(seq_len(k), order_idx))
  pg <- cs_blk_page(Y, order_idx, alternative, if (calibration == "permutation") "asymptotic" else calibration)
  page_l <- pg$l
  page_z <- pg$z
  page_method <- pg$method
  statistic <- page_l
  p_asym <- stats::pnorm(page_z, lower.tail = FALSE)
  p_page <- pg$p
} else if (test == "durbin") {
  du <- cs_blk_durbin(W)
  chi2 <- du$chi2
  dfc <- du$df
  p_asym <- du$p
  durbin_f <- du$f
  durbin_df2 <- du$df2
  durbin_p_f <- du$p_f
  statistic <- chi2
} else if (test == "skillings_mack") {
  sm <- cs_blk_skillings_mack(W)
  chi2 <- sm$chi2
  dfc <- sm$df
  p_asym <- sm$p
  n_blocks_used <- sm$n_blocks_used
  statistic <- chi2
} else {
  fn <- if (test == "mack_skillings") cs_blk_mack_skillings else cs_blk_gore
  rr <- fn(pb, pt, pv, nlevels(df[[subj]]), k)
  chi2 <- rr$chi2
  dfc <- rr$df
  p_asym <- rr$p
  if (!is.null(rr$replicates)) replicates <- rr$replicates
  statistic <- chi2
}
p <- if (test == "page") p_page else p_asym
n_perm <- perm_count <- NA_real_
if (calibration == "permutation") {
  pr <- cs_blk_permutation_p(test, pb, pt, pv, nlevels(df[[subj]]), k, as.integer(1999), seed, order_idx, alternative)
  p <- pr$p
  n_perm <- pr$n_perm
  perm_count <- pr$count
  if (test == "page") page_method <- "permutation"
}

# Mean within-subject ranks (joint ranks within the subject for replicated designs)
rank_sum <- numeric(k)
rank_n <- numeric(k)
for (i in seq_len(nrow(W))) {
  if (test %in% c("mack_skillings", "gore")) {
    m <- pb == i
    if (!any(m)) next
    r_ <- rank(pv[m])
    tm <- pt[m]
    for (h in seq_along(r_)) {
      rank_sum[tm[h]] <- rank_sum[tm[h]] + r_[h]
      rank_n[tm[h]] <- rank_n[tm[h]] + 1
    }
  } else {
    o <- which(obs[i, ])
    rank_sum[o] <- rank_sum[o] + rank(W[i, o])
    rank_n[o] <- rank_n[o] + 1
  }
}
mean_ranks <- rank_sum / rank_n
ties <- sum(vapply(seq_len(nrow(W)), function(i) length(unique(W[i, obs[i, ]])) < sum(obs[i, ]), logical(1)))

# %% Pairwise comparisons
posthoc_requested <- "conover"
posthoc_method <- if (TRUE) cs_blk_pairwise_for(test, posthoc_requested) else NULL
pairs <- data.frame()
add_pair <- function(i, j, stat, p) data.frame(contrast = paste(conditions[i], "-", conditions[j]), stat = stat, p = p, stringsAsFactors = FALSE)
if (identical(posthoc_method, "conover")) {
  cv <- cs_friedman_conover(Y)  # Conover (1999): t on rank sums, df (n - 1)(k - 1)
  for (pr_ in cv$pairs) pairs <- rbind(pairs, add_pair(pr_$i, pr_$j, pr_$t, pr_$p))
} else if (identical(posthoc_method, "wilcoxon")) {
  for (i in seq_len(k - 1)) {
    for (j in (i + 1):k) {
      d <- W[, i] - W[, j]
      d <- d[!is.na(d)]  # subjects with both conditions
      nz <- d[d != 0]  # zero differences dropped (R's default)
      if (length(nz) == 0) {
        pairs <- rbind(pairs, add_pair(i, j, 0, 1))
        next
      }
      w <- wilcox.test(nz, exact = FALSE, correct = TRUE)  # tie-corrected normal approximation
      pairs <- rbind(pairs, add_pair(i, j, unname(w$statistic), w$p.value))
    }
  }
} else if (identical(posthoc_method, "nemenyi")) {
  for (x in cs_blk_nemenyi(Y)) pairs <- rbind(pairs, add_pair(x$i, x$j, x$q, x$p))
} else if (identical(posthoc_method, "exact")) {
  for (x in cs_blk_exact_pairs(Y)) pairs <- rbind(pairs, add_pair(x$i, x$j, x$d, x$p))
} else if (!is.null(posthoc_method) && posthoc_method %in% c("quade_conover", "durbin_conover")) {
  rows <- if (posthoc_method == "quade_conover") cs_blk_quade_pairs(Y) else cs_blk_durbin_pairs(W)
  for (x in rows) pairs <- rbind(pairs, add_pair(x$i, x$j, x$t, x$p))
}
adjust <- if (identical(posthoc_method, "nemenyi")) "single-step" else "holm"
if (nrow(pairs) > 0) pairs$p_adj <- if (identical(posthoc_method, "nemenyi")) pairs$p else cs_p_adjust(pairs$p, adjust)
notes <- character()
if (TRUE && !identical(posthoc_method, posthoc_requested)) {
  notes <- c(notes, if (is.null(posthoc_method)) sprintf("No standard pairwise follow-up exists for the %s; no pairs were compared.", label)
                    else sprintf("Pairwise comparisons use the test that fits the %s (%s) instead of %s.", label,
                                 gsub("_", " ", posthoc_method), gsub("_", " ", posthoc_requested)))
}

# %% Assumptions
complete_row <- if (test %in% c("friedman", "quade", "page")) {
  list(key = "complete", label = "Complete subjects", status = if (n_dropped_subjects > 0) "warn" else "pass",
       detail = paste0(sprintf("%d subjects have a value for every condition", n_subj),
                       if (n_dropped_subjects > 0) sprintf("; %d were left out.", n_dropped_subjects) else "."))
} else if (test %in% c("durbin", "skillings_mack")) {
  list(key = "complete", label = "Complete subjects", status = "pass",
       detail = sprintf("Subjects with missing conditions are kept: %d empty subject × condition cell(s).", design$n_empty_cells))
} else {
  list(key = "complete", label = "Complete subjects", status = "pass", detail = "Every subject has every condition (several values per cell).")
}
is_exact_ph <- identical(posthoc_method, "exact")
ties_row <- if (ties > 0) {
  list(key = "ties", label = "Ties within subjects", status = if (is_exact_ph) "warn" else "info",
       detail = paste0(sprintf("%d subject(s) have tied values; the statistic is tie-corrected.", ties),
                       if (is_exact_ph) " The exact pairwise p-values assume no ties." else "",
                       if (test == "page" && calibration == "exact") " Page's exact distribution assumes no ties, so the large-sample p-value is used." else ""))
} else list(key = "ties", label = "Ties within subjects", status = "pass", detail = "No ties within subjects.")
layout_detail <- if (test %in% c("mack_skillings", "gore")) {
  if (test == "mack_skillings") sprintf("Replicated complete design: %d subjects × %d conditions, %d values per cell.", n_subj, k, as.integer(replicates))
  else sprintf("Replicated complete design with unequal replicates (%d values); the Gore statistic is large-sample.", n_obs)
} else if (test %in% c("durbin", "skillings_mack")) {
  paste0(if (design$balanced_incomplete) "Balanced incomplete design: every subject has " else "Incomplete design: ",
         if (test == "durbin") sprintf("%d of %d conditions; each condition appears in %d subjects.", as.integer(du$block_size), k, as.integer(du$replications))
         else sprintf("%d of %d subjects have at least two conditions.", as.integer(n_blocks_used), n_subj))
} else sprintf("Complete design: %d subjects × %d conditions, one value per cell.", n_subj, k)
choice_note <- if ("friedman" == "auto") sprintf(" Chosen automatically: %s.", label) else ""
assumptions <- list(complete_row, ties_row, list(key = "layout", label = "Design layout", status = "pass", detail = paste0(layout_detail, choice_note)))

# %% Result
na_null <- function(x) if (length(x) == 0 || (length(x) == 1 && is.na(x))) NA else x
values <- list(chi2 = na_null(chi2), df = na_null(dfc), p = p, f_id = na_null(f_id), df1_id = na_null(df1_id), df2_id = na_null(df2_id),
               p_id = na_null(p_id), kendall_w = na_null(kendall_w), n_subjects = n_subj, k = k, n_dropped_subjects = n_dropped_subjects,
               test_used = test, statistic = statistic, p_asymptotic = p_asym, f = na_null(f), df1 = na_null(df1), df2 = na_null(df2),
               page_l = na_null(page_l), page_z = na_null(page_z), page_method = na_null(page_method), durbin_f = na_null(durbin_f),
               durbin_df2 = na_null(durbin_df2), durbin_p_f = na_null(durbin_p_f), replicates = na_null(replicates), n_obs = n_obs,
               n_blocks_used = na_null(n_blocks_used), n_perm = na_null(n_perm), perm_count = na_null(perm_count))
for (j in seq_len(k)) values[[sprintf("mean_rank[%s]", conditions[j])]] <- mean_ranks[[j]]
for (r_ in seq_len(nrow(pairs))) {
  values[[sprintf("stat[%s]", pairs$contrast[r_])]] <- pairs$stat[r_]
  values[[sprintf("p_adj[%s]", pairs$contrast[r_])]] <- pairs$p_adj[r_]
}
medians <- vapply(seq_len(k), function(j) stats::median(pv[pt == j]), numeric(1))
tables <- list(list(key = "descriptives", title = "Mean ranks",
                    columns = list(list(key = "condition", label = cond, type = "string"), list(key = "n", label = "n", type = "integer"),
                                   list(key = "median", label = "Median", type = "number"), list(key = "mean_rank", label = "Mean rank", type = "number")),
                    rows = data.frame(condition = conditions, n = as.integer(rank_n), median = medians, mean_rank = mean_ranks,
                                      stringsAsFactors = FALSE)))
if (nrow(pairs) > 0) {
  stat_label <- c(conover = "Conover t", wilcoxon = "Wilcoxon V", nemenyi = "q", exact = "D (rank-sum difference)",
                  quade_conover = "Quade t", durbin_conover = "Durbin t")[[posthoc_method]]
  title_m <- c(conover = "Conover", wilcoxon = "Wilcoxon signed-rank", nemenyi = "Nemenyi, single step", exact = "exact rank-sum differences",
               quade_conover = "Quade t", durbin_conover = "Durbin t")[[posthoc_method]]
  tables[[2]] <- list(key = "posthoc", title = sprintf("Pairwise comparisons (%s)", title_m),
                      columns = list(list(key = "contrast", label = "Contrast", type = "string"),
                                     list(key = "stat", label = stat_label, type = "number"),
                                     list(key = "p", label = "p", type = "pvalue"), list(key = "p_adj", label = "p adj.", type = "pvalue")),
                      rows = pairs)
}
w_txt <- if (!is.na(kendall_w)) sprintf("; Kendall's W = %.3f.", kendall_w) else "."
w_apa <- if (!is.na(kendall_w)) paste0(", W = ", cs_fmt_num(kendall_w, leading_zero = FALSE)) else ""
if (test == "quade") {
  stat_items <- list(list(key = "f", label = "Quade F", value = f), list(key = "df1", label = "df1", value = df1), list(key = "df2", label = "df2", value = df2))
  summary <- sprintf("Quade F(%d, %d) = %.2f, %s%s", as.integer(df1), as.integer(df2), f, cs_fmt_p(p), w_txt)
  apa <- sprintf("F(%d, %d) = %s, %s%s", as.integer(df1), as.integer(df2), cs_fmt_num(f), cs_fmt_p(p), w_apa)
} else if (test == "page") {
  stat_items <- list(list(key = "page_l", label = "Page's L", value = page_l), list(key = "page_z", label = "z", value = page_z))
  summary <- sprintf("Page's L = %.0f, z = %.2f, %s (%s)%s", page_l, page_z, cs_fmt_p(p), page_method, w_txt)
  apa <- sprintf("L = %.0f, z = %s, %s%s", page_l, cs_fmt_num(page_z), cs_fmt_p(p), w_apa)
} else {
  stat_items <- list(list(key = "chi2", label = "χ²", value = chi2), list(key = "df", label = "df", value = dfc))
  summary <- sprintf("%s χ²(%d) = %.2f, %s%s", sub(" test$", "", label), as.integer(dfc), chi2, cs_fmt_p(p), w_txt)
  apa <- sprintf("χ²(%d, N = %d) = %s, %s%s", as.integer(dfc), n_subj, cs_fmt_num(chi2), cs_fmt_p(p), w_apa)
}
p_lab <- if (calibration == "permutation") "p (permutation)" else if (identical(page_method, "exact")) "p (exact)" else "p"
stat_items[[length(stat_items) + 1]] <- list(key = "p", label = p_lab, value = p, format = "p")
if (calibration == "permutation" || identical(page_method, "exact")) {
  stat_items[[length(stat_items) + 1]] <- list(key = "p_asymptotic", label = "p (large-sample)", value = p_asym, format = "p")
}
if (test == "friedman") {
  stat_items <- c(stat_items, list(list(key = "f_id", label = "Iman–Davenport F", value = f_id),
                                   list(key = "p_id", label = "p (Iman–Davenport)", value = p_id, format = "p")))
}
if (test == "durbin") {
  stat_items <- c(stat_items, list(list(key = "durbin_f", label = "Durbin F", value = durbin_f),
                                   list(key = "durbin_p_f", label = "p (F)", value = durbin_p_f, format = "p")))
}
if (!is.na(n_perm)) {
  stat_items[[length(stat_items) + 1]] <- list(key = "n_perm", label = "Permutations", value = n_perm, format = "integer")
  notes <- c(notes, sprintf("p-value from %d within-subject permutations (seed %d).", as.integer(n_perm), as.integer(seed)))
}
if (test == "page") notes <- c(notes, sprintf("Expected order: %s, outcomes %s.", paste(conditions[order_idx], collapse = " → "), alternative))
if (calibration == "exact" && test != "page") notes <- c(notes, sprintf("Exact p-values are available for Page's L only; the %s uses its large-sample p-value.", label))
notes <- c(sprintf("%d conditions of %s ranked within each of %d subjects (%s).", k, cond, n_subj, label), notes)
effect_sizes <- if (!is.na(kendall_w)) list(list(key = "kendall_w", label = "Kendall's W", value = kendall_w,
                                                   method = "Friedman χ² / (n (k − 1)), tie-corrected")) else list()
lr <- which(t(obs), arr.ind = TRUE)
keep <- seq_len(min(nrow(lr), 5000))
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0  # consult-a-statistician input
cs_publish(list(
  method = "nonparam.friedman",
  methodVersion = "1.1.2",
  title = label,
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n_subj,
  summary = summary,
  apa = apa,
  statistics = stat_items,
  tables = tables,
  effectSizes = effect_sizes,
  assumptions = assumptions,
  warnings = warnings,
  notes = as.list(notes),
  values = values,
  charts = list(cs_chart("profiles", "paired-lines", sprintf("%s by %s per %s", y, cond, subj), list(
    subject = cs_col(subj, subjects[lr[keep, 2]], "categorical"),
    condition = cs_col(cond, conditions[lr[keep, 1]], "categorical", levels = conditions),
    value = cs_col(y, W[cbind(lr[keep, 2], lr[keep, 1])], "numeric")), controls = list(means = FALSE)))
))

Sources

  • Friedman, M. (1937). The use of ranks to avoid the assumption of normality implicit in the analysis of variance. JASA, 32, 675–701.
  • Iman, R. L., & Davenport, J. M. (1980). Approximations of the critical region of the Friedman statistic. Communications in Statistics, 9, 571–595.
  • Conover, W. J. (1999). Practical nonparametric statistics (3rd ed.), pp. 369–389 (Quade, Durbin and their pairwise comparisons).
  • Quade, D. (1979). Using weighted rankings in the analysis of complete blocks with additive block effects. JASA, 74, 680–683.
  • Page, E. B. (1963). Ordered hypotheses for multiple treatments: a significance test for linear ranks. JASA, 58, 216–230.
  • Durbin, J. (1951). Incomplete blocks in ranking experiments. British Journal of Psychology, 4, 85–90.
  • Skillings, J. H., & Mack, G. A. (1981). On the use of a Friedman-type statistic in balanced and unbalanced block designs. Technometrics, 23, 171–177.
  • Mack, G. A., & Skillings, J. H. (1980). A Friedman-type rank test for main effects in a two-factor ANOVA. JASA, 75, 947–951.
  • Gore, A. P. (1975). Some nonparametric tests and selection procedures for main effects in two-way layouts. Annals of the Institute of Statistical Mathematics, 27, 487–500.
  • Eisinga, R., Heskes, T., Pelzer, B., & Te Grotenhuis, M. (2017). Exact p-values for pairwise comparison of Friedman rank sums. BMC Bioinformatics, 18, 68.

From the CodeSplash method registry · nonparam.friedman v1.1.2.