# Marginal vs conditional R-squared in mixed models
# https://tidyecology.com/posts/marginal-vs-conditional-r2/
#
# 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-10-14

## ---- sim ----
library(nlme)

set.seed(44)
nsite <- 20; nrep <- 10
site <- factor(rep(sprintf("S%02d", 1:nsite), each = nrep))
a <- rnorm(nsite, 0, 2)                  # site intercepts
x <- rnorm(nsite * nrep, 0, 1)
y <- 5 + 1.5 * x + a[as.integer(site)] + rnorm(nsite * nrep, 0, 1.5)
dat <- data.frame(site = site, x = x, y = y)

m <- lme(y ~ x, random = ~ 1 | site, data = dat, method = "REML")
summary(m)$tTable

## ---- components ----
var_f <- var(as.vector(predict(m, level = 0)))          # fixed effects
var_a <- as.numeric(VarCorr(m)["(Intercept)", "Variance"])  # random intercept
var_e <- sigma(m)^2                                     # residual

c(fixed = var_f, random = var_a, residual = var_e)

## ---- r2 ----
total <- var_f + var_a + var_e
R2_marginal    <- var_f / total
R2_conditional <- (var_f + var_a) / total

c(marginal = R2_marginal, conditional = R2_conditional)

## ---- fig-decomp ----
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))

ord <- data.frame(part = c("fixed effects", "random (site)", "residual"),
                   frac = c(var_f, var_a, var_e) / total)
ord$xmin <- c(0, cumsum(ord$frac)[-3])
ord$xmax <- cumsum(ord$frac)
ord$part <- factor(ord$part, levels = ord$part)
cols <- c("fixed effects" = "#275139", "random (site)" = "#c9b458",
          "residual" = "#dad9ca")

ggplot(ord) +
  geom_rect(aes(xmin = xmin, xmax = xmax, ymin = 0, ymax = 1, fill = part),
            colour = "#f5f4ee", linewidth = 1) +
  scale_fill_manual(values = cols, name = NULL) +
  geom_vline(xintercept = R2_marginal,    colour = "#16241d",
             linewidth = 0.5, linetype = "dashed") +
  geom_vline(xintercept = R2_conditional, colour = "#16241d",
             linewidth = 0.5, linetype = "dashed") +
  annotate("text", x = R2_marginal, y = 1.12,
           label = sprintf("Marginal R2 = %.2f", R2_marginal),
           hjust = -0.05, size = 3.6, colour = "#16241d") +
  annotate("text", x = R2_conditional, y = 1.26,
           label = sprintf("Conditional R2 = %.2f", R2_conditional),
           hjust = 1.05, size = 3.6, colour = "#16241d") +
  scale_x_continuous(limits = c(0, 1), breaks = seq(0, 1, 0.2), expand = c(0.02, 0)) +
  scale_y_continuous(limits = c(0, 1.34), expand = c(0, 0)) +
  labs(x = "Proportion of total variance", y = NULL) +
  theme_minimal(base_size = 12) + te_canvas +
  theme(axis.text.y = element_blank(), panel.grid.major.y = element_blank(),
        panel.grid.minor = element_blank(), legend.position = "bottom")
