GMeasurement · measurement.plackett_luce
Rankings (Plackett–Luce)
Which items do people rank highest, by how much, and how sure can we be of the order, from complete or partial rankings?
Estimates each item's worth from rankings by maximum likelihood under the Plackett–Luce model: a ranking is a sequence of choices, each from the items not yet chosen. Rankings may cover different subsets of items, and an item that was shown but not ranked (rank missing) stays among the alternatives at every step, so top-k rankings are used correctly. Reports worths on a centered log scale with standard errors, each item's share (its chance of being ranked first among all items), a bootstrap over rankings (how often each item comes first, rank intervals), a likelihood-ratio test against equal worths and a check of first choices against the model. A set of rankings whose "ranked above" graph isn't strongly connected has no finite estimate and stops with a clear message.
A real result
Example “Fruit rankings”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Plackett–Luce model: LR χ²(6) = 115.08, p < .001
- LR χ²
- 115.08
- p
- < .001
- AIC
- 1259.38
- mango first
- 89.0%
Plots
View data
| Worth (log) | Upper | Item | Lower |
|---|---|---|---|
| 0.7604 | 0.9882 | mango | 0.5326 |
| 0.5478 | 0.7845 | peach | 0.3111 |
| 0.3851 | 0.6220 | melon | 0.1482 |
| −0.0653 | 0.1708 | pear | −0.3013 |
| −0.1676 | 0.0660 | plum | −0.4011 |
| −0.5964 | −0.3467 | lemon | −0.8460 |
| −0.8642 | −0.5987 | lime | −1.130 |
View data
| Item | Share of resamples |
|---|---|
| mango | 0.8900 |
| peach | 0.1000 |
| melon | 0.0100 |
| pear | 0 |
| plum | 0 |
| lemon | 0 |
| lime | 0 |
Assumptions
- Connected rankings — Every item is ranked above and below its way to every other item, so the estimates are finite and unique.
- First choices match the model — Largest standardized gap: lemon, first in 15 rankings against 11.4 expected (z = 1.13).
- Rankings per item — Every item is in at least 10 rankings (fewest 101).
- Independent rankings — Not checked from data: rankings are treated as independent, and each choice ignores the items already chosen (independence of irrelevant alternatives). The bootstrap resamples single rankings.
Worths (log scale, centered; share = chance of being ranked first among all 7)
| Rank | Item | Worth (log) | SE | 95% CI low | 95% CI high | Share | Rankings | Ranked first | Expected first | First in resamples | Rank low | Rank high |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | mango | 0.7604 | 0.1162 | 0.5326 | 0.9882 | 0.2643 | 112 | 41 | 39.595 | 0.8900 | 1 | 2 |
| 2 | peach | 0.5478 | 0.1208 | 0.3111 | 0.7845 | 0.2137 | 101 | 27 | 29.383 | 0.1000 | 1 | 3 |
| 3 | melon | 0.3851 | 0.1209 | 0.1482 | 0.6220 | 0.1816 | 102 | 27 | 25.873 | 0.0100 | 2 | 3 |
| 4 | pear | −0.0653 | 0.1204 | −0.3013 | 0.1708 | 0.1158 | 104 | 14 | 18.017 | 0 | 4 | 5 |
| 5 | plum | −0.1676 | 0.1192 | −0.4011 | 0.0660 | 0.1045 | 115 | 19 | 17.293 | 0 | 4 | 5 |
| 6 | lemon | −0.5964 | 0.1274 | −0.8460 | −0.3467 | 0.0681 | 112 | 15 | 11.410 | 0 | 6 | 7 |
| 7 | lime | −0.8642 | 0.1354 | −1.130 | −0.5987 | 0.0521 | 108 | 7 | 8.429 | 0 | 6 | 7 |
Model fit
| Value | |
|---|---|
| Rankings | 150 |
| Choices | 541 |
| Log-likelihood | −623.69 |
| Log-likelihood, equal worths | −681.23 |
| LR χ² vs equal worths | 115.08 |
| LR p | 1.754e-22 |
| AIC | 1259.38 |
| BIC | 1277.44 |
- Plackett–Luce model: worths are log-worths centered to sum to 0; the last item (plum) was the reference in the fit. Lower values of rank are better. 56 of 150 rankings leave some shown items unranked; those items stay among the alternatives at every step. Newton iterations: 4.
- Bootstrap: 200 of 200 resamples of single rankings refitted (seed 42; the same resamples in Python and R); 0 skipped because a resample's rankings weren't connected or didn't converge. Intervals are percentile intervals.
Plackett–Luce model: LR χ²(6) = 115.08, p < .001
- LR χ²
- 115.08
- p
- < .001
- AIC
- 1259.38
- mango first
- 89.0%
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Connected rankings — Every item is ranked above and below its way to every other item, so the estimates are finite and unique.
- First choices match the model — Largest standardized gap: lemon, first in 15 rankings against 11.4 expected (z = 1.13).
- Rankings per item — Every item is in at least 10 rankings (fewest 101).
- Independent rankings — Not checked from data: rankings are treated as independent, and each choice ignores the items already chosen (independence of irrelevant alternatives). The bootstrap resamples single rankings.
Worths (log scale, centered; share = chance of being ranked first among all 7)
| Rank | Item | Worth (log) | SE | 95% CI low | 95% CI high | Share | Rankings | Ranked first | Expected first | First in resamples | Rank low | Rank high |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | mango | 0.7604 | 0.1162 | 0.5326 | 0.9882 | 0.2643 | 112 | 41 | 39.595 | 0.8900 | 1 | 2 |
| 2 | peach | 0.5478 | 0.1208 | 0.3111 | 0.7845 | 0.2137 | 101 | 27 | 29.383 | 0.1000 | 1 | 3 |
| 3 | melon | 0.3851 | 0.1209 | 0.1482 | 0.6220 | 0.1816 | 102 | 27 | 25.873 | 0.0100 | 2 | 3 |
| 4 | pear | −0.0653 | 0.1204 | −0.3013 | 0.1708 | 0.1158 | 104 | 14 | 18.017 | 0 | 4 | 5 |
| 5 | plum | −0.1676 | 0.1192 | −0.4011 | 0.0660 | 0.1045 | 115 | 19 | 17.293 | 0 | 4 | 5 |
| 6 | lemon | −0.5964 | 0.1274 | −0.8460 | −0.3467 | 0.0681 | 112 | 15 | 11.410 | 0 | 6 | 7 |
| 7 | lime | −0.8642 | 0.1354 | −1.130 | −0.5987 | 0.0521 | 108 | 7 | 8.429 | 0 | 6 | 7 |
Model fit
| Value | |
|---|---|
| Rankings | 150 |
| Choices | 541 |
| Log-likelihood | −623.69 |
| Log-likelihood, equal worths | −681.23 |
| LR χ² vs equal worths | 115.08 |
| LR p | 1.754e-22 |
| AIC | 1259.38 |
| BIC | 1277.44 |
- Plackett–Luce model: worths are log-worths centered to sum to 0; the last item (plum) was the reference in the fit. Lower values of rank are better. 56 of 150 rankings leave some shown items unranked; those items stay among the alternatives at every step. Newton iterations: 4.
- Bootstrap: 200 of 200 resamples of single rankings refitted (seed 42; the same resamples in Python and R); 0 skipped because a resample's rankings weren't connected or didn't converge. Intervals are percentile intervals.
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
- Fruit rankingshme_rankings · item: fruit · rank: rank · ranking: taster
- Fruit scores panelshme_rankings · cluster: panel · item: fruit · rank: score · ranking: taster
- Pairs as rankingshme_pairs_as_rankings · item: item · rank: rank · ranking: judgment
- Degenerate constanthme_rankings · item: fruit · rank: rank · ranking: taster
- Degenerate all nahme_rankings · item: fruit · rank: rank · ranking: taster
- Degenerate infhme_rankings · item: fruit · rank: rank · ranking: taster
- Degenerate n1hme_rankings · item: fruit · rank: rank · ranking: taster
- Degenerate tieshme_rankings · item: fruit · rank: rank · ranking: taster
In the guides
Where it sits in the decision guides
- Preferences from rankings: Plackett–Luce · Statistics Guide · G — Agreement / reliability
What you need
- Rankingcategorical / numeric · 1 column
- Which ranking each row belongs to (a respondent, a judge's list, a ballot). Long data — one row per item shown in a ranking.
- Itemcategorical · 1 column · 2–1000 levels
- The item the row is about. List every item that was shown, ranked or not.
- Ranknumeric · 1 column
- The item's position (1 = best by default) or a score. Leave it missing for an item that was shown but not ranked; tied ranks within one ranking aren't allowed.
- Clustercategorical · 0–1 column
- Optional — the independent unit for the bootstrap (a judge who made several rankings, a session, a panel); whole clusters are resampled instead of single rankings.
Choices you make
model
- Which values are betterdefault lower
How to read the Rank column. Only the order within each ranking matters.
- Lower values (rank 1 is best)(default) — For positions: 1 is the top choice.
- Higher values (scores) — For scores or ratings that order the items: the highest is the top choice.
statistics
- Bootstrap resamplesdefault 200
Resamples of rankings (or whole clusters) refitted to show how stable the order is; the same resamples in Python and R for a seed. 0 skips the bootstrap.
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
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.
Connected rankings
Every item must be ranked above and below its way to every other item (a strongly connected graph), or its worth runs off to infinity.
First choices match the model
Each item's observed number of first choices against the number the worths predict; a standardized gap beyond 3 flags an item the model misses.
Rankings per item
Items in fewer than 10 rankings have imprecise worths.
Independent rankingsNot checked from data: state why it holds
Rankings are treated as independent and choices follow the model (independence of irrelevant alternatives); several rankings by one judge call for a cluster bootstrap.
What it reports
- n_rankings
- Number of rankings fitted (each is one respondent's or judge's ordered list).
- n_choices
- Number of choice steps across all rankings (each pick from two or more remaining items).
- items
- Number of items with worths estimated (items that appear in the fitted comparisons or rankings).
- partial
- Rankings that leave some shown items unranked (top-k); those items stay among the alternatives at every step.
- n_left_out
- Judgments with no preference (inconsistent, abstain) or an item against itself; for rankings, rows missing a ranking or item.
- loglik
- Log-likelihood of the fitted model at its estimates; higher is a better fit for the same data.
- loglik_null
- Log-likelihood when every item has the same worth (keeping any position effect and tie parameter).
- npar
- Number of estimated parameters: items − 1 worths, plus a position effect, tie parameter or judge reliabilities when present.
- lr
- Twice the gain in log-likelihood over equal worths; large values say the items really differ.
- lr_df
- Degrees of freedom of the likelihood-ratio test against equal worths: items − 1.
- lr_p
- p-value of the likelihood-ratio test that all items have the same worth.
- aic
- Akaike's information criterion, −2 log-likelihood + 2 × parameters; lower is better among models of the same data.
- bic
- Bayesian information criterion, with log(judgments or rankings) per parameter; lower is better among models of the same data.
- fit_max_z
- The largest standardized gap between an item's observed and expected first choices; beyond 3 flags poor fit.
- fit_item
- The item whose first choices the model fits worst.
- top_item
- The item with the highest estimated worth.
- top_item_freq
- Share of bootstrap refits in which the top item stays on top.
- boot_ok
- Number of bootstrap resamples that were refitted successfully.
- boot_failed
- Resamples whose comparisons weren't connected (no finite worths) or that didn't converge; many skips mean a thin design.
- iterations
- Newton steps (Crowd-BT: EM cycles) the fit needed to converge.
Per group, level or term: score[<item>], se[<item>], ci_low[<item>], ci_high[<item>], worth[<item>], rank[<item>], boot_low[<item>], boot_high[<item>], top_freq[<item>], rank_low[<item>], rank_high[<item>], shown[<item>], first_choices[<item>], first_expected[<item>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-7). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Both engines build the same choice stages and run the same Newton iterations (codesplash.stats.paired_comparison ↔ cs_pc_*), and draw the same bootstrap resamples from the shared Wichmann–Hill stream, so they agree to rounding.
The exact script CodeSplash ran for example “Fruit rankings” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Rankings (Plackett–Luce)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.plackett_luce 1.0.0 · spec 8227e60eb1412e03
# Dataset: hme_rankings (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import json
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_finite
from codesplash.stats import paired_comparison as pc # twin of R's cs_pc_* (R/stats_paired_comparison.R)
# %% Data (long rankings: one row per item shown; a missing rank = shown but not ranked)
col_r, col_i, col_v = "taster", "fruit", "rank"
col_c = None
cols = [c for c in (col_r, col_i, col_v, col_c) if c is not None]
df = pd.read_parquet("tests/parity/fixtures/hme_rankings.parquet", columns=list(dict.fromkeys(cols)))
stored = json.loads("{\"fruit\":[\"lemon\",\"lime\",\"mango\",\"melon\",\"peach\",\"pear\",\"plum\"],\"rank\":null,\"taster\":null}")
n_input = len(df)
need = [c for c in (col_r, col_i, col_c) if c is not None]
df = df.dropna(subset=need).reset_index(drop=True) # rows without a ranking, item or cluster can't be placed
warnings = []
if n_input - len(df):
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_input - len(df), total=n_input))
if not len(df):
cs.cs_error("CS_E_NO_ROWS")
value = df[col_v].to_numpy(dtype=float)
check_finite(value, col_v) # infinite values stop the run (registry/errors.yaml)
item_text = df[col_i].astype(str).to_numpy()
levels = stored.get(col_i) or sorted(set(item_text))
rid = df[col_r].astype(str).to_numpy()
names = list(pd.unique(rid))
code = np.array([names.index(x) for x in rid], dtype=np.int64)
dup = pd.Series(list(zip(code, item_text))).duplicated().to_numpy()
if dup.any():
cs.cs_error("CS_E_INVALID_VALUES", column=col_i, requirement="listed at most once in each ranking", count=int(dup.sum()))
if np.isnan(value).all():
cs.cs_error("CS_E_ALL_MISSING", column=col_v)
better = "lower"
reps = 200
conf = 0.95
seed = 42 # portable Wichmann–Hill stream: R draws the same resamples for this seed
# %% Choice stages (each ranking = a sequence of choices from the items not yet chosen)
pos_all = {it: i for i, it in enumerate(levels)}
item_all = np.array([pos_all[x] for x in item_text], dtype=np.int64)
st_rank, st_choice, mem_stage, mem_item, n_rank, partial, tied = pc.pl_stages(code, item_all, value, better)
if tied >= 0:
cs.cs_error("CS_E_UNDEFINED", what="The Plackett–Luce model", reason=f"ranking {names[tied]} has tied ranks; break the ties or leave that ranking out")
if len(set(item_text)) < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=col_i, min=2, k=len(set(item_text)))
if len(st_choice) == 0: # no ranking shows two or more items
cs.cs_error("CS_E_TOO_FEW_ROWS", what="The Plackett–Luce model", min=2, n=0)
used = sorted(set(mem_item.tolist()))
items = [levels[i] for i in used]
k = len(items)
if k < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=col_i, min=2, k=k)
remap = np.full(len(levels), -1, dtype=np.int64)
remap[used] = np.arange(k)
st_choice, mem_item = remap[st_choice], remap[mem_item]
w_rank = np.ones(n_rank)
w_stage = w_rank[st_rank]
adj = pc.pl_graph(st_choice, mem_stage, mem_item, w_stage, k)
if not pc.strongly_connected(adj):
cs.cs_error("CS_E_UNDEFINED", what="The Plackett–Luce model", reason="some items are never ranked below (or never above) the rest, so their worths run off to infinity; add rankings that link them")
if col_c is not None:
cv = df[col_c].astype(str).to_numpy()
first_row = np.array([np.flatnonzero(code == g)[0] for g in range(n_rank)])
cl_names = list(pd.unique(cv[first_row]))
unit = np.array([cl_names.index(x) for x in cv[first_row]], dtype=np.int64)
unit_label = f"whole values of {col_c}"
else:
unit = None
unit_label = "single rankings"
# %% Fit (maximum likelihood: Newton steps on log-worths, the last item as reference, then centered)
try:
fit = pc.fit_pl(st_choice, mem_stage, mem_item, w_stage, k)
except RuntimeError:
cs.cs_error("CS_E_NO_CONVERGENCE", what="The Plackett–Luce model")
except np.linalg.LinAlgError:
cs.cs_error("CS_E_COLLINEAR")
s = fit["scores"]
se = np.sqrt(np.diag(fit["cov"]))
z = pc.z_value(conf)
worth = np.exp(s) / np.exp(s).sum()
ranks = pc.point_ranks(s)
loglik, loglik0 = fit["loglik"], fit["loglik_null"]
npar = k - 1
lr = 2 * (loglik - loglik0)
O, E, zr = pc.pl_first_choice_fit(st_rank, st_choice, mem_stage, mem_item, fit["raw"], w_rank, k)
worst = int(np.argmax(np.abs(zr)))
pairs = np.unique(st_rank[mem_stage] * k + mem_item) # rankings in which each item takes part
shown = np.bincount(pairs % k, minlength=k).astype(float)
values = {"n_rankings": float(n_rank), "n_choices": float(len(st_choice)), "items": float(k), "partial": float(partial),
"n_left_out": float(n_input - len(df)), "loglik": loglik, "loglik_null": loglik0, "npar": float(npar), "lr": lr,
"lr_df": float(npar), "lr_p": pc.lr_p(lr, npar), "aic": -2 * loglik + 2 * npar, "bic": -2 * loglik + npar * np.log(n_rank),
"fit_max_z": float(np.abs(zr[worst])), "fit_item": items[worst], "iterations": float(fit["iterations"])}
for i, it in enumerate(items):
values.update({f"score[{it}]": float(s[i]), f"se[{it}]": float(se[i]), f"ci_low[{it}]": float(s[i] - z * se[i]),
f"ci_high[{it}]": float(s[i] + z * se[i]), f"worth[{it}]": float(worth[i]), f"rank[{it}]": float(ranks[i]),
f"shown[{it}]": float(shown[i]), f"first_choices[{it}]": float(O[i]), f"first_expected[{it}]": float(E[i])})
# %% Bootstrap of the order (shared Wichmann–Hill stream; rankings, or whole clusters)
boot_scores, boot_failed = [], 0
if reps > 0:
counts = pc.boot_counts(w_rank, unit, reps, seed)
for r in range(reps):
wb = counts[r][st_rank]
if not pc.strongly_connected(pc.pl_graph(st_choice, mem_stage, mem_item, wb, k)):
boot_failed += 1
continue
try:
boot_scores.append(pc.fit_pl(st_choice, mem_stage, mem_item, wb, k)["scores"])
except (RuntimeError, np.linalg.LinAlgError):
boot_failed += 1
boot_scores = np.array(boot_scores) if boot_scores else np.zeros((0, k))
values["boot_ok"] = float(len(boot_scores)) if reps > 0 else None
values["boot_failed"] = float(boot_failed) if reps > 0 else None
top = pc.top_index(s)
values["top_item"] = items[top]
if len(boot_scores) >= 2:
blo, bhi, topf, rlo, rhi = pc.boot_summary(boot_scores, conf)
for i, it in enumerate(items):
values.update({f"boot_low[{it}]": float(blo[i]), f"boot_high[{it}]": float(bhi[i]), f"top_freq[{it}]": float(topf[i]),
f"rank_low[{it}]": float(rlo[i]), f"rank_high[{it}]": float(rhi[i])})
values["top_item_freq"] = float(topf[top])
else:
blo = bhi = topf = rlo = rhi = None
values["top_item_freq"] = None
# %% Assumptions
thin = [f"{it} ({int(shown[i])})" for i, it in enumerate(items) if shown[i] < 10]
assumptions = [
{"key": "connectivity", "label": "Connected rankings", "status": "pass",
"detail": "Every item is ranked above and below its way to every other item, so the estimates are finite and unique."},
{"key": "fit", "label": "First choices match the model", "status": "warn" if abs(zr[worst]) > 3 else "pass",
"detail": f"Largest standardized gap: {items[worst]}, first in {O[worst]:.0f} rankings against {E[worst]:.1f} expected (z = {zr[worst]:.2f})"
+ (" — the model misses this item's first choices." if abs(zr[worst]) > 3 else ".")},
{"key": "sample_size", "label": "Rankings per item", "status": "warn" if thin else "pass",
"detail": "In fewer than 10 rankings: " + ", ".join(thin[:8]) + (" …" if len(thin) > 8 else "") + "." if thin else f"Every item is in at least 10 rankings (fewest {int(shown.min())})."},
{"key": "independence", "label": "Independent rankings", "status": "info",
"detail": f"Not checked from data: rankings are treated as independent, and each choice ignores the items already chosen (independence of irrelevant alternatives). The bootstrap resamples {unit_label}."},
]
# %% Result
order = np.argsort(-np.round(s, 10), kind="stable")
pct = f"{conf:.0%}"
cols_t = [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "item", "label": "Item", "type": "string"},
{"key": "score", "label": "Worth (log)", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
{"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"},
{"key": "worth", "label": "Share", "type": "number"}, {"key": "shown", "label": "Rankings", "type": "number"},
{"key": "first", "label": "Ranked first", "type": "number"}, {"key": "expected", "label": "Expected first", "type": "number"}]
if blo is not None:
cols_t += [{"key": "top_freq", "label": "First in resamples", "type": "number"},
{"key": "rank_low", "label": "Rank low", "type": "number"}, {"key": "rank_high", "label": "Rank high", "type": "number"}]
rows = []
for i in order:
r = {"rank": float(ranks[i]), "item": items[i], "score": float(s[i]), "se": float(se[i]), "ci_low": float(s[i] - z * se[i]),
"ci_high": float(s[i] + z * se[i]), "worth": float(worth[i]), "shown": float(shown[i]), "first": float(O[i]), "expected": float(E[i])}
if blo is not None:
r.update({"top_freq": float(topf[i]), "rank_low": float(rlo[i]), "rank_high": float(rhi[i])})
rows.append(r)
fit_rows = [{"stat": "Rankings", "value": float(n_rank)}, {"stat": "Choices", "value": float(len(st_choice))},
{"stat": "Log-likelihood", "value": loglik}, {"stat": "Log-likelihood, equal worths", "value": loglik0},
{"stat": "LR χ² vs equal worths", "value": lr}, {"stat": "LR p", "value": values["lr_p"]},
{"stat": "AIC", "value": values["aic"]}, {"stat": "BIC", "value": values["bic"]}]
tables = [{"key": "items", "title": f"Worths (log scale, centered; share = chance of being ranked first among all {k})", "columns": cols_t, "rows": rows},
{"key": "fit", "title": "Model fit", "columns": [{"key": "stat", "label": "", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}], "rows": fit_rows}]
charts = [cs.chart("worths", "forest", f"Worths (log scale) with {pct} intervals", {
"label": cs.col("Item", [items[i] for i in order], "categorical", levels=[items[i] for i in order]),
"estimate": cs.col("Worth (log)", [float(s[i]) for i in order], "numeric"),
"low": cs.col("Lower", [float(s[i] - z * se[i]) for i in order], "numeric"),
"high": cs.col("Upper", [float(s[i] + z * se[i]) for i in order], "numeric"),
}, controls={"reference": 0})]
if topf is not None:
charts.append(cs.chart("top", "bar-ranked", "How often each item comes first in the bootstrap", {
"category": cs.col("Item", [items[i] for i in order], "categorical", levels=[items[i] for i in order]),
"value": cs.col("Share of resamples", [float(topf[i]) for i in order], "numeric"),
}, controls={"agg": "sum", "top": min(30, k)}))
notes = [f"Plackett–Luce model: worths are log-worths centered to sum to 0; the last item ({items[-1]}) was the reference in the fit. "
f"{'Lower' if better == 'lower' else 'Higher'} values of {col_v} are better. {partial} of {n_rank} rankings leave some shown items unranked; "
f"those items stay among the alternatives at every step. Newton iterations: {fit['iterations']}."]
if reps > 0:
notes.append(f"Bootstrap: {len(boot_scores)} of {reps} resamples of {unit_label} refitted (seed {seed}; the same resamples in Python and R); "
f"{boot_failed} skipped because a resample's rankings weren't connected or didn't converge. Intervals are percentile intervals.")
summary = f"Plackett–Luce model for {k} items from {n_rank} rankings: {items[top]} has the highest worth" + (
f" and comes first in {values['top_item_freq']:.0%} of the bootstrap resamples." if values["top_item_freq"] is not None else ".")
cs.publish({
"method": "measurement.plackett_luce",
"methodVersion": "1.0.0",
"title": "Plackett–Luce model",
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(n_rank),
"summary": summary,
"apa": f"Plackett–Luce model: LR χ²({npar}) = {cs.fmt_num(lr)}, {cs.fmt_p(values['lr_p'])}",
"statistics": [{"key": "lr", "label": "LR χ²", "value": lr}, {"key": "lr_p", "label": "p", "value": values["lr_p"], "format": "p"},
{"key": "aic", "label": "AIC", "value": values["aic"]}, {"key": "top_item_freq", "label": f"{items[top]} first", "value": values["top_item_freq"], "format": "percent"}],
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"charts": charts,
"values": values,
})
The exact script CodeSplash ran for example “Fruit rankings” · R version 4.5.1 (2025-06-13)
# Rankings (Plackett–Luce)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.plackett_luce 1.0.0 · spec 8227e60eb1412e03
# Dataset: hme_rankings (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data (long rankings: one row per item shown; a missing rank = shown but not ranked)
col_r <- "taster"
col_i <- "fruit"
col_v <- "rank"
col_c <- NULL
cols <- unique(c(col_r, col_i, col_v, col_c))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/hme_rankings.parquet", col_select = cols))
stored_levels <- c("lemon", "lime", "mango", "melon", "peach", "pear", "plum")
n_input <- nrow(df)
need <- c(col_r, col_i, col_c)
df <- df[stats::complete.cases(df[need]), , drop = FALSE] # rows without a ranking, item or cluster can't be placed
warnings <- list()
if (n_input - nrow(df) > 0) warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_input - nrow(df), total = n_input))
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
value <- as.numeric(df[[col_v]])
cs_check_finite(value, col_v) # infinite values stop the run (registry/errors.yaml)
item_text <- as.character(df[[col_i]])
levels_i <- if (!is.null(stored_levels)) stored_levels else sort(unique(item_text), method = "radix")
rid <- as.character(df[[col_r]])
names_r <- unique(rid)
code <- match(rid, names_r)
dup <- duplicated(paste(code, item_text, sep = "\r"))
if (any(dup)) cs_error("CS_E_INVALID_VALUES", column = col_i, requirement = "listed at most once in each ranking", count = sum(dup))
if (all(is.na(value))) cs_error("CS_E_ALL_MISSING", column = col_v)
better <- "lower"
reps <- 200
conf <- 0.95
seed <- 42 # portable Wichmann–Hill stream: Python draws the same resamples for this seed
# %% Choice stages (each ranking = a sequence of choices from the items not yet chosen)
item_all <- match(item_text, levels_i)
stg <- cs_pc_pl_stages(code, item_all, value, better)
if (stg$tied > 0) cs_error("CS_E_UNDEFINED", what = "The Plackett–Luce model", reason = sprintf("ranking %s has tied ranks; break the ties or leave that ranking out", names_r[stg$tied]))
if (length(unique(item_text)) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = col_i, min = 2, k = length(unique(item_text)))
if (length(stg$st_choice) == 0) cs_error("CS_E_TOO_FEW_ROWS", what = "The Plackett–Luce model", min = 2, n = 0) # no ranking shows two or more items
n_rank <- stg$n_rank
used <- sort(unique(stg$mem_item))
items <- levels_i[used]
k <- length(items)
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = col_i, min = 2, k = k)
remap <- rep(0L, length(levels_i))
remap[used] <- seq_len(k)
st_rank <- stg$st_rank
st_choice <- remap[stg$st_choice]
mem_stage <- stg$mem_stage
mem_item <- remap[stg$mem_item]
w_rank <- rep(1, n_rank)
w_stage <- w_rank[st_rank]
adj <- cs_pc_pl_graph(st_choice, mem_stage, mem_item, w_stage, k)
if (!cs_pc_strongly_connected(adj)) {
cs_error("CS_E_UNDEFINED", what = "The Plackett–Luce model", reason = "some items are never ranked below (or never above) the rest, so their worths run off to infinity; add rankings that link them")
}
if (!is.null(col_c)) {
cv <- as.character(df[[col_c]])
first_row <- match(seq_len(n_rank), code)
cl <- cv[first_row]
unit <- match(cl, unique(cl))
unit_label <- paste("whole values of", col_c)
} else {
unit <- NULL
unit_label <- "single rankings"
}
# %% Fit (maximum likelihood: Newton steps on log-worths, the last item as reference, then centered)
fit <- tryCatch(cs_pc_fit_pl(st_choice, mem_stage, mem_item, w_stage, k), error = function(e) {
if (grepl("singular", conditionMessage(e))) cs_error("CS_E_COLLINEAR")
cs_error("CS_E_NO_CONVERGENCE", what = "The Plackett–Luce model")
})
s <- fit$scores
se <- sqrt(diag(fit$cov))
z <- cs_pc_z(conf)
worth <- exp(s) / sum(exp(s))
ranks <- cs_pc_point_ranks(s)
loglik <- fit$loglik
loglik0 <- fit$loglik_null
npar <- k - 1
lr <- 2 * (loglik - loglik0)
ff <- cs_pc_pl_first_fit(st_rank, st_choice, mem_stage, mem_item, fit$raw, w_rank, k)
worst <- which.max(abs(ff$z))
pairs <- unique((st_rank[mem_stage] - 1) * k + mem_item) # rankings in which each item takes part
shown <- tabulate((pairs - 1) %% k + 1, nbins = k)
values <- list(n_rankings = n_rank, n_choices = length(st_choice), items = k, partial = stg$partial, n_left_out = n_input - nrow(df),
loglik = loglik, loglik_null = loglik0, npar = npar, lr = lr, lr_df = npar, lr_p = cs_pc_lr_p(lr, npar),
aic = -2 * loglik + 2 * npar, bic = -2 * loglik + npar * log(n_rank), fit_max_z = abs(ff$z[worst]),
fit_item = items[worst], iterations = fit$iterations)
for (i in seq_len(k)) {
it <- items[i]
values[[sprintf("score[%s]", it)]] <- s[i]
values[[sprintf("se[%s]", it)]] <- se[i]
values[[sprintf("ci_low[%s]", it)]] <- s[i] - z * se[i]
values[[sprintf("ci_high[%s]", it)]] <- s[i] + z * se[i]
values[[sprintf("worth[%s]", it)]] <- worth[i]
values[[sprintf("rank[%s]", it)]] <- ranks[i]
values[[sprintf("shown[%s]", it)]] <- shown[i]
values[[sprintf("first_choices[%s]", it)]] <- ff$O[i]
values[[sprintf("first_expected[%s]", it)]] <- ff$E[i]
}
# %% Bootstrap of the order (shared Wichmann–Hill stream; rankings, or whole clusters)
boot <- list()
boot_failed <- 0
if (reps > 0) {
counts <- cs_pc_boot_counts(w_rank, unit, reps, seed)
for (r in seq_len(reps)) {
wb <- counts[r, ][st_rank]
if (!cs_pc_strongly_connected(cs_pc_pl_graph(st_choice, mem_stage, mem_item, wb, k))) {
boot_failed <- boot_failed + 1
next
}
res <- tryCatch(cs_pc_fit_pl(st_choice, mem_stage, mem_item, wb, k)$scores, error = function(e) NULL)
if (is.null(res)) boot_failed <- boot_failed + 1 else boot[[length(boot) + 1]] <- res
}
}
boot_scores <- if (length(boot)) do.call(rbind, boot) else matrix(0, 0, k)
values["boot_ok"] <- list(if (reps > 0) nrow(boot_scores) else NULL)
values["boot_failed"] <- list(if (reps > 0) boot_failed else NULL)
top <- cs_pc_top_index(s)
values$top_item <- items[top]
bsum <- NULL
if (nrow(boot_scores) >= 2) {
bsum <- cs_pc_boot_summary(boot_scores, conf)
for (i in seq_len(k)) {
it <- items[i]
values[[sprintf("boot_low[%s]", it)]] <- bsum$low[i]
values[[sprintf("boot_high[%s]", it)]] <- bsum$high[i]
values[[sprintf("top_freq[%s]", it)]] <- bsum$top[i]
values[[sprintf("rank_low[%s]", it)]] <- bsum$rank_low[i]
values[[sprintf("rank_high[%s]", it)]] <- bsum$rank_high[i]
}
values$top_item_freq <- bsum$top[top]
} else {
values["top_item_freq"] <- list(NULL)
}
# %% Assumptions
thin <- sprintf("%s (%d)", items, as.integer(shown))[shown < 10]
assumptions <- list(
list(key = "connectivity", label = "Connected rankings", status = "pass",
detail = "Every item is ranked above and below its way to every other item, so the estimates are finite and unique."),
list(key = "fit", label = "First choices match the model", status = if (abs(ff$z[worst]) > 3) "warn" else "pass",
detail = paste0(sprintf("Largest standardized gap: %s, first in %.0f rankings against %.1f expected (z = %.2f)", items[worst], ff$O[worst], ff$E[worst], ff$z[worst]),
if (abs(ff$z[worst]) > 3) " — the model misses this item's first choices." else ".")),
list(key = "sample_size", label = "Rankings per item", status = if (length(thin)) "warn" else "pass",
detail = if (length(thin)) paste0("In fewer than 10 rankings: ", paste(utils::head(thin, 8), collapse = ", "), if (length(thin) > 8) " …" else "", ".") else
sprintf("Every item is in at least 10 rankings (fewest %d).", as.integer(min(shown)))),
list(key = "independence", label = "Independent rankings", status = "info",
detail = sprintf("Not checked from data: rankings are treated as independent, and each choice ignores the items already chosen (independence of irrelevant alternatives). The bootstrap resamples %s.", unit_label))
)
# %% Result
ord <- order(-round(s, 10), method = "radix")
pct <- sprintf("%.0f%%", conf * 100)
cols_t <- list(list(key = "rank", label = "Rank", type = "integer"), list(key = "item", label = "Item", type = "string"),
list(key = "score", label = "Worth (log)", type = "number"), list(key = "se", label = "SE", type = "number"),
list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number"),
list(key = "worth", label = "Share", type = "number"), list(key = "shown", label = "Rankings", type = "number"),
list(key = "first", label = "Ranked first", type = "number"), list(key = "expected", label = "Expected first", type = "number"))
if (!is.null(bsum)) {
cols_t <- c(cols_t, list(list(key = "top_freq", label = "First in resamples", type = "number"),
list(key = "rank_low", label = "Rank low", type = "number"), list(key = "rank_high", label = "Rank high", type = "number")))
}
rows <- lapply(ord, function(i) {
r <- list(rank = ranks[i], item = items[i], score = s[i], se = se[i], ci_low = s[i] - z * se[i], ci_high = s[i] + z * se[i],
worth = worth[i], shown = shown[i], first = ff$O[i], expected = ff$E[i])
if (!is.null(bsum)) { r$top_freq <- bsum$top[i]; r$rank_low <- bsum$rank_low[i]; r$rank_high <- bsum$rank_high[i] }
r
})
fit_rows <- list(list(stat = "Rankings", value = n_rank), list(stat = "Choices", value = length(st_choice)),
list(stat = "Log-likelihood", value = loglik), list(stat = "Log-likelihood, equal worths", value = loglik0),
list(stat = "LR χ² vs equal worths", value = lr), list(stat = "LR p", value = values$lr_p),
list(stat = "AIC", value = values$aic), list(stat = "BIC", value = values$bic))
tables <- list(list(key = "items", title = sprintf("Worths (log scale, centered; share = chance of being ranked first among all %d)", k), columns = cols_t, rows = rows),
list(key = "fit", title = "Model fit", columns = list(list(key = "stat", label = "", type = "string"), list(key = "value", label = "Value", type = "number")), rows = fit_rows))
charts <- list(cs_chart("worths", "forest", sprintf("Worths (log scale) with %s intervals", pct), list(
label = cs_col("Item", items[ord], "categorical", levels = items[ord]),
estimate = cs_col("Worth (log)", s[ord], "numeric"),
low = cs_col("Lower", (s - z * se)[ord], "numeric"),
high = cs_col("Upper", (s + z * se)[ord], "numeric")
), controls = list(reference = 0)))
if (!is.null(bsum)) {
charts[[2]] <- cs_chart("top", "bar-ranked", "How often each item comes first in the bootstrap", list(
category = cs_col("Item", items[ord], "categorical", levels = items[ord]),
value = cs_col("Share of resamples", bsum$top[ord], "numeric")
), controls = list(agg = "sum", top = min(30, k)))
}
notes <- list(sprintf("Plackett–Luce model: worths are log-worths centered to sum to 0; the last item (%s) was the reference in the fit. %s values of %s are better. %d of %d rankings leave some shown items unranked; those items stay among the alternatives at every step. Newton iterations: %d.",
items[k], if (better == "lower") "Lower" else "Higher", col_v, as.integer(stg$partial), as.integer(n_rank), as.integer(fit$iterations)))
if (reps > 0) {
notes[[2]] <- sprintf("Bootstrap: %d of %d resamples of %s refitted (seed %s; the same resamples in Python and R); %d skipped because a resample's rankings weren't connected or didn't converge. Intervals are percentile intervals.",
nrow(boot_scores), as.integer(reps), unit_label, format(seed), as.integer(boot_failed))
}
summary <- paste0(sprintf("Plackett–Luce model for %d items from %d rankings: %s has the highest worth", k, as.integer(n_rank), items[top]),
if (!is.null(values$top_item_freq)) sprintf(" and comes first in %.0f%% of the bootstrap resamples.", 100 * values$top_item_freq) else ".")
cs_publish(list(
method = "measurement.plackett_luce",
methodVersion = "1.0.0",
title = "Plackett–Luce model",
engine = cs_engine_info("stats", "codesplashr"),
n = as.integer(n_rank),
summary = summary,
apa = sprintf("Plackett–Luce model: LR χ²(%d) = %s, %s", as.integer(npar), cs_fmt_num(lr), cs_fmt_p(values$lr_p)),
statistics = list(list(key = "lr", label = "LR χ²", value = lr), list(key = "lr_p", label = "p", value = values$lr_p, format = "p"),
list(key = "aic", label = "AIC", value = values$aic),
list(key = "top_item_freq", label = paste(items[top], "first"), value = values$top_item_freq, format = "percent")),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = notes,
charts = charts,
values = values
))
Sources
- Plackett, R. L. (1975). The analysis of permutations. Journal of the Royal Statistical Society, Series C, 24, 193–202.
- Luce, R. D. (1959). Individual Choice Behavior: A Theoretical Analysis. Wiley.
- Hunter, D. R. (2004). MM algorithms for generalized Bradley–Terry models. Annals of Statistics, 32, 384–406.
- Turner, H. L., van Etten, J., Firth, D., & Kosmidis, I. (2020). Modelling rankings in R: the PlackettLuce package. Computational Statistics, 35, 1027–1057.
From the CodeSplash method registry · measurement.plackett_luce v1.0.0.