# The Leslie matrix: a worked example in R
# https://tidyecology.com/posts/leslie-matrix-population-models/
#
# 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-15

## ---- setup ----
library(ggplot2)
library(dplyr)
library(tidyr)

te_ink <- "#16241d"; te_forest <- "#275139"; te_gold <- "#c9b458"
te_faint <- "#5d6b61"; te_line <- "#dad9ca"; te_paper <- "#f5f4ee"
theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(text = element_text(colour = "#2c3a31"),
          plot.title = element_text(colour = te_ink, face = "bold", size = base_size * 1.15),
          plot.subtitle = element_text(colour = te_faint, size = base_size * 0.95),
          axis.title = element_text(colour = "#46604a"), axis.text = element_text(colour = te_faint),
          panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          plot.background = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          legend.key = element_rect(fill = te_paper, colour = NA),
          strip.text = element_text(colour = te_ink, face = "bold"))
}

## same demography as the life-table post; census just before breeding,
## so newborns first appear at age 1 (ages 1 to 5 are the matrix classes)
p0        <- 0.50                          # first-year survival (age 0 to 1)
surv_1to5 <- c(0.60, 0.70, 0.70, 0.50)     # survival age 1->2, 2->3, 3->4, 4->5
m_age     <- c(0.00, 1.50, 2.00, 1.70, 1.00)  # fecundity at ages 1 to 5

Fi <- p0 * m_age                            # pre-breeding fertility coefficient
L  <- matrix(0, 5, 5)
L[1, ] <- Fi
for (i in 1:4) L[i + 1, i] <- surv_1to5[i]
L

## ---- naive-vs-correct ----
L_naive <- L
L_naive[1, ] <- m_age                       # fertility without first-year survival
lam_correct <- Re(eigen(L)$values[1])
lam_naive   <- Re(eigen(L_naive)$values[1])
c(correct = lam_correct, naive = lam_naive,
  overestimate_pct = 100 * (lam_naive - lam_correct) / lam_correct)

## ---- eigenvalue ----
ev  <- eigen(L)
lam <- Re(ev$values[1])
lam2 <- sort(Mod(ev$values), decreasing = TRUE)[2]
c(lambda = lam, second_modulus = lam2)

## ---- projection ----
n0 <- c(100, 0, 0, 0, 0)
steps <- 20
N <- matrix(0, steps + 1, 5); N[1, ] <- n0
for (t in 1:steps) N[t + 1, ] <- as.numeric(L %*% N[t, ])

total <- rowSums(N)
ratio <- total[-1] / total[-length(total)]
c(ratio_year1 = ratio[1], ratio_year10 = ratio[10], ratio_year20 = ratio[20], lambda = lam)

## ---- fig-convergence ----
prop <- N / rowSums(N)
pd <- as.data.frame(prop); colnames(pd) <- paste("age", 1:5); pd$year <- 0:steps
pd_long <- pivot_longer(pd, starts_with("age"), names_to = "class", values_to = "prop")
ggplot(pd_long, aes(year, prop, colour = class)) +
  geom_line(linewidth = 0.9) +
  scale_colour_manual(values = c("#275139", "#2f8f63", "#93a87f", "#c9b458", "#b5534e"),
                      name = NULL) +
  labs(title = "Age structure converges to a stable distribution",
       subtitle = "Starting with everyone in age 1, the proportions settle within about ten years",
       x = "Year", y = "Proportion in age class") +
  theme_te()

## ---- stable-distribution ----
w <- Re(ev$vectors[, 1]); w <- w / sum(w)
round(100 * w, 1)

## ---- reproductive-value ----
vleft <- Re(eigen(t(L))$vectors[, 1])
vleft <- vleft / vleft[1]                    # scale so age 1 has value 1
round(vleft, 3)

## ---- fig-signatures ----
sig <- data.frame(age = factor(1:5), stable = w, rv = vleft) |>
  pivot_longer(c(stable, rv), names_to = "quantity", values_to = "value")
sig$quantity <- factor(sig$quantity, levels = c("stable", "rv"),
                       labels = c("Stable age distribution", "Reproductive value"))
ggplot(sig, aes(age, value, fill = quantity)) +
  geom_col(width = 0.7, show.legend = FALSE) +
  facet_wrap(~quantity, scales = "free_y") +
  scale_fill_manual(values = c(te_forest, te_gold)) +
  labs(title = "Two demographic signatures from the same matrix",
       subtitle = "Left: emergent age proportions. Right: expected future reproduction by age.",
       x = "Age class", y = NULL) +
  theme_te()
