GAgreement & reliability · agreement.kappa
Cohen's kappa (two raters)
Do two raters assign the same categories more often than chance?
Measures chance-corrected agreement between two raters on a categorical scale. Unweighted κ treats every disagreement alike; linear or quadratic weights give partial credit for near misses on ordered categories. Reports the Fleiss–Cohen–Everitt standard error and interval, the z test, observed and expected agreement, PABAK and the maximum attainable κ.
A real result
Example “Unweighted”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
κ = .54, 95% CI [0.44, 0.65], z = 10.89, p < .001
- κ
- 0.5425
- 95% CI
- [0.4388, 0.6463]
- p
- < .001
- Observed agreement
- 67.3%
Effect size
- Cohen's κ 0.5425 95% CI [0.4388, 0.6463]
Plots
View data
| rater_b | Count | rater_a | Subjects |
|---|---|---|---|
| none | 44 | none | 44 |
| mild | 12 | none | 12 |
| moderate | 0 | none | 0 |
| severe | 0 | none | 0 |
| none | 8 | mild | 8 |
| mild | 28 | mild | 28 |
| moderate | 7 | mild | 7 |
| severe | 2 | mild | 2 |
| none | 2 | moderate | 2 |
| mild | 7 | moderate | 7 |
| moderate | 18 | moderate | 18 |
| severe | 6 | moderate | 6 |
| none | 0 | severe | 0 |
| mild | 0 | severe | 0 |
| moderate | 5 | severe | 5 |
| severe | 11 | severe | 11 |
View data
| rater_a | rater_b | Subjects |
|---|---|---|
| none | none | 44 |
| none | mild | 12 |
| none | moderate | 0 |
| none | severe | 0 |
| mild | none | 8 |
| mild | mild | 28 |
| mild | moderate | 7 |
| mild | severe | 2 |
| moderate | none | 2 |
| moderate | mild | 7 |
| moderate | moderate | 18 |
| moderate | severe | 6 |
| severe | none | 0 |
| severe | mild | 0 |
| severe | moderate | 5 |
| severe | severe | 11 |
Assumptions
- Sample size — 150 subjects.
- Prevalence and bias — The most common category covers 37% of a rater's ratings.
Agreement table
| rater_a \ rater_b | none | mild | moderate | severe | Total |
|---|---|---|---|---|---|
| none | 44 | 12 | 0 | 0 | 56 |
| mild | 8 | 28 | 7 | 2 | 45 |
| moderate | 2 | 7 | 18 | 6 | 33 |
| severe | 0 | 0 | 5 | 11 | 16 |
| Total | 54 | 47 | 30 | 19 | 150 |
Rows: rater_a; columns: rater_b.
Agreement indices
| Index | Value |
|---|---|
| Observed agreement (weighted) | 0.6733 |
| Expected agreement (weighted) | 0.2859 |
| PABAK | 0.5644 |
| κ max (unweighted) | 0.9533 |
| SE (non-null) | 0.0529 |
| SE (null) | 0.0498 |
- Categories in stored order: none, mild, moderate, severe.
κ = .54, 95% CI [0.44, 0.65], z = 10.89, p < .001
- κ
- 0.5425
- 95% CI
- [0.4388, 0.6463]
- p
- < .001
- Observed agreement
- 67.3%
Effect size
- Cohen's κ 0.5425 95% CI [0.4388, 0.6463]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Sample size — 150 subjects.
- Prevalence and bias — The most common category covers 37% of a rater's ratings.
Agreement table
| rater_a \ rater_b | none | mild | moderate | severe | Total |
|---|---|---|---|---|---|
| none | 44 | 12 | 0 | 0 | 56 |
| mild | 8 | 28 | 7 | 2 | 45 |
| moderate | 2 | 7 | 18 | 6 | 33 |
| severe | 0 | 0 | 5 | 11 | 16 |
| Total | 54 | 47 | 30 | 19 | 150 |
Rows: rater_a; columns: rater_b.
Agreement indices
| Index | Value |
|---|---|
| Observed agreement (weighted) | 0.6733 |
| Expected agreement (weighted) | 0.2859 |
| PABAK | 0.5644 |
| κ max (unweighted) | 0.9533 |
| SE (non-null) | 0.0529 |
| SE (null) | 0.0498 |
- Categories in stored order: none, mild, moderate, severe.
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
- Unweightedratings_sim · rater_a: rater_a · rater_b: rater_b
- Quadratic spaceratings_sim · rater_a: rater_a · rater_b: rater e
- Linear missingratings_sim · rater_a: rater_c · rater_b: rater_d
- Booleanratings_sim · rater_a: yes_a · rater_b: yes_b
- Null value unweightedratings_sim · rater_a: rater_a · rater_b: rater_b
- Null value quadraticratings_sim · rater_a: rater_a · rater_b: rater e
- Degenerate n1ratings_sim · rater_a: rater_a · rater_b: rater_b
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Categorical (2 raters): Cohen's κ · Statistics Guide · G — Agreement / reliability
What you need
- Rater Acategorical / boolean · 1 column · 2–30 levels
- The first rater's category for each subject.
- Rater Bcategorical / boolean · 1 column · 2–30 levels
- The second rater's category for the same subjects.
Choices you make
hypothesis
- Weightsdefault none
Weighted κ uses the stored level order of the categories.
- None (nominal categories)(default) — Counts only exact matches; pick it for unordered categories.
- Linear (ordered categories) — Credit falls in a straight line with distance; pick it for ordered categories with equal steps.
- Quadratic (ordered; ≈ ICC) — Credit falls with squared distance, so near misses lose little; the usual choice for ordered scales.
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
Advanced
- Null value (κ₀)default 0
κ under the null hypothesis. 0 tests for agreement beyond chance; a value like 0.6 tests against a benchmark, using the non-null standard error.
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.
Sample size
The large-sample standard error needs enough subjects (and some in each category).
Prevalence and bias
κ is low when one category dominates even if raters agree often (the kappa paradox); compare PABAK and κ max.
What it reports
- Tests: Agreement differs from the null value (κ ≠ 0 unless set)
- kappa
- Agreement between raters beyond what chance would produce; 0 is chance level, 1 is perfect.
- ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- se
- The typical size of the error in an estimate, the standard deviation of its sampling distribution.
- se0
- The typical size of the error in an estimate, the standard deviation of its sampling distribution.
- z
- An estimate in standard-error units, compared with the standard normal distribution.
- p
- How surprising your data would be if the null hypothesis were true, as a probability.
- po
- Observed agreement is the share of ratings that match; chance agreement is the share expected to match anyway.
- pe
- Observed agreement is the share of ratings that match; chance agreement is the share expected to match anyway.
- po_raw
- Observed agreement is the share of ratings that match; chance agreement is the share expected to match anyway.
- pabak
- Kappa recomputed as if the categories were equally common and the raters' margins equal. For two categories, it's 2·po − 1.
- kappa_max
- The largest unweighted κ the two raters' category totals allow. Empty for weighted κ.
- n
- How many independent units the analysis used; it sets precision and power.
- k
- How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
- weights_label
- Kappa for ordered categories, giving partial credit for near misses by linear or quadratic weights.
Per group, level or term: null_value
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Both engines use the same closed form (codesplash.stats.agreement.kappa ↔ cs_kappa); variances per Fleiss, Cohen & Everitt (1969), as psych::cohen.kappa and irr::kappa2.
The exact script CodeSplash ran for example “Unweighted” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Cohen's kappa (two raters)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method agreement.kappa 1.1.0 · spec c464900e1c604d42
# Dataset: ratings_sim (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.stats import agreement as ag # Cohen's κ with FCE variances (twin of R's cs_kappa)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/ratings_sim.parquet", columns=["rater_a", "rater_b"])
n_input = len(df)
df["rater_a"] = pd.Categorical(df["rater_a"], categories=["none", "mild", "moderate", "severe"]) # stored level order
df["rater_b"] = pd.Categorical(df["rater_b"], categories=["none", "mild", "moderate", "severe"]) # stored level order
df = df.dropna(subset=["rater_a", "rater_b"]) # listwise deletion over the analysis columns
df["rater_a"] = df["rater_a"].cat.remove_unused_categories()
df["rater_b"] = df["rater_b"].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, ["rater_a", "rater_b"]) # infinite values stop the run (registry/errors.yaml)
# %% Agreement table
a, b = "rater_a", "rater_b"
cats = list(dict.fromkeys([str(x) for x in df[a].cat.categories] + [str(x) for x in df[b].cat.categories])) # stored order
k = len(cats)
if k < 2:
cs.cs_error("CS_E_UNDEFINED", what="Cohen's κ", reason="the raters used only one category")
ia = np.array([cats.index(x) for x in df[a].astype(str)])
ib = np.array([cats.index(x) for x in df[b].astype(str)])
table = np.zeros((k, k))
np.add.at(table, (ia, ib), 1)
# %% Cohen's kappa
weights = "none"
conf = 0.95
res = ag.kappa(table, weights, conf)
k0 = 0 # H0: κ = κ0; 0 keeps the usual test with the null SE
if k0 != 0:
from codesplash.stats import agreement_null as agn # twin of R's cs_kappa_null_test
res["z"], res["p"] = agn.kappa_null_test(res["kappa"], res["se"], k0)
weights_label = {"none": "Unweighted", "linear": "Linearly weighted", "quadratic": "Quadratically weighted"}[weights]
nan = lambda x: None if not np.isfinite(x) else float(x) # noqa: E731
values = {key: nan(res[key]) for key in ("kappa", "ci_low", "ci_high", "se", "se0", "z", "p", "po", "pe", "po_raw", "pabak", "kappa_max")}
values.update({"n": float(res["n"]), "k": float(k), "weights_label": weights_label})
if k0 != 0:
values["null_value"] = k0
# %% Assumptions
n = int(res["n"])
empty = [c for i, c in enumerate(cats) if table[i].sum() + table[:, i].sum() == 0]
pr, pc = table.sum(axis=1) / n, table.sum(axis=0) / n
dominant = max(pr.max(), pc.max())
assumptions = [
{"key": "sample_size", "label": "Sample size", "status": "warn" if n < 30 else "pass",
"detail": f"{n} subjects" + (" — the large-sample interval is approximate." if n < 30 else ".")},
{"key": "prevalence", "label": "Prevalence and bias", "status": "warn" if dominant > 0.8 else "pass",
"detail": f"The most common category covers {dominant:.0%} of a rater's ratings"
+ ("; κ can be low despite high agreement (compare PABAK)." if dominant > 0.8 else ".")},
]
# %% Result
pct = f"{conf:.0%}"
cols = [{"key": "rater_a", "label": f"{a} \\ {b}", "type": "string"}] + [
{"key": f"c{j}", "label": c, "type": "integer"} for j, c in enumerate(cats)] + [{"key": "total", "label": "Total", "type": "integer"}]
rows = [{"rater_a": c, **{f"c{j}": float(table[i, j]) for j in range(k)}, "total": float(table[i].sum())} for i, c in enumerate(cats)]
rows.append({"rater_a": "Total", **{f"c{j}": float(table[:, j].sum()) for j in range(k)}, "total": float(n)})
cs.publish({
"method": "agreement.kappa",
"methodVersion": "1.1.0",
"title": f"{weights_label} Cohen's kappa",
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": n,
"summary": f"{weights_label} κ = {res['kappa']:.3f}, {pct} CI [{res['ci_low']:.3f}, {res['ci_high']:.3f}]; observed agreement {res['po_raw']:.1%}.",
"apa": f"κ = {cs.fmt_num(res['kappa'], 2, leading_zero=False)}, {pct} CI [{cs.fmt_num(res['ci_low'])}, {cs.fmt_num(res['ci_high'])}], z = {cs.fmt_num(res['z'])}, {cs.fmt_p(res['p'])}",
"statistics": [{"key": "kappa", "label": "κ", "value": res["kappa"]}, {"key": "ci", "label": f"{pct} CI", "value": [res["ci_low"], res["ci_high"]]},
{"key": "p", "label": "p", "value": res["p"], "format": "p"}, {"key": "po_raw", "label": "Observed agreement", "value": res["po_raw"], "format": "percent"}],
"tables": [
{"key": "agreement", "title": "Agreement table", "columns": cols, "rows": rows, "note": f"Rows: {a}; columns: {b}."},
{"key": "indices", "title": "Agreement indices", "columns": [
{"key": "index", "label": "Index", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
"rows": [{"index": "Observed agreement (weighted)", "value": res["po"]}, {"index": "Expected agreement (weighted)", "value": res["pe"]},
{"index": "PABAK", "value": res["pabak"]}, {"index": "κ max (unweighted)", "value": values["kappa_max"]},
{"index": "SE (non-null)", "value": res["se"]}, {"index": "SE (null)", "value": res["se0"]}]},
],
"effectSizes": [{"key": "kappa", "label": "Cohen's κ", "value": res["kappa"], "ciLow": res["ci_low"], "ciHigh": res["ci_high"],
"ciLevel": conf, "method": "Fleiss–Cohen–Everitt large-sample SE"}],
"assumptions": assumptions,
"warnings": warnings + ([f"Categories never used: {', '.join(empty)}."] if empty else []),
"notes": [f"Categories in stored order: {', '.join(cats)}." + (" Weights 1 − |i − j|/(k − 1)." if weights == "linear" else " Weights 1 − (i − j)²/(k − 1)²." if weights == "quadratic" else "")]
+ ([f"The test is against a null value of {cs.fmt_num(k0)} (H₀: κ = {cs.fmt_num(k0)}): z = (κ − κ₀) / SE with the non-null standard error (Fleiss, Levin & Paik, 2003)."] if k0 != 0 else []),
"charts": [cs.chart("table", "matrix-heatmap", "Agreement table", {
"row": cs.col(a, [c for c in cats for _ in cats], "categorical", levels=cats),
"col": cs.col(b, [c for _ in cats for c in cats], "categorical", levels=cats),
"value": cs.col("Subjects", table.ravel().tolist(), "numeric"),
"label": cs.col("Count", [f"{int(x)}" for x in table.ravel()], "categorical"),
}, controls={"scale": "sequential"})] + ([cs.chart("agreement", "agreement-chart", "Agreement chart (Bangdiwala)", {
"a": cs.col(a, [c for c in cats for _ in cats], "categorical", levels=cats),
"b": cs.col(b, [c for _ in cats for c in cats], "categorical", levels=cats),
"count": cs.col("Subjects", table.ravel().tolist(), "numeric"),
}, controls={"partial": weights != "none"})] if k <= 12 else []),
"values": values,
})
The exact script CodeSplash ran for example “Unweighted” · R version 4.5.1 (2025-06-13)
# Cohen's kappa (two raters)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method agreement.kappa 1.1.0 · spec c464900e1c604d42
# Dataset: ratings_sim (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/ratings_sim.parquet", col_select = c("rater_a", "rater_b")))
n_input <- nrow(df)
df[["rater_a"]] <- factor(df[["rater_a"]], levels = c("none", "mild", "moderate", "severe")) # stored level order
df[["rater_b"]] <- factor(df[["rater_b"]], levels = c("none", "mild", "moderate", "severe")) # stored level order
df <- df[stats::complete.cases(df[c("rater_a", "rater_b")]), , 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("rater_a", "rater_b")) # infinite values stop the run (registry/errors.yaml)
# %% Agreement table
a <- "rater_a"
b <- "rater_b"
cats <- unique(c(levels(df[[a]]), levels(df[[b]]))) # stored order
k <- length(cats)
if (k < 2) cs_error("CS_E_UNDEFINED", what = "Cohen's κ", reason = "the raters used only one category")
tab <- unclass(table(factor(as.character(df[[a]]), levels = cats), factor(as.character(df[[b]]), levels = cats)))
tab <- matrix(as.numeric(tab), k, k)
# %% Cohen's kappa
weights <- "none"
conf <- 0.95
res <- cs_kappa(tab, weights, conf) # FCE variances (twin of codesplash.stats.agreement.kappa)
k0 <- 0 # H0: kappa = kappa0; 0 keeps the usual test with the null SE
if (k0 != 0) {
tst <- cs_kappa_null_test(res$kappa, res$se, k0) # twin of codesplash.stats.agreement_null.kappa_null_test
res$z <- tst$z
res$p <- tst$p
}
weights_label <- c(none = "Unweighted", linear = "Linearly weighted", quadratic = "Quadratically weighted")[[weights]]
fin <- function(x) if (!is.finite(x)) NA else unname(x)
values <- lapply(res[c("kappa", "ci_low", "ci_high", "se", "se0", "z", "p", "po", "pe", "po_raw", "pabak", "kappa_max")], fin)
values$n <- res$n
values$k <- k
values$weights_label <- weights_label
if (k0 != 0) values$null_value <- k0
# %% Assumptions
n <- res$n
empty <- cats[rowSums(tab) + colSums(tab) == 0]
dominant <- max(rowSums(tab) / n, colSums(tab) / n)
assumptions <- list(
list(key = "sample_size", label = "Sample size", status = if (n < 30) "warn" else "pass",
detail = paste0(sprintf("%d subjects", n), if (n < 30) " — the large-sample interval is approximate." else ".")),
list(key = "prevalence", label = "Prevalence and bias", status = if (dominant > 0.8) "warn" else "pass",
detail = paste0(sprintf("The most common category covers %.0f%% of a rater's ratings", 100 * dominant),
if (dominant > 0.8) "; κ can be low despite high agreement (compare PABAK)." else "."))
)
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
cols <- c(list(list(key = "rater_a", label = sprintf("%s \\ %s", a, b), type = "string")),
lapply(seq_len(k), function(j) list(key = sprintf("c%d", j - 1), label = cats[j], type = "integer")),
list(list(key = "total", label = "Total", type = "integer")))
rows <- lapply(seq_len(k), function(i) {
r <- list(rater_a = cats[i])
for (j in seq_len(k)) r[[sprintf("c%d", j - 1)]] <- tab[i, j]
r$total <- sum(tab[i, ])
r
})
tot <- list(rater_a = "Total")
for (j in seq_len(k)) tot[[sprintf("c%d", j - 1)]] <- sum(tab[, j])
tot$total <- n
rows[[k + 1]] <- tot
weight_note <- switch(weights, linear = " Weights 1 − |i − j|/(k − 1).", quadratic = " Weights 1 − (i − j)²/(k − 1)².", "")
cs_publish(list(
method = "agreement.kappa",
methodVersion = "1.1.0",
title = paste(weights_label, "Cohen's kappa"),
engine = cs_engine_info("stats", "codesplashr"),
n = n,
summary = sprintf("%s κ = %.3f, %s CI [%.3f, %.3f]; observed agreement %.1f%%.", weights_label, res$kappa, pct, res$ci_low, res$ci_high, 100 * res$po_raw),
apa = sprintf("κ = %s, %s CI [%s, %s], z = %s, %s", cs_fmt_num(res$kappa, 2, leading_zero = FALSE), pct, cs_fmt_num(res$ci_low),
cs_fmt_num(res$ci_high), cs_fmt_num(res$z), cs_fmt_p(res$p)),
statistics = list(list(key = "kappa", label = "κ", value = res$kappa), list(key = "ci", label = paste(pct, "CI"), value = c(res$ci_low, res$ci_high)),
list(key = "p", label = "p", value = res$p, format = "p"),
list(key = "po_raw", label = "Observed agreement", value = res$po_raw, format = "percent")),
tables = list(
list(key = "agreement", title = "Agreement table", columns = cols, rows = rows, note = sprintf("Rows: %s; columns: %s.", a, b)),
list(key = "indices", title = "Agreement indices", columns = list(
list(key = "index", label = "Index", type = "string"), list(key = "value", label = "Value", type = "number")),
rows = list(list(index = "Observed agreement (weighted)", value = res$po), list(index = "Expected agreement (weighted)", value = res$pe),
list(index = "PABAK", value = res$pabak), list(index = "κ max (unweighted)", value = values$kappa_max),
list(index = "SE (non-null)", value = res$se), list(index = "SE (null)", value = res$se0)))
),
effectSizes = list(list(key = "kappa", label = "Cohen's κ", value = res$kappa, ciLow = res$ci_low, ciHigh = res$ci_high,
ciLevel = conf, method = "Fleiss–Cohen–Everitt large-sample SE")),
assumptions = assumptions,
warnings = c(warnings, if (length(empty)) list(sprintf("Categories never used: %s.", paste(empty, collapse = ", ")))),
notes = c(list(paste0(sprintf("Categories in stored order: %s.", paste(cats, collapse = ", ")), weight_note)),
if (k0 != 0) list(sprintf("The test is against a null value of %s (H₀: κ = %s): z = (κ − κ₀) / SE with the non-null standard error (Fleiss, Levin & Paik, 2003).", cs_fmt_num(k0), cs_fmt_num(k0)))),
charts = c(list(cs_chart("table", "matrix-heatmap", "Agreement table", list(
row = cs_col(a, rep(cats, each = k), "categorical", levels = cats),
col = cs_col(b, rep(cats, times = k), "categorical", levels = cats),
value = cs_col("Subjects", as.vector(t(tab)), "numeric"),
label = cs_col("Count", as.character(as.vector(t(tab))), "categorical")
), controls = list(scale = "sequential"))), if (k <= 12) list(cs_chart("agreement", "agreement-chart", "Agreement chart (Bangdiwala)", list(
a = cs_col(a, rep(cats, each = k), "categorical", levels = cats),
b = cs_col(b, rep(cats, times = k), "categorical", levels = cats),
count = cs_col("Subjects", as.vector(t(tab)), "numeric")
), controls = list(partial = weights != "none")))),
values = values
))
Sources
- Cohen, J. (1960). A coefficient of agreement for nominal scales. Educational and Psychological Measurement, 20, 37–46.
- Cohen, J. (1968). Weighted kappa. Psychological Bulletin, 70, 213–220.
- Fleiss, J. L., Cohen, J., & Everitt, B. S. (1969). Large sample standard errors of kappa and weighted kappa. Psychological Bulletin, 72, 323–327.
- Byrt, T., Bishop, J., & Carlin, J. B. (1993). Bias, prevalence and kappa. Journal of Clinical Epidemiology, 46, 423–429.
From the CodeSplash method registry · agreement.kappa v1.1.0.