Skip to content

DRegression models · regression.ordinal

Ordinal logistic regression (proportional odds)

How do predictors shift an ordered outcome (e.g. low / medium / high) up or down?

Cumulative-link model for an ordered outcome (proportional odds with a logit link, or probit): one coefficient per predictor shifts every cumulative split at once. Reports odds ratios (logit), cut-points, the likelihood-ratio test against the thresholds-only model, McFadden's R² and the Brant test of the proportional-odds assumption (omnibus and per term).

Verified in Python and R Python and R agree to 6 decimals

A real result

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

Ordinal logistic regressionRecorded · Python and R agreeRecorded 2026-11-17 · 85 values compared · largest relative difference 9.0e-10
R

χ²(6, N = 1681) = 169.73, p < .001, McFadden R² = .05

LR χ²
169.73
p
< .001
McFadden R²
0.0465
Brant p
.201
AIC
3495.15

Effect size

  • McFadden R² 0.0465

Plots

Cumulative odds ratiosHow large are several estimates, how precise, and which exclude the null?
View data
Odds ratiohighTermlow
1.7622.163Infl: Medium1.435
3.6284.655Infl: High2.828
0.56420.7127Type: Apartment0.4466
0.69340.9398Type: Atrium0.5115
0.33590.4520Type: Terrace0.2496
1.4341.729Cont: High1.189

Assumptions

  • Proportional odds — Brant χ²(6) = 8.53, p = .201.
  • Observations per category — Smallest outcome category: Medium with 446 rows.
  • Multicollinearity — Largest VIF 1.03 (Cont).

Coefficients

TermBSEzpOdds ratio95% CI low95% CI highBrant p
Infl: Medium0.56640.10475.412< .0011.7621.4352.163.573
Infl: High1.2890.127210.136< .0013.6282.8284.655.658
Type: Apartment−0.57240.1192−4.800< .0010.56420.44660.7127.494
Type: Atrium−0.36620.1552−2.360.0180.69340.51150.9398.094
Type: Terrace−1.0910.1515−7.202< .0010.33590.24960.4520.860
Cont: High0.36030.09553.771< .0011.4341.1891.729.257

Positive B: higher outcome categories more likely. P(Y ≤ j) = F(ζ_j − x'B); Wald z tests; Brant p per term.

Cut-points (thresholds ζ)

SplitζSE
Low|Medium−0.49610.1248
Medium|High0.69070.1255
  • Cumulative logit model (MASS::polr parameterization); outcome order: Low < Medium < High; categorical predictors against their first level.
Python

χ²(6, N = 1681) = 169.73, p < .001, McFadden R² = .05

LR χ²
169.73
p
< .001
McFadden R²
0.0465
Brant p
.201
AIC
3495.15

Effect size

  • McFadden R² 0.0465

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

Assumptions

  • Proportional odds — Brant χ²(6) = 8.53, p = .201.
  • Observations per category — Smallest outcome category: Medium with 446 rows.
  • Multicollinearity — Largest VIF 1.03 (Cont).

Coefficients

TermBSEzpOdds ratio95% CI low95% CI highBrant p
Infl: Medium0.56640.10475.412< .0011.7621.4352.163.573
Infl: High1.2890.127210.136< .0013.6282.8284.655.658
Type: Apartment−0.57240.1192−4.800< .0010.56420.44660.7127.494
Type: Atrium−0.36620.1552−2.360.0180.69340.51150.9398.094
Type: Terrace−1.0910.1515−7.202< .0010.33590.24960.4520.860
Cont: High0.36030.09553.771< .0011.4341.1891.729.257

Positive B: higher outcome categories more likely. P(Y ≤ j) = F(ζ_j − x'B); Wald z tests; Brant p per term.

Cut-points (thresholds ζ)

SplitζSE
Low|Medium−0.49610.1248
Medium|High0.69070.1255
  • Cumulative logit model (MASS::polr parameterization); outcome order: Low < Medium < High; categorical predictors against their first level.

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

  • Housinghousing · outcome: Sat · predictors: Infl, Type, Cont
  • Probithousing · outcome: Sat · predictors: Infl, Cont
  • Numeric missingsurvey · outcome: Exer · predictors: Age, Pulse, Sex
  • Degenerate constanthousing · outcome: Sat · predictors: Infl, Type, Cont

In the guides

Where it sits in the decision guides

  • Ordinal variables: Spearman / Kendall, polychoric · Statistics Guide · C — Test association
  • Ordinal outcome: proportional odds · Statistics Guide · D — Predict an outcome
  • Model-specific checks (VIF, PH, PO, dispersion) · Statistics Guide · Step 2 — Check assumptions
  • Regression (linear, logistic, Poisson) · DS & ML Decision Guide · Predict — forecast or classify outcomes

What you need

Ordered outcomecategorical · 1 column · 3–20 levels
The stored level order is the outcome's order (lowest first); set it in the data dictionary.
Predictorsnumeric / categorical / boolean · 1–20 columns · 2–30 levels
Columns used to explain or predict the outcome.

Choices you make

statistics

Linkdefault logit

Logit gives proportional odds ratios; probit assumes a normal latent variable.

  • Logit (proportional odds)(default) — Effects read as odds ratios under proportional odds; the usual choice.
  • Probit (latent normal) — Effects read on a latent normal scale; pick it when your field expects it, since the fit is usually near-identical.
Interactionsdefault none

Add interaction terms so the effect of one predictor can depend on the value of another.

  • None (main effects only)(default) — Fits main effects only; the usual starting point and the easiest to read.
  • First two predictors (A × B) — Adds the A × B term for the first two predictors; pick it when you expect one effect to depend on the other.
  • All pairs of predictors — Adds every two-way term; uses many coefficients, so pick it with plenty of rows and a reason to look.

hypothesis

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.

  • Proportional odds (Brant)

    Each predictor's effect is the same at every cumulative split (low vs higher, low+medium vs high …).

    • If violated → Multinomial logistic regression — Lets every predictor have a separate effect for each outcome category, so proportional odds is no longer assumed. Changes the question: Ignores the order of the outcome; reports relative-risk ratios against a reference category instead of cumulative odds ratios.
  • Observations per category

    Sparse outcome categories make cut-points and the Brant test unstable.

  • Multicollinearity (VIF)

What it reports

  • Tests: Model vs thresholds only (likelihood-ratio test)
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.
n_levels
How many independent units the analysis used; it sets precision and power.
link
Connects the linear predictor to the outcome's mean, e.g. logit for probabilities, log for counts.
log_lik
The logarithm of the likelihood; higher (less negative) means the model fits the data better.
null_log_lik
How well a model with no predictors fits. The likelihood-ratio test compares the fitted model with it.
lr_chi2
A sum of squared, scaled differences between observed and expected counts or estimates.
lr_df
Compares nested models by how much the log-likelihood improves when parameters are added.
lr_p
Compares nested models by how much the log-likelihood improves when parameters are added.
mcfadden_r2
An R²-like summary for models without a usual R². Versions differ, and none reads as variance explained.
aic
A model score balancing fit against complexity; lower is better, and only differences matter.
bic
Like AIC but with a stronger penalty for parameters as n grows; favors simpler models.
brant_chi2
A sum of squared, scaled differences between observed and expected counts or estimates.
brant_df
How much independent information is left to estimate variability after fitting the model.
brant_p
How surprising your data would be if the null hypothesis were true, as a probability.
min_category_n
Number of observations in the rarest outcome category. Few cases there make the related coefficients unstable.
epv
Events (the rarer outcome) per estimated coefficient in logistic or Cox models.
converged
Whether an iterative fit found a stable solution; warnings mean estimates may be unreliable.
n_params
How many values a model learns from the data: a regression's coefficients (intercept included) or a network's weights and biases.
max_interaction_order
The most factors combined in one term of the model: 1 means main effects only, 2 two-way interactions.
missing_share
Values that were not recorded; how they went missing decides which fixes are safe.

Per group, level or term: coef[<term>], se[…], z[…], p[…], ci_low[…], ci_high[…], or[…], or_ci_low[…], or_ci_high[…], cut[<a|b>], cut_se[…], brant_p[<term>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses pandas, numpy, statsmodels, scipy, codesplash; R uses stats, MASS, nanoparquet, codesplashr.

Default traps between the two languages

  • Fits start from statsmodels OrderedModel / MASS::polr and are polished by the same Newton–Raphson twin (analytic gradient, central-difference Hessian) in both engines; standard errors come from that Hessian.
  • The Brant test uses the J − 1 binary logits fitted by the same IRLS twin in both engines, with the cross-covariance of the nested binary fits. It isn't compared with the brant package. A Monte Carlo at n = 600 gave size 5.9% at the 5% level.
Python

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

# Ordinal logistic regression (proportional odds)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.ordinal 2.0.1 · spec 91aa7e0a91455ca8
# Dataset: housing (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
from statsmodels.miscmodels.ordinal_model import OrderedModel

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import glm as csglm
from codesplash.stats import regression as csreg

# %% Data
df = pd.read_parquet("tests/parity/fixtures/housing.parquet", columns=["Sat", "Infl", "Type", "Cont"])
n_input = len(df)
df["Sat"] = pd.Categorical(df["Sat"], categories=["Low", "Medium", "High"])  # stored level order
df["Infl"] = pd.Categorical(df["Infl"], categories=["Low", "Medium", "High"])  # stored level order
df["Type"] = pd.Categorical(df["Type"], categories=["Tower", "Apartment", "Atrium", "Terrace"])  # stored level order
df["Cont"] = pd.Categorical(df["Cont"], categories=["Low", "High"])  # stored level order
df = df.dropna(subset=["Sat", "Infl", "Type", "Cont"])  # listwise deletion over the analysis columns
df["Sat"] = df["Sat"].cat.remove_unused_categories()
df["Infl"] = df["Infl"].cat.remove_unused_categories()
df["Type"] = df["Type"].cat.remove_unused_categories()
df["Cont"] = df["Cont"].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, ["Sat", "Infl", "Type", "Cont"])  # infinite values stop the run (registry/errors.yaml)

# %% Outcome and design matrix
outcome = "Sat"
predictors = ["Infl", "Type", "Cont"]
link = "logit"  # logit | probit
interactions = "none"
conf = 0.95
levels_y = [str(x) for x in df[outcome].cat.categories]  # stored order = outcome order (lowest first)
J = len(levels_y)
if J < 3:  # two levels: logistic regression
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=outcome, min=3, k=J)
y = df[outcome].cat.codes.to_numpy()  # 0..J−1
Xf = csreg.design_matrix(df, predictors, interactions)  # treatment dummies, intercept first
# Degenerate input stops with a catalog error; R runs the same checks in the same order.
# More rows than coefficients: the slopes plus J − 1 thresholds.
cs.check_rows(len(df), (Xf.shape[1] - 1) + (J - 1) + 1, "Ordinal regression")
for col in predictors:
    check_not_constant(df[col], col)  # one value (or one level with data) is no variation
if np.linalg.matrix_rank(Xf.to_numpy()) < Xf.shape[1]:
    cs.cs_error("CS_E_COLLINEAR")
X = Xf.drop(columns="(Intercept)")  # thresholds replace the intercept
terms = list(X.columns)
n, p = X.shape

# %% Fit: OrderedModel (BFGS) for starting values, then the shared Newton polish
om = OrderedModel(y, X, distr=link).fit(method="bfgs", maxiter=2000, gtol=1e-8, disp=False)
start_cuts = om.model.transform_threshold_params(om.params)[1:-1]  # actual cut-points ζ
theta, V, log_lik = csglm.clm_fit(X.to_numpy(), y, J, np.concatenate([np.asarray(om.params)[:p], start_cuts]), link)
b, cuts = theta[:p], theta[p:]
se = np.sqrt(np.diag(V))
zval = theta / se
pval = 2 * stats.norm.sf(np.abs(zval))
zc = stats.norm.ppf(1 - (1 - conf) / 2)
counts = np.bincount(y, minlength=J)
null_log_lik = float(np.sum(counts * np.log(counts / n)))
lr_chi2 = 2 * (log_lik - null_log_lik)
lr_p = float(stats.chi2.sf(lr_chi2, p))
mcfadden = 1 - log_lik / null_log_lik
aic = -2 * log_lik + 2 * (p + J - 1)
bic = -2 * log_lik + np.log(n) * (p + J - 1)
br = csglm.brant(Xf.to_numpy(), y, J)  # proportional-odds check from the J − 1 binary logits

# %% Assumptions
assumptions = [{"key": "proportional_odds", "label": "Proportional odds", "status": "warn" if br["p"] < 0.05 else "pass",
                "statistic": br["chi2"], "p": br["p"],
                "detail": f"Brant χ²({br['df']}) = {br['chi2']:.2f}, {cs.fmt_p(br['p'])}" + ("; effects differ across cut-points — consider a multinomial model." if br["p"] < 0.05 else ".")}]
min_n = int(counts.min())
assumptions.append({"key": "sample_size", "label": "Observations per category", "status": "warn" if min_n < 10 else "pass", "statistic": min_n,
                    "detail": f"Smallest outcome category: {levels_y[int(counts.argmin())]} with {min_n} rows."})
main_cols = [c for c in terms if csreg.TIMES not in c]
vifs = csreg.gvif(X, main_cols, df, predictors)  # one generalized VIF per factor
if vifs:
    worst = max(vifs, key=vifs.get)
    assumptions.append({"key": "multicollinearity", "label": "Multicollinearity", "status": "pass" if vifs[worst] < 5 else ("warn" if vifs[worst] < 10 else "fail"),
                        "statistic": vifs[worst], "detail": f"Largest VIF {vifs[worst]:.2f} ({worst})."})

# %% Result
alpha = 1 - conf
values = {}
coefs = []
for j, t in enumerate(terms):
    row = {"term": t, "estimate": float(b[j]), "se": float(se[j]), "z": float(zval[j]), "p": float(pval[j]),
           "ci_low": float(b[j] - zc * se[j]), "ci_high": float(b[j] + zc * se[j])}
    if link == "logit":
        row.update({"or": float(np.exp(row["estimate"])), "or_ci_low": float(np.exp(row["ci_low"])), "or_ci_high": float(np.exp(row["ci_high"]))})
    row["brant_p"] = br["terms"][j]["p"]
    coefs.append(row)
    for key in ("estimate", "se", "z", "p", "ci_low", "ci_high", "or", "or_ci_low", "or_ci_high", "brant_p"):
        if key in row:
            values[f"{'coef' if key == 'estimate' else key}[{t}]"] = row[key]
cut_rows = []
for j in range(J - 1):
    label = f"{levels_y[j]}|{levels_y[j + 1]}"
    cut_rows.append({"cut": label, "estimate": float(cuts[j]), "se": float(se[p + j])})
    values[f"cut[{label}]"] = float(cuts[j])
    values[f"cut_se[{label}]"] = float(se[p + j])
values.update({"n": n, "k": p, "n_levels": J, "link": link, "log_lik": float(log_lik), "null_log_lik": null_log_lik, "lr_chi2": float(lr_chi2),
               "lr_df": float(p), "lr_p": lr_p, "mcfadden_r2": float(mcfadden), "aic": float(aic), "bic": float(bic),
               "brant_chi2": br["chi2"], "brant_df": float(br["df"]), "brant_p": br["p"], "min_category_n": min_n,
               "epv": min_n / p, "converged": bool(np.max(np.abs(csglm.clm_loglik_grad(theta, X.to_numpy(), y, J, link)[1])) < 1e-6),
               "n_params": p + J - 1, "max_interaction_order": 2 if interactions != "none" and len(predictors) >= 2 else 1, "missing_share": n_dropped / n_input if n_input else 0.0})
pct = f"{conf:.0%}"
coef_cols = [{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "B", "type": "number"},
             {"key": "se", "label": "SE", "type": "number"}, {"key": "z", "label": "z", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}]
coef_cols += ([{"key": "or", "label": "Odds ratio", "type": "number"}, {"key": "or_ci_low", "label": f"{pct} CI low", "type": "number"},
               {"key": "or_ci_high", "label": f"{pct} CI high", "type": "number"}] if link == "logit" else
              [{"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"}])
coef_cols.append({"key": "brant_p", "label": "Brant p", "type": "pvalue"})
summary = (f"{'Proportional-odds' if link == 'logit' else 'Ordinal probit'} model of {outcome} ({J} levels, n = {n}): "
           f"χ²({p}) = {lr_chi2:.2f}, {cs.fmt_p(lr_p)}; Brant test of proportional odds {cs.fmt_p(br['p'])}.")
charts = []
if link == "logit":
    charts.append(cs.chart("odds", "forest", "Cumulative odds ratios", {
        "label": cs.col("Term", [c["term"] for c in coefs], kind="categorical"), "estimate": cs.col("Odds ratio", [c["or"] for c in coefs]),
        "low": cs.col("low", [c["or_ci_low"] for c in coefs]), "high": cs.col("high", [c["or_ci_high"] for c in coefs])}, controls={"reference": 1, "log": True}))
cs.publish({
    "method": "regression.ordinal",
    "methodVersion": "2.0.1",
    "title": "Ordinal logistic regression" if link == "logit" else "Ordinal probit regression",
    "engine": cs.engine_info("pandas", "numpy", "statsmodels", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"χ²({p}, N = {n}) = {cs.fmt_num(lr_chi2)}, {cs.fmt_p(lr_p)}, McFadden R² = {cs.fmt_num(mcfadden, leading_zero=False)}",
    "statistics": [{"key": "lr_chi2", "label": "LR χ²", "value": float(lr_chi2)}, {"key": "lr_p", "label": "p", "value": lr_p, "format": "p"},
                   {"key": "mcfadden_r2", "label": "McFadden R²", "value": float(mcfadden)}, {"key": "brant_p", "label": "Brant p", "value": br["p"], "format": "p"},
                   {"key": "aic", "label": "AIC", "value": float(aic)}],
    "tables": [
        {"key": "coefficients", "title": "Coefficients", "columns": coef_cols, "rows": coefs,
         "note": "Positive B: higher outcome categories more likely. P(Y ≤ j) = F(ζ_j − x'B); Wald z tests; Brant p per term."},
        {"key": "cutpoints", "title": "Cut-points (thresholds ζ)", "columns": [
            {"key": "cut", "label": "Split", "type": "string"}, {"key": "estimate", "label": "ζ", "type": "number"}, {"key": "se", "label": "SE", "type": "number"}],
         "rows": cut_rows},
    ],
    "effectSizes": [{"key": "mcfadden_r2", "label": "McFadden R²", "value": float(mcfadden)}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Cumulative {link} model (MASS::polr parameterization); outcome order: {' < '.join(levels_y)}; categorical predictors against their first level."],
    "charts": charts,
    "values": values,
})
R

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

# Ordinal logistic regression (proportional odds)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method regression.ordinal 2.0.1 · spec 91aa7e0a91455ca8
# Dataset: housing (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/housing.parquet", col_select = c("Sat", "Infl", "Type", "Cont")))
n_input <- nrow(df)
df[["Sat"]] <- factor(df[["Sat"]], levels = c("Low", "Medium", "High"))  # stored level order
df[["Infl"]] <- factor(df[["Infl"]], levels = c("Low", "Medium", "High"))  # stored level order
df[["Type"]] <- factor(df[["Type"]], levels = c("Tower", "Apartment", "Atrium", "Terrace"))  # stored level order
df[["Cont"]] <- factor(df[["Cont"]], levels = c("Low", "High"))  # stored level order
df <- df[stats::complete.cases(df[c("Sat", "Infl", "Type", "Cont")]), , 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("Sat", "Infl", "Type", "Cont"))  # infinite values stop the run (registry/errors.yaml)

# %% Outcome and model
outcome <- "Sat"
predictors <- c("Infl", "Type", "Cont")
link <- "logit"  # logit | probit
interactions <- "none"
conf <- 0.95
levels_y <- levels(df[[outcome]])  # stored order = outcome order (lowest first)
J <- length(levels_y)
if (J < 3) cs_error("CS_E_TOO_FEW_GROUPS", column = outcome, min = 3, k = J)  # two levels: logistic regression
y <- as.integer(df[[outcome]])  # 1..J
terms_all <- cs_design_labels(df, predictors, interactions)
# Degenerate input stops with a catalog error; Python runs the same checks in the same order.
# More rows than coefficients: the slopes plus J - 1 thresholds.
cs_check_rows(nrow(df), (length(terms_all) - 1) + (J - 1) + 1, "Ordinal regression")
for (col in predictors) cs_check_not_constant(df[[col]], col)  # one value (or one level with data) is no variation
fml <- cs_model_formula(outcome, predictors, interactions)
Xf <- model.matrix(fml, data = df)  # treatment dummies, intercept first
if (qr(Xf)$rank < ncol(Xf)) cs_error("CS_E_COLLINEAR")
stopifnot(length(terms_all) == ncol(Xf))
colnames(Xf) <- terms_all
X <- Xf[, -1, drop = FALSE]  # thresholds replace the intercept
terms <- colnames(X)
n <- nrow(X)
p <- ncol(X)

# %% Fit: MASS::polr (BFGS) for starting values, then the shared Newton polish
pf0 <- MASS::polr(fml, data = df, method = if (link == "logit") "logistic" else "probit", Hess = FALSE, control = list(reltol = 1e-12, maxit = 2000))
fitc <- cs_clm_fit(X, y, J, c(unname(pf0$coefficients), unname(pf0$zeta)), link)
theta <- fitc$theta
V <- fitc$cov
log_lik <- fitc$ll
b <- theta[seq_len(p)]
cuts <- theta[p + seq_len(J - 1)]
se <- sqrt(diag(V))
zval <- theta / se
pval <- 2 * pnorm(abs(zval), lower.tail = FALSE)
zc <- qnorm(1 - (1 - conf) / 2)
counts <- tabulate(y, nbins = J)
null_log_lik <- sum(counts * log(counts / n))
lr_chi2 <- 2 * (log_lik - null_log_lik)
lr_p <- pchisq(lr_chi2, p, lower.tail = FALSE)
mcfadden <- 1 - log_lik / null_log_lik
aic <- -2 * log_lik + 2 * (p + J - 1)
bic <- -2 * log_lik + log(n) * (p + J - 1)
br <- cs_brant(Xf, y, J)  # proportional-odds check from the J - 1 binary logits

# %% Assumptions
assumptions <- list(list(key = "proportional_odds", label = "Proportional odds", status = if (br$p < 0.05) "warn" else "pass",
                         statistic = br$chi2, p = br$p,
                         detail = paste0(sprintf("Brant χ²(%d) = %.2f, %s", br$df, br$chi2, cs_fmt_p(br$p)),
                                         if (br$p < 0.05) "; effects differ across cut-points — consider a multinomial model." else ".")))
min_n <- min(counts)
assumptions[[2]] <- list(key = "sample_size", label = "Observations per category", status = if (min_n < 10) "warn" else "pass", statistic = min_n,
                         detail = sprintf("Smallest outcome category: %s with %d rows.", levels_y[which.min(counts)], min_n))
main_cols <- terms[!grepl(" × ", terms, fixed = TRUE)]
vifs <- cs_gvif(X, main_cols, df, predictors)  # one generalized VIF per factor
if (length(vifs)) {
  mv <- max(vifs)
  assumptions[[3]] <- list(key = "multicollinearity", label = "Multicollinearity", status = if (mv < 5) "pass" else if (mv < 10) "warn" else "fail",
                           statistic = mv, detail = sprintf("Largest VIF %.2f (%s).", mv, names(vifs)[which.max(vifs)]))
}

# %% Result
alpha <- 1 - conf
values <- list()
coefs <- list()
for (j in seq_len(p)) {
  t <- terms[j]
  row <- list(term = t, estimate = b[j], se = se[j], z = zval[j], p = pval[j], ci_low = b[j] - zc * se[j], ci_high = b[j] + zc * se[j])
  if (link == "logit") row <- c(row, list(or = exp(row$estimate), or_ci_low = exp(row$ci_low), or_ci_high = exp(row$ci_high)))
  row$brant_p <- br$terms[[j]]$p
  coefs[[j]] <- row
  for (key in c("estimate", "se", "z", "p", "ci_low", "ci_high", "or", "or_ci_low", "or_ci_high", "brant_p")) {
    if (!is.null(row[[key]])) values[[sprintf("%s[%s]", if (key == "estimate") "coef" else key, t)]] <- row[[key]]
  }
}
cut_rows <- list()
for (j in seq_len(J - 1)) {
  label <- paste0(levels_y[j], "|", levels_y[j + 1])
  cut_rows[[j]] <- list(cut = label, estimate = cuts[j], se = se[p + j])
  values[[sprintf("cut[%s]", label)]] <- cuts[j]
  values[[sprintf("cut_se[%s]", label)]] <- se[p + j]
}
values <- c(values, list(n = n, k = p, n_levels = J, link = link, log_lik = log_lik, null_log_lik = null_log_lik, lr_chi2 = lr_chi2,
                         lr_df = p, lr_p = lr_p, mcfadden_r2 = mcfadden, aic = aic, bic = bic, brant_chi2 = br$chi2, brant_df = br$df,
                         brant_p = br$p, min_category_n = min_n,
                         epv = min_n / p, converged = max(abs(cs_clm_loglik_grad(theta, X, y, J, link)$grad)) < 1e-6,
                         n_params = p + J - 1, max_interaction_order = if (interactions != "none" && length(predictors) >= 2) 2 else 1, missing_share = if (n_input > 0) n_dropped / n_input else 0))
pct <- sprintf("%.0f%%", conf * 100)
coef_cols <- list(list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "B", type = "number"),
                  list(key = "se", label = "SE", type = "number"), list(key = "z", label = "z", type = "number"), list(key = "p", label = "p", type = "pvalue"))
coef_cols <- c(coef_cols, if (link == "logit") {
  list(list(key = "or", label = "Odds ratio", type = "number"), list(key = "or_ci_low", label = paste(pct, "CI low"), type = "number"),
       list(key = "or_ci_high", label = paste(pct, "CI high"), type = "number"))
} else {
  list(list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number"))
}, list(list(key = "brant_p", label = "Brant p", type = "pvalue")))
summary <- sprintf("%s model of %s (%d levels, n = %d): χ²(%d) = %.2f, %s; Brant test of proportional odds %s.",
                   if (link == "logit") "Proportional-odds" else "Ordinal probit", outcome, J, n, p, lr_chi2, cs_fmt_p(lr_p), cs_fmt_p(br$p))
charts <- list()
if (link == "logit") {
  charts[[1]] <- cs_chart("odds", "forest", "Cumulative odds ratios", list(
    label = cs_col("Term", vapply(coefs, `[[`, "", "term"), kind = "categorical"), estimate = cs_col("Odds ratio", vapply(coefs, `[[`, 0, "or")),
    low = cs_col("low", vapply(coefs, `[[`, 0, "or_ci_low")), high = cs_col("high", vapply(coefs, `[[`, 0, "or_ci_high"))),
    controls = list(reference = 1, log = TRUE))
}
cs_publish(list(
  method = "regression.ordinal",
  methodVersion = "2.0.1",
  title = if (link == "logit") "Ordinal logistic regression" else "Ordinal probit regression",
  engine = cs_engine_info("stats", "MASS", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("χ²(%d, N = %d) = %s, %s, McFadden R² = %s", p, n, cs_fmt_num(lr_chi2), cs_fmt_p(lr_p), cs_fmt_num(mcfadden, leading_zero = FALSE)),
  statistics = list(list(key = "lr_chi2", label = "LR χ²", value = lr_chi2), list(key = "lr_p", label = "p", value = lr_p, format = "p"),
                    list(key = "mcfadden_r2", label = "McFadden R²", value = mcfadden), list(key = "brant_p", label = "Brant p", value = br$p, format = "p"),
                    list(key = "aic", label = "AIC", value = aic)),
  tables = list(
    list(key = "coefficients", title = "Coefficients", columns = coef_cols, rows = coefs,
         note = "Positive B: higher outcome categories more likely. P(Y ≤ j) = F(ζ_j − x'B); Wald z tests; Brant p per term."),
    list(key = "cutpoints", title = "Cut-points (thresholds ζ)", columns = list(
      list(key = "cut", label = "Split", type = "string"), list(key = "estimate", label = "ζ", type = "number"), list(key = "se", label = "SE", type = "number")),
      rows = cut_rows)
  ),
  effectSizes = list(list(key = "mcfadden_r2", label = "McFadden R²", value = mcfadden)),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Cumulative %s model (MASS::polr parameterization); outcome order: %s; categorical predictors against their first level.",
                       link, paste(levels_y, collapse = " < "))),
  charts = charts,
  values = values
))

Sources

  • McCullagh, P. (1980). Regression models for ordinal data. JRSS B, 42, 109–142.
  • Brant, R. (1990). Assessing proportionality in the proportional odds model for ordinal logistic regression. Biometrics, 46, 1171–1178.
  • Venables, W. N., & Ripley, B. D. (2002). Modern Applied Statistics with S (4th ed.), §7.3. Springer.

From the CodeSplash method registry · regression.ordinal v2.0.1.