# Intraspecific trait variability in R
# https://tidyecology.com/posts/intraspecific-trait-variability/
#
# 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

## ---- build ----
build <- function(seed, tolr, plast, turn = 18) {
  set.seed(seed)
  n_site <- 40; n_sp <- 24
  moist <- seq(0, 1, length.out = n_site)
  opt   <- runif(n_sp, -0.10, 1.10)                    # where the species prefers to grow
  base  <- 19 - turn * 0.5 + turn * opt + rnorm(n_sp, 0, 2.6)
  mu <- outer(moist, opt, function(e, o) exp(-(e - o)^2 / (2 * tolr^2)))
  A  <- matrix(rpois(n_site * n_sp, sweep(mu, 2, rlnorm(n_sp, log(26), 0.35), "*")),
               n_site, n_sp)
  Tij <- outer(rep(1, n_site), base) + plast * outer(moist - 0.5, rep(1, n_sp))
  list(A = A, e = moist, Tij = Tij, opt = opt, base = base)
}

## ---- parts ----
parts <- function(s) {
  spec <- rowSums(s$A * s$Tij) / rowSums(s$A)             # specific averaging
  spmn <- colSums(s$A * s$Tij) / colSums(s$A)             # one trait value per species
  fix  <- as.vector(s$A %*% spmn) / rowSums(s$A)          # fixed averaging
  list(spec = spec, fix = fix, itv = spec - fix, spmn = spmn)
}

## ---- algebra ----
ssq <- function(y, x) { f <- lm(y ~ x); sum((fitted(f) - mean(y))^2) }
bof <- function(y, x) unname(coef(lm(y ~ x))[2])
decomp <- function(p, x) {
  ss <- c(turnover = ssq(p$fix, x), intraspecific = ssq(p$itv, x))
  tot <- ssq(p$spec, x)
  c(ss, covariation = tot - sum(ss), total = tot,
    b_fix = bof(p$fix, x), b_itv = bof(p$itv, x), b_spec = bof(p$spec, x),
    cross = 2 * bof(p$fix, x) * bof(p$itv, x) * sum((x - mean(x))^2))
}
sM <- build(3092, tolr = 0.45, plast = 8)        # turnover and plasticity, both alive
dM <- unname(decomp(parts(sM), sM$e))
names(dM) <- c("turnover", "intraspecific", "covariation", "total",
               "b_fix", "b_itv", "b_spec", "cross")
c(dM[c("b_fix", "b_itv", "b_spec")],
  additive_gap = abs(dM["b_fix"] + dM["b_itv"] - dM["b_spec"]))

## ---- cross ----
c(dM[c("covariation", "cross")], gap = abs(dM["covariation"] - dM["cross"]))

## ---- caseA ----
sA <- build(309, tolr = 0.20, plast = 0)         # turnover only
dA <- unname(decomp(parts(sA), sA$e))
c(pc_turnover = 100 * dA[1] / dA[4], pc_itv = 100 * dA[2] / dA[4],
  pc_cov = 100 * dA[3] / dA[4], b_itv = dA[6])

## ---- caseB ----
sB <- build(309, tolr = 5, plast = 12, turn = 0)   # no habitat preference, plastic plants
pB <- parts(sB); dB <- decomp(pB, sB$e)
rbind(database = coef(summary(lm(pB$fix  ~ sB$e)))[2, ],
      field    = coef(summary(lm(pB$spec ~ sB$e)))[2, ])

## ---- sci-tex-helper ----
sci_tex <- function(x, digits = 2) {
  s <- formatC(x, format = "e", digits = digits)
  paste0("$", sub("e.*", "", s), " \\times 10^{", as.integer(sub(".*e", "", s)), "}$")
}

## ---- fig-cases ----
suppressMessages(library(ggplot2))
theme_te <- theme_minimal(base_size = 11) +
  theme(
        plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
        panel.background = element_rect(fill = "#f5f4ee", colour = NA),
        panel.grid.minor = element_blank(),
        panel.grid.major = element_line(colour = "#e8e7dc", linewidth = 0.3),
        axis.title = element_text(colour = "#46604a"),
        axis.text  = element_text(colour = "#5d6b61"),
        plot.title = element_text(colour = "#16241d", face = "bold", size = 11.5),
        plot.subtitle = element_text(colour = "#5d6b61", size = 9.5),
        strip.text = element_text(colour = "#16241d", face = "bold"),
        legend.position = "top", legend.title = element_blank(),
        legend.text = element_text(colour = "#2c3a31"))
pA <- parts(sA)
mk <- function(p, s, lab) data.frame(
  e = rep(s$e, 3), v = c(p$spec, p$fix, p$itv - mean(p$itv) + 19),
  series = rep(c("specific (measured in the plot)", "fixed (one value per species)",
                 "intraspecific part (shifted to 19)"), each = length(s$e)),
  case = lab)
fd <- rbind(mk(pA, sA, "all turnover: plasticity off"),
            mk(pB, sB, "all plasticity: no habitat preference"))
p_cases <- ggplot(fd, aes(e, v, colour = series)) +
  geom_line(linewidth = 0.95) +
  facet_wrap(~case) +
  scale_colour_manual(values = c("specific (measured in the plot)" = "#275139",
                                 "fixed (one value per species)" = "#cda23f",
                                 "intraspecific part (shifted to 19)" = "#b5534e")) +
  guides(colour = guide_legend(nrow = 2)) +
  labs(x = "soil moisture (gradient position)", y = "community weighted mean SLA",
       title = "Same trait, same gradient, two mechanisms",
       subtitle = "the database sees only the turnover panel") +
  theme_te
p_cases

## ---- thumb ----
ggsave("thumbnail.png", p_cases, width = 7.5, height = 5.4, dpi = 100)

## ---- sweep ----
gr <- c(0, -4, -8, -11, -14)
tab <- t(vapply(gr, function(pl) {
  s <- build(3091, tolr = 0.45, plast = pl); d <- unname(decomp(parts(s), s$e))
  ## decomp() order: turnover, intraspecific, covariation, total, b_fix, b_itv, b_spec, cross
  c(plasticity = pl, b_fix = d[5], b_itv = d[6], b_spec = d[7],
    pc_turnover = 100 * d[1] / d[4], pc_itv = 100 * d[2] / d[4], pc_cov = 100 * d[3] / d[4])
}, numeric(7)))
print(round(tab, 1))

## ---- fig-slopes ----
gg <- seq(0, -16, by = -1)
sl <- do.call(rbind, lapply(gg, function(pl) {
  s <- build(3091, tolr = 0.45, plast = pl); d <- decomp(parts(s), s$e)
  data.frame(plast = pl, slope = c(d["b_fix"], d["b_itv"], d["b_spec"]),
             which = c("turnover (fixed averaging)", "intraspecific",
                       "community trend (their sum)"))
}))
ggplot(sl, aes(plast, slope, colour = which)) +
  geom_hline(yintercept = 0, colour = "#93a87f", linewidth = 0.4) +
  geom_line(linewidth = 1.05) +
  scale_colour_manual(values = c("turnover (fixed averaging)" = "#cda23f",
                                 "intraspecific" = "#b5534e",
                                 "community trend (their sum)" = "#275139")) +
  labs(x = "plasticity: change in SLA per unit moisture, within a species",
       y = "slope of the CWM against moisture",
       title = "The three slopes across the plasticity sweep",
       subtitle = "the community trend crosses zero, and the percentage table's denominator is zero there") +
  theme_te

## ---- breadth ----
grid <- c(0.10, 0.14, 0.20, 0.28, 0.40, 0.55, 0.80, 1.20)
br <- t(vapply(grid, function(tl) {
  s <- build(3092, tolr = tl, plast = 8); p <- parts(s); d <- unname(decomp(p, s$e))
  cwo <- colSums(s$A * s$e) / colSums(s$A)                      # mean moisture per species
  brd <- mean(sqrt(colSums(s$A * (s$e - rep(cwo, each = nrow(s$A)))^2) / colSums(s$A)))
  c(tolerance = tl, niche_sd = brd, pc_turnover = 100 * d[1] / d[4], pc_itv = 100 * d[2] / d[4],
    intrinsic = bof(s$base, s$opt), from_survey = bof(p$spmn, s$opt))
}, numeric(6)))
print(round(br, 2))

## ---- fig-breadth ----
bd <- data.frame(x = rep(br[, "tolerance"], 2),
                 y = c(br[, "pc_turnover"], br[, "pc_itv"]),
                 which = rep(c("turnover", "intraspecific"), each = nrow(br)))
ggplot(bd, aes(x, y, colour = which)) +
  geom_line(linewidth = 1.05) + geom_point(size = 1.9) +
  scale_x_log10(breaks = br[, "tolerance"], labels = br[, "tolerance"]) +
  scale_colour_manual(values = c("turnover" = "#cda23f", "intraspecific" = "#b5534e")) +
  labs(x = "niche width: sd of the species response curve (the gradient is one unit long)",
       y = "share of the community trend (%)",
       title = "The same plants, the same plasticity",
       subtitle = "the turnover / intraspecific split moves with niche width, not only with plasticity") +
  theme_te
