Blocks without normality: Friedman and Quade
Rank within each subject and test the rank sums. Friedman treats every subject alike; Quade gives more weight to subjects who vary more.
What runs in CodeSplash
- STAT034Friedman test Runs in CodeSplash
- STAT035Quade test Runs in CodeSplash
- Friedman test (repeated measures, ranks) Verified in Python and R
You will be able to
- Compute Friedman's statistic from within-subject ranks
- Explain Quade's block weighting and when it helps
- Choose a pairwise follow-up for a blocked rank test
Rank inside each block
ReadA blockBlockingGrouping observations that share a source (a subject, a batch) so their differences cancel out. groups measurements that belong together: a subject, a store, a batch. Friedman's test ranks the conditions within each block, so differences between blocks can't matter.
If the conditions are interchangeable, each one should get an average rank of in the long run:
Predict the agreement
PredictPredict first
Twenty-two players each ran bases three ways. Kendall's measures how much players agree on the ranking of methods: 0 means no agreement and 1 means complete agreement.
Would you expect agreement to be strong, given a small difference in times? Drag to your guess.
Make your guess between 0 and 1 Kendall's W, then reveal.
Reveal
= 0.25. Players agree only weakly on the order, even though the test detects a difference: (2) = 11.14, p = .004.
Read the result
Readχ²(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
View data
| base method | player | time |
|---|---|---|
| Round Out | p01 | 5.400 |
| Narrow Angle | p01 | 5.500 |
| Wide Angle | p01 | 5.550 |
| Round Out | p02 | 5.850 |
| Narrow Angle | p02 | 5.700 |
| Wide Angle | p02 | 5.750 |
| Round Out | p03 | 5.200 |
| Narrow Angle | p03 | 5.600 |
| Wide Angle | p03 | 5.500 |
| Round Out | p04 | 5.550 |
| Narrow Angle | p04 | 5.500 |
| Wide Angle | p04 | 5.400 |
| Round Out | p05 | 5.900 |
| Narrow Angle | p05 | 5.850 |
| Wide Angle | p05 | 5.700 |
| Round Out | p06 | 5.450 |
| Narrow Angle | p06 | 5.550 |
| Wide Angle | p06 | 5.600 |
| Round Out | p07 | 5.400 |
| Narrow Angle | p07 | 5.400 |
| Wide Angle | p07 | 5.350 |
| Round Out | p08 | 5.450 |
| Narrow Angle | p08 | 5.500 |
| Wide Angle | p08 | 5.350 |
| Round Out | p09 | 5.250 |
| Narrow Angle | p09 | 5.150 |
| Wide Angle | p09 | 5 |
| Round Out | p10 | 5.850 |
| Narrow Angle | p10 | 5.800 |
| Wide Angle | p10 | 5.700 |
| Round Out | p11 | 5.250 |
| Narrow Angle | p11 | 5.200 |
| Wide Angle | p11 | 5.100 |
| Round Out | p12 | 5.650 |
| Narrow Angle | p12 | 5.550 |
| Wide Angle | p12 | 5.450 |
| Round Out | p13 | 5.600 |
| Narrow Angle | p13 | 5.350 |
| Wide Angle | p13 | 5.450 |
| Round Out | p14 | 5.050 |
| Narrow Angle | p14 | 5 |
| Wide Angle | p14 | 4.950 |
| Round Out | p15 | 5.500 |
| Narrow Angle | p15 | 5.500 |
| Wide Angle | p15 | 5.400 |
| Round Out | p16 | 5.450 |
| Narrow Angle | p16 | 5.550 |
| Wide Angle | p16 | 5.500 |
| Round Out | p17 | 5.550 |
| Narrow Angle | p17 | 5.550 |
| Wide Angle | p17 | 5.350 |
| Round Out | p18 | 5.450 |
| Narrow Angle | p18 | 5.500 |
| Wide Angle | p18 | 5.550 |
| Round Out | p19 | 5.500 |
| Narrow Angle | p19 | 5.450 |
| Wide Angle | p19 | 5.250 |
| Round Out | p20 | 5.650 |
| Narrow Angle | p20 | 5.600 |
| Wide Angle | p20 | 5.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 method | n | Median | Mean rank |
|---|---|---|---|
| Round Out | 22 | 5.500 | 2.409 |
| Narrow Angle | 22 | 5.525 | 2.136 |
| Wide Angle | 22 | 5.450 | 1.455 |
Pairwise comparisons (Conover)
| Contrast | Conover t | p | p adj. |
|---|---|---|---|
| Round Out - Narrow Angle | 1.047 | .301 | .301 |
| Round Out - Wide Angle | 3.664 | < .001 | .002 |
| Narrow Angle - Wide Angle | 2.617 | .012 | .025 |
- 3 conditions of base method ranked within each of 22 subjects (Friedman test).
The exact R script · R 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)))
))
χ²(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 method | n | Median | Mean rank |
|---|---|---|---|
| Round Out | 22 | 5.500 | 2.409 |
| Narrow Angle | 22 | 5.525 | 2.136 |
| Wide Angle | 22 | 5.450 | 1.455 |
Pairwise comparisons (Conover)
| Contrast | Conover t | p | p adj. |
|---|---|---|---|
| Round Out - Narrow Angle | 1.047 | .301 | .301 |
| Round Out - Wide Angle | 3.664 | < .001 | .002 |
| Narrow Angle - Wide Angle | 2.617 | .012 | .025 |
- 3 conditions of base method ranked within each of 22 subjects (Friedman test).
The exact Python script · Python 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})],
})
The card also reports the Iman–Davenport F approximation, usually more accurate than for small samples: F = 7.12, p = .002.
Friedman uses only the order inside each block, so it can lose much of the information in the differences. With few conditions that loss is largest.
Quade: weigh the blocks
ReadFriedman treats a store where sales barely differ the same as a store with huge gaps. Quade's test ranks the blocks by their range, and gives wide-range blocks more weight.
Seven stores sold five brands. Quade gives F(4, 24) = 3.83, p = .015. With few conditions it is often more powerful. With five or more, Friedman tends to catch up.
Follow up
In the appChoose the Test and keep Pairwise comparisons on. Your Pairwise test options are Conover, Nemenyi, Exact rank-sum differences, Wilcoxon signed-rank, and Quade's own t comparisons.
import pandas as pd
from scipy import stats
wide = pd.read_csv("rounding_times.csv").pivot(index="player", columns="base method", values="time")
print(stats.friedmanchisquare(*[wide[c] for c in wide.columns]))df <- read.csv("rounding_times.csv")
friedman.test(time ~ base.method | player, data = df)
stores <- read.csv("c3_store_brand.csv")
quade.test(sold ~ brand | store, data = stores)Decide on a follow-up
ReflectNemenyi is the classic follow-up for comparing several methods across data sets, and its critical-difference diagram is widely used in machine learning. Conover has more power. An exact method controls the error precisely but needs a small design.
Which would you report if a reviewer asked you to justify the choice?
Check your understanding
CheckpointCheck yourself
With 4 conditions per subject, what mean rank should each condition have if they are interchangeable?
Show the answer
Answer: 2.5
(k + 1) / 2 = 5 / 2 = 2.5.
Check yourself
Why do differences between subjects not affect Friedman's test?
Show the answer
Answer: b
Each subject's values turn into ranks 1 to k, whatever the overall level.
Check yourself
You have 3 conditions, and blocks vary a lot in how spread out they are. Which test does well here?
Show the answer
Answer: a
Quade weights wide-range blocks, which helps with few conditions. Kruskal–Wallis would ignore the blocking altogether.
Recap
Recap- Friedman ranks within blocks, so differences between blocks don't matter.
- Quade adds weights for how spread out each block is, and tends to win with few conditions.
- Kendall's reports agreement, and it can stay small when the test is significant.
Concepts in this lesson