# Beta regression for proportion and cover data
# https://tidyecology.com/posts/beta-regression-for-proportions/
#
# 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-11-13

## ---- dgp ----
set.seed(4284)
n   <- 180
x   <- round(runif(n, -2, 2), 3)          # standardised soil moisture
b0  <- 0.4; b1 <- 1.15                     # true mean model (logit scale)
phi <- 9                                   # true precision
mu  <- plogis(b0 + b1 * x)
y   <- rbeta(n, mu * phi, (1 - mu) * phi)  # cover as a proportion in (0, 1)

## ---- 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)), "}$")
}

## ---- beta-fit ----
negll <- function(par, y, X) {
  k   <- ncol(X)
  mu  <- plogis(X %*% par[1:k])
  phi <- exp(par[k + 1])
  -sum(dbeta(y, mu * phi, (1 - mu) * phi, log = TRUE))
}
X   <- cbind(1, x)
fit <- optim(c(0, 0, log(5)), negll, y = y, X = X, method = "BFGS", hessian = TRUE)
stopifnot(fit$convergence == 0)   # check before inverting the Hessian
bh  <- fit$par[1:2]
phih <- exp(fit$par[3])
se  <- sqrt(diag(solve(fit$hessian)))     # asymptotic SE from the Hessian
p226_b1  <- round(bh[2], 3)
p226_b1se <- round(se[2], 3)
p226_phi <- round(phih, 2)

## ---- score-check ----
g <- sapply(1:3, function(j) {
  e <- 1e-6; p1 <- fit$par; p2 <- fit$par; p1[j] <- p1[j] - e; p2[j] <- p2[j] + e
  (negll(p2, y, X) - negll(p1, y, X)) / (2 * e)
})
p226_score <- signif(max(abs(g)), 2)

## ---- naive-ols ----
ols <- lm(qlogis(y) ~ x)
p226_ols <- round(coef(ols)[2], 3)

## ---- fig-fit ----
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.position = "top", legend.title = element_blank(),
    legend.text = element_text(colour = "#2c3a31"))
}
xs  <- seq(-2, 2, length = 200)
mus <- plogis(bh[1] + bh[2] * xs)
lo  <- qbeta(.05, mus * phih, (1 - mus) * phih)
hi  <- qbeta(.95, mus * phih, (1 - mus) * phih)
om  <- plogis(coef(ols)[1] + coef(ols)[2] * xs)
dl  <- data.frame(xs, mus, lo, hi, om)
ggplot() +
  geom_ribbon(data = dl, aes(xs, ymin = lo, ymax = hi), fill = "#2f8f63", alpha = 0.15) +
  geom_point(data = data.frame(x, y), aes(x, y), colour = "#275139", alpha = 0.45, size = 1.6) +
  geom_line(data = dl, aes(xs, mus, colour = "Beta mean"), linewidth = 1) +
  geom_line(data = dl, aes(xs, om, colour = "logit + OLS"), linewidth = 1, linetype = "dashed") +
  scale_colour_manual(values = c("Beta mean" = "#275139", "logit + OLS" = "#b5534e")) +
  scale_y_continuous(limits = c(0, 1)) +
  labs(x = "Soil moisture (standardised)", y = "Vegetation cover (proportion)",
       title = "Beta regression for bounded cover data") +
  theme_te()

## ---- monte-carlo ----
set.seed(101)
B <- 2000
sb <- so <- numeric(B)
for (b in 1:B) {
  mb <- plogis(b0 + b1 * x)
  yb <- rbeta(n, mb * phi, (1 - mb) * phi)
  sb[b] <- optim(c(0, 0, log(5)), negll, y = yb, X = X, method = "BFGS")$par[2]
  so[b] <- coef(lm(qlogis(yb) ~ x))[2]
}
p226_biasBeta <- round(100 * (mean(sb) - b1) / b1, 1)
p226_biasOls  <- round(100 * (mean(so) - b1) / b1, 1)
p226_sdratio  <- round(sd(so) / sd(sb), 2)

## ---- fig-mc ----
d2 <- rbind(data.frame(slope = sb, method = "Beta ML"),
            data.frame(slope = so, method = "logit + OLS"))
ggplot(d2, aes(slope, fill = method)) +
  geom_histogram(alpha = 0.55, position = "identity", bins = 45, colour = NA) +
  geom_vline(xintercept = b1, colour = "#16241d", linewidth = 0.7) +
  scale_fill_manual(values = c("Beta ML" = "#2f8f63", "logit + OLS" = "#c9b458")) +
  labs(x = "Estimated slope", y = "Count",
       title = "Sampling distribution of the slope (2000 datasets)") +
  theme_te()

## ---- variable-dispersion ----
set.seed(4285)
xd  <- round(runif(n, -2, 2), 3)
mud <- plogis(0.3 + 0.9 * xd)
phid <- exp(2.4 - 0.7 * xd)                 # precision shrinks as moisture rises
yd  <- rbeta(n, mud * phid, (1 - mud) * phid)
Xd  <- cbind(1, xd)
nll_c <- function(p) { mu <- plogis(Xd %*% p[1:2]); ph <- exp(p[3])
  -sum(dbeta(yd, mu * ph, (1 - mu) * ph, log = TRUE)) }
nll_v <- function(p) { mu <- plogis(Xd %*% p[1:2]); ph <- exp(Xd %*% p[3:4])
  -sum(dbeta(yd, mu * ph, (1 - mu) * ph, log = TRUE)) }
fc <- optim(c(0, 0, log(5)), nll_c, method = "BFGS")
fv <- optim(c(0, 0, 2, 0), nll_v, method = "BFGS")
LR <- 2 * (fc$value - fv$value)
p226_g1   <- round(fv$par[4], 3)
p226_LR   <- round(LR, 1)
p226_LRp  <- signif(pchisq(LR, 1, lower.tail = FALSE), 3)
p226_dAIC <- round(2 * (fc$value - fv$value) - 2, 1)

## ---- boundary ----
set.seed(4286)
xb2  <- round(runif(120, -2, 2), 3)
mub2 <- plogis(0.2 + 0.8 * xb2)
yb2  <- rbeta(120, mub2 * 7, (1 - mub2) * 7)      # precision fixed at 7 across the gradient
yb2[sample(120, 6)] <- 0
yb2[sample(120, 4)] <- 1
n2  <- length(yb2)
ysv <- (yb2 * (n2 - 1) + 0.5) / n2
p226_nzero <- sum(yb2 == 0)
p226_none  <- sum(yb2 == 1)
p226_sv0   <- round(min(ysv), 4)

## ---- honest-limit ----
set.seed(4287)
ntr <- round(runif(150, 8, 25))
xc  <- round(runif(150, -2, 2), 3)
pc  <- plogis(0.3 + 1.0 * xc)
k   <- rbinom(150, ntr, pc)
bin <- glm(cbind(k, ntr - k) ~ xc, family = binomial)
p226_bin   <- round(coef(bin)[2], 3)
p226_binse <- round(summary(bin)$coefficients[2, 2], 3)
