# Ordinal regression for ordered cover classes
# https://tidyecology.com/posts/ordinal-regression-cover-classes/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-06-04

## ---- dgp ----
set.seed(4227)
n    <- 260
x    <- round(runif(n, -2, 2), 3)
beta <- 1.25
th   <- c(-1.6, -0.4, 0.9, 2.1)                       # four cutpoints on the logit scale
Pcum <- cbind(sapply(th, function(t) plogis(t - beta * x)), 1)
Pcat <- cbind(Pcum[, 1], t(apply(Pcum, 1, diff)))     # per-class probabilities
y    <- apply(Pcat, 1, function(p) sample(1:5, 1, prob = p))

## ---- sci-tex-helper ----
sci_tex <- function(x, digits = 2) {
  s <- formatC(x, format = "e", digits = digits)
  paste0("$", sub("e.*", "", s), " \\times 10^{", as.integer(sub(".*e", "", s)), "}$")
}

## ---- hand-fit ----
negll_po <- function(par, y, x) {
  b   <- par[1]
  th  <- cumsum(c(par[2], exp(par[3:5])))             # ordered cutpoints
  Pc  <- plogis(outer(th, b * x, "-"))                # (J-1) x n cumulative
  Pc  <- rbind(Pc, 1)
  Pk  <- rbind(Pc[1, ], apply(Pc, 2, diff))           # J x n category probs
  -sum(log(pmax(Pk[cbind(y, seq_along(y))], 1e-12)))
}
fit <- optim(c(0, -1.5, log(1.2), log(1.3), log(1.2)),
             negll_po, y = y, x = x, method = "BFGS", hessian = TRUE)
stopifnot(fit$convergence == 0)   # check before inverting the Hessian
bh  <- fit$par[1]
thh <- cumsum(c(fit$par[2], exp(fit$par[3:5])))
p227_b  <- round(bh, 3)
p227_bse <- round(sqrt(diag(solve(fit$hessian)))[1], 3)
p227_or <- round(exp(bh), 2)

## ---- polr-check ----
suppressWarnings(suppressMessages(library(MASS)))
pol <- polr(factor(y, ordered = TRUE) ~ x, method = "logistic", Hess = TRUE)
p227_dbeta <- signif(abs(bh - coef(pol)), 2)
p227_dcut  <- signif(max(abs(thh - pol$zeta)), 2)

## ---- fig-probs ----
suppressWarnings(suppressMessages(library(ggplot2)))
theme_te <- function() theme_minimal(base_size = 12) + theme(
  panel.grid.minor = element_blank(),
  panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3),
  plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
  panel.background = element_rect(fill = "#f5f4ee", colour = NA),
  axis.text = element_text(colour = "#46604a"), axis.title = element_text(colour = "#2c3a31"),
  plot.title = element_text(colour = "#16241d", face = "bold"),
  plot.subtitle = element_text(colour = "#5d6b61"),
  legend.title = element_blank(), legend.text = element_text(colour = "#2c3a31"))
xs  <- seq(-2, 2, length = 140)
Pc  <- cbind(sapply(pol$zeta, function(t) plogis(t - coef(pol) * xs)), 1)
Pks <- cbind(Pc[, 1], t(apply(Pc, 1, diff)))
d1  <- data.frame(x = rep(xs, 5), prob = as.vector(Pks),
  cls = factor(rep(1:5, each = length(xs)),
               labels = c("1 (<5%)", "2 (5-25%)", "3 (25-50%)", "4 (50-75%)", "5 (>75%)")))
ggplot(d1, aes(x, prob, colour = cls)) + geom_line(linewidth = 1.1) +
  scale_colour_manual(values = c("#c9b458", "#9ab04f", "#5f9a55", "#39794f", "#1d5b4e")) +
  labs(x = "Soil moisture (standardised)", y = "Predicted probability",
       title = "Predicted cover-class probabilities") + theme_te()

## ---- naive ----
ols <- lm(y ~ x)
p227_pred <- round(predict(ols, data.frame(x = 2)), 2)
p227_sp   <- round(cor(x, y, method = "spearman"), 3)

## ---- parallel-slopes ----
sep_slopes <- function(y, x) sapply(1:4, function(j) coef(glm((y > j) ~ x, family = binomial))[2])
ss_po <- sep_slopes(y, x)
p227_spreadPO <- round(diff(range(ss_po)), 3)

set.seed(4228)                                         # a non-proportional counterexample
x2 <- round(runif(n, -2, 2), 3)
bj <- c(0.4, 0.9, 1.6, 2.4)                            # effect grows across thresholds
Pc2 <- cbind(sapply(1:4, function(j) plogis(th[j] - bj[j] * x2)), 1)
Pk2 <- cbind(Pc2[, 1], t(apply(Pc2, 1, diff))); Pk2 <- pmax(Pk2, 0); Pk2 <- Pk2 / rowSums(Pk2)
y2  <- apply(Pk2, 1, function(p) sample(1:5, 1, prob = p))
ss_np <- sep_slopes(y2, x2)
p227_spreadNP <- round(diff(range(ss_np)), 3)

## ---- fig-parallel ----
d2 <- data.frame(thr = factor(rep(c("1|2", "2|3", "3|4", "4|5"), 2)),
  slope = c(ss_po, ss_np), type = rep(c("Proportional odds", "Non-proportional"), each = 4))
ggplot(d2, aes(thr, slope, colour = type, group = type)) +
  geom_hline(yintercept = beta, colour = "#93a87f", linetype = "dashed") +
  geom_line(linewidth = 0.9) + geom_point(size = 3) +
  scale_colour_manual(values = c("Proportional odds" = "#275139", "Non-proportional" = "#b5534e")) +
  labs(x = "Cumulative split (class threshold)", y = "Slope from separate binary logit",
       title = "The parallel-slopes assumption, made visible") + theme_te()
