# Modelling non-constant variance with nlme
# https://tidyecology.com/posts/variance-structure-heteroscedasticity/
#
# 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-09-30

## ---- sim1 ----
library(nlme)

set.seed(7)
ng <- 40
mk <- function(level, mu, sdv) data.frame(mgmt = level, biomass = rnorm(ng, mu, sdv))
dat <- rbind(mk("Grazed", 10, 1.5), mk("Mown", 14, 2.2), mk("Abandoned", 18, 5.0))
dat$mgmt <- factor(dat$mgmt, levels = c("Grazed", "Mown", "Abandoned"))

round(tapply(dat$biomass, dat$mgmt, sd), 2)
bartlett.test(biomass ~ mgmt, data = dat)$p.value

## ---- fig-spread ----
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))
mgmt_cols <- c(Grazed = "#cda23f", Mown = "#2f8f63", Abandoned = "#b5534e")

ggplot(dat, aes(mgmt, biomass, colour = mgmt)) +
  geom_jitter(width = 0.12, alpha = 0.55, size = 1.3) +
  geom_boxplot(fill = NA, outlier.shape = NA, width = 0.45, linewidth = 0.6) +
  scale_colour_manual(values = mgmt_cols, guide = "none") +
  labs(x = NULL, y = "Biomass") +
  theme_minimal(base_size = 12) + te_canvas

## ---- fit1 ----
m0 <- gls(biomass ~ mgmt - 1, data = dat, method = "REML")
m1 <- gls(biomass ~ mgmt - 1, weights = varIdent(form = ~ 1 | mgmt),
          data = dat, method = "REML")

AIC(m0, m1)
anova(m0, m1)

## ---- varest ----
m1$sigma                                              # reference (Grazed) SD
coef(m1$modelStruct$varStruct, unconstrained = FALSE)  # multipliers

## ---- se1 ----
data.frame(mean        = coef(m1),
           SE_constant = sqrt(diag(vcov(m0))),
           SE_varIdent = sqrt(diag(vcov(m1))),
           row.names   = levels(dat$mgmt))

## ---- fig-ci ----
ci <- rbind(
  data.frame(mgmt = levels(dat$mgmt), model = "constant variance",
             mean = coef(m0), se = sqrt(diag(vcov(m0)))),
  data.frame(mgmt = levels(dat$mgmt), model = "varIdent (per group)",
             mean = coef(m1), se = sqrt(diag(vcov(m1)))))
ci$mgmt <- factor(ci$mgmt, levels = levels(dat$mgmt))
ci$lo <- ci$mean - 1.96 * ci$se
ci$hi <- ci$mean + 1.96 * ci$se

ggplot(ci, aes(mgmt, mean, colour = model)) +
  geom_point(position = position_dodge(0.4), size = 2.4) +
  geom_errorbar(aes(ymin = lo, ymax = hi), position = position_dodge(0.4),
                width = 0.18, linewidth = 0.8) +
  scale_colour_manual(values = c("constant variance" = "#9aa69d",
                                 "varIdent (per group)" = "#275139")) +
  labs(x = NULL, y = "Estimated group mean (95% CI)", colour = NULL) +
  theme_minimal(base_size = 12) + te_canvas +
  theme(legend.position = "top")

## ---- sim2 ----
set.seed(31)
n <- 120
x <- runif(n, 1, 10)
y <- 2 + 1.2 * x + rnorm(n, 0, 0.35 * x)   # sd proportional to x
d2 <- data.frame(x = x, y = y)

m0 <- gls(y ~ x, data = d2, method = "REML")
m1 <- gls(y ~ x, weights = varPower(form = ~ x), data = d2, method = "REML")
AIC(m0, m1)

## ---- power-est ----
coef(m1$modelStruct$varStruct, unconstrained = FALSE)  # power
m1$sigma                                                # scale

## ---- slope2 ----
rbind(
  constant = summary(m0)$tTable["x", c("Value", "Std.Error")],
  varPower = summary(m1)$tTable["x", c("Value", "Std.Error")]
)

## ---- fig-funnel ----
delta <- coef(m1$modelStruct$varStruct, unconstrained = FALSE)
gx <- seq(1, 10, length = 100)
band <- data.frame(x = gx, fit = coef(m1)[1] + coef(m1)[2] * gx,
                   sd = m1$sigma * gx^delta)

ggplot(d2, aes(x, y)) +
  geom_ribbon(data = band, aes(x = x, ymin = fit - 1.96 * sd, ymax = fit + 1.96 * sd),
              inherit.aes = FALSE, fill = "#c9b458", alpha = 0.25) +
  geom_point(colour = "#5d6b61", alpha = 0.6, size = 1.4) +
  geom_line(data = band, aes(x, fit), inherit.aes = FALSE,
            colour = "#275139", linewidth = 1) +
  labs(x = "Predictor x", y = "Biomass") +
  theme_minimal(base_size = 12) + te_canvas
