# Life table response experiments (LTRE) in R
# https://tidyecology.com/posts/life-table-response-experiment/
#
# 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

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

## ---- theme ----
te_ink <- "#16241d"; te_body <- "#2c3a31"; te_forest <- "#275139"
te_label <- "#46604a"; te_sage <- "#93a87f"; te_paper <- "#f5f4ee"
te_line <- "#dad9ca"; te_gold <- "#c9b458"; te_deep <- "#1d5b4e"
te_brick <- "#b5534e"; te_faint <- "#5d6b61"
theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(text = element_text(colour = te_body),
          plot.title = element_text(colour = te_ink, face = "bold"),
          plot.subtitle = element_text(colour = te_faint),
          axis.title = element_text(colour = te_label),
          axis.text = element_text(colour = te_body),
          panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          strip.text = element_text(colour = te_ink, face = "bold"),
          plot.background = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          legend.position = "none")
}

## ---- matrices ----
A_control <- matrix(c(0,    0,    1.0,
                      0.30, 0.30, 0,
                      0,    0.26, 0.90), nrow = 3, byrow = TRUE)
A_treat   <- matrix(c(0,    0,    1.8,
                      0.34, 0.30, 0,
                      0,    0.30, 0.80), nrow = 3, byrow = TRUE)

lambda <- function(A) {
  ev <- eigen(A); Re(ev$values[which.max(Re(ev$values))])
}
lam_c <- lambda(A_control); lam_t <- lambda(A_treat)
c(lambda_control = lam_c, lambda_treatment = lam_t, delta_lambda = lam_t - lam_c)

## ---- sensitivities ----
sensitivity <- function(A) {
  ev <- eigen(A); i <- which.max(Re(ev$values))
  w <- Re(ev$vectors[, i])
  evL <- eigen(t(A)); iL <- which.max(Re(evL$values))
  v <- Re(evL$vectors[, iL])
  outer(v, w) / sum(v * w)
}
A_mid <- (A_control + A_treat) / 2
S_mid <- sensitivity(A_mid)
round(S_mid, 3)

## ---- contributions ----
dA <- A_treat - A_control
contr <- dA * S_mid

cells <- list(c(1, 3), c(3, 3), c(2, 1), c(3, 2))
labels <- c("Fecundity (large adult)", "Adult survival (large stasis)",
            "Growth small to medium", "Growth medium to large")
tab <- data.frame(
  element = labels,
  raw_difference = sapply(cells, function(k) dA[k[1], k[2]]),
  sensitivity = sapply(cells, function(k) round(S_mid[k[1], k[2]], 3)),
  contribution = sapply(cells, function(k) round(contr[k[1], k[2]], 4)))
tab

c(sum_of_contributions = sum(contr), delta_lambda = lam_t - lam_c,
  residual = (lam_t - lam_c) - sum(contr))

## ---- fig-tornado ----
res <- data.frame(short = c("Fecundity", "Adult survival", "Growth S->M", "Growth M->L"),
                  contr = sapply(cells, function(k) contr[k[1], k[2]]),
                  raw = sapply(cells, function(k) dA[k[1], k[2]]))
res$sign <- ifelse(res$contr >= 0, "pos", "neg")
res1 <- res |> arrange(contr) |> mutate(short = factor(short, levels = short))

ggplot(res1, aes(contr, short, fill = sign)) +
  geom_col(width = 0.62) +
  geom_vline(xintercept = 0, colour = te_faint, linewidth = 0.4) +
  scale_fill_manual(values = c(pos = te_forest, neg = te_brick)) +
  geom_text(aes(label = sprintf("%+.3f", contr),
                hjust = ifelse(contr >= 0, -0.15, 1.15)),
            colour = te_body, size = 3.1) +
  labs(title = "Which vital-rate differences drive the change in growth",
       subtitle = sprintf("Contributions sum approximately to the growth difference of %+.3f", lam_t - lam_c),
       x = "Contribution to the change in growth", y = NULL) +
  coord_cartesian(xlim = c(-0.095, 0.095)) +
  theme_te()

## ---- fig-reorder ----
ord <- res |> arrange(desc(abs(raw))) |> pull(short)
long <- res |>
  transmute(short,
            `Raw vital-rate difference` = raw,
            `LTRE contribution` = contr) |>
  pivot_longer(-short, names_to = "panel", values_to = "value") |>
  mutate(short = factor(short, levels = rev(ord)),
         panel = factor(panel, levels = c("Raw vital-rate difference", "LTRE contribution")),
         sign = ifelse(value >= 0, "pos", "neg"))

ggplot(long, aes(value, short, fill = sign)) +
  geom_col(width = 0.62) +
  geom_vline(xintercept = 0, colour = te_faint, linewidth = 0.4) +
  scale_fill_manual(values = c(pos = te_forest, neg = te_brick)) +
  facet_wrap(~panel, scales = "free_x") +
  labs(title = "Biggest raw change is not the biggest contribution",
       subtitle = "Fecundity has the largest raw change;\nadult survival, far more sensitive, contributes most",
       x = NULL, y = NULL) +
  theme_te()
