# Stage-structured Lefkovitch matrices in R
# https://tidyecology.com/posts/stage-structured-lefkovitch/
#
# 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_mown <- "#2f8f63"
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))
}

stages <- c("Seedling", "Juvenile", "Small adult", "Large adult")
A <- matrix(0, 4, 4, dimnames = list(stages, stages))
A["Juvenile",    "Seedling"]    <- 0.30   # survive and grow
A["Juvenile",    "Juvenile"]    <- 0.35   # stasis
A["Small adult", "Juvenile"]    <- 0.30   # survive and grow
A["Small adult", "Small adult"] <- 0.45   # stasis
A["Large adult", "Small adult"] <- 0.25   # survive and grow
A["Seedling",    "Small adult"] <- 1.60   # fecundity
A["Large adult", "Large adult"] <- 0.82   # stasis
A["Seedling",    "Large adult"] <- 3.00   # fecundity
A

## ---- fig-structure ----
df <- as.data.frame(as.table(A))
colnames(df) <- c("to", "from", "value")
df$to   <- factor(df$to,   levels = rev(stages))
df$from <- factor(df$from, levels = stages)
df$kind <- "zero"
df$kind[df$value > 0 & as.character(df$to) == "Seedling"] <- "fecundity"
df$kind[df$value > 0 & as.character(df$from) == as.character(df$to)] <- "stasis"
df$kind[df$value > 0 & df$kind == "zero"] <- "growth"
df$lab <- ifelse(df$value > 0, sprintf("%.2f", df$value), "")
ggplot(df, aes(from, to, fill = kind)) +
  geom_tile(colour = "white", linewidth = 1.2) +
  geom_text(aes(label = lab), colour = te_ink, size = 4) +
  scale_fill_manual(values = c(zero = "#eeece1", fecundity = te_gold,
                               stasis = te_faint, growth = te_mown), name = NULL) +
  labs(title = "A stage matrix has a non-zero diagonal",
       subtitle = "Fecundity in the top row, stasis on the diagonal, growth below it",
       x = "from stage", y = "to stage") +
  theme_te() +
  theme(panel.grid = element_blank(), axis.text.x = element_text(angle = 20, hjust = 1))

## ---- eigen ----
ev  <- eigen(A)
lam <- Re(ev$values[1])
w   <- Re(ev$vectors[, 1]); w <- w / sum(w)
c(lambda = lam)
round(100 * w, 1)

## ---- fig-stable ----
data.frame(stage = factor(stages, levels = stages), w = w) |>
  ggplot(aes(stage, w)) +
  geom_col(fill = te_forest, width = 0.68) +
  labs(title = "Stable stage distribution",
       subtitle = sprintf("Large adults hold %.0f%% because they persist for years", 100 * w[4]),
       x = NULL, y = "Proportion") +
  theme_te() + theme(axis.text.x = element_text(angle = 15, hjust = 1))

## ---- residence ----
stasis    <- diag(A)
residence <- 1 / (1 - stasis)
round(residence, 2)

## ---- no-stasis ----
A_nostasis <- A
diag(A_nostasis) <- 0
lam_nostasis <- Re(eigen(A_nostasis)$values[1])
c(with_stasis = lam, without_stasis = lam_nostasis)
