# Additive diversity partitioning in R
# https://tidyecology.com/posts/additive-diversity-partitioning/
#
# 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(vegan)
library(ggplot2)

theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(
      plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
      panel.background = element_rect(fill = "#f5f4ee", colour = NA),
      panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3),
      panel.grid.minor = element_blank(),
      axis.text   = element_text(colour = "#46604a"),
      axis.title  = element_text(colour = "#2c3a31"),
      plot.title  = element_text(colour = "#16241d", face = "bold"),
      plot.subtitle = element_text(colour = "#5d6b61"),
      strip.text  = element_text(colour = "#16241d", face = "bold"),
      legend.position = "none"
    )
}
forest <- "#275139"; label <- "#46604a"; sage <- "#93a87f"
red <- "#b5534e"; faint <- "#5d6b61"; gold <- "#cda23f"

## ---- simulate ----
set.seed(20)
nreg <- 3; per <- 5; nsamp <- nreg * per; npool <- 60
region <- factor(rep(paste0("R", 1:nreg), each = per))
comm <- matrix(0, nsamp, npool)
for (k in 1:nreg) {
  start <- (k - 1) * 16 + 1
  pool  <- start:min(start + 27, npool)          # overlapping regional pool
  for (r in which(region == paste0("R", k))) {
    present <- sample(pool, size = sample(10:16, 1))
    comm[r, present] <- rpois(length(present), 4) + 1
  }
}
comm <- comm[, colSums(comm) > 0]
c(samples = nrow(comm), species = ncol(comm), gamma = sum(colSums(comm) > 0))

## ---- adipart ----
dat <- data.frame(region = region)
set.seed(5)
ap <- adipart(comm ~ region, dat, index = "richness",
              weights = "unif", nsimul = 999)
S <- ap$statistic
a1 <- S[["alpha.1"]]; b1 <- S[["beta.1"]]
a2 <- S[["alpha.2"]]; b2 <- S[["beta.2"]]; g <- S[["gamma"]]
round(c(alpha.sample = a1, beta.within = b1,
        alpha.region = a2, beta.among = b2, gamma = g), 1)

## ---- fig-partition ----
comp <- data.frame(
  part = factor(c("mean sample richness (alpha)",
                  "among samples within region (beta 1)",
                  "among regions (beta 2)"),
                levels = c("among regions (beta 2)",
                           "among samples within region (beta 1)",
                           "mean sample richness (alpha)")),
  value = c(a1, b1, b2))
comp$lab <- sprintf("%.1f", comp$value)

ggplot(comp, aes(x = "community", y = value, fill = part)) +
  geom_col(width = 0.5, colour = "#f5f4ee", linewidth = 0.6) +
  geom_text(aes(label = lab), position = position_stack(vjust = 0.5),
            colour = c("white", "#16241d", "#16241d"), size = 4.4, fontface = "bold") +
  annotate("text", x = "community", y = g + 1.2,
           label = paste0("gamma = ", sprintf("%.0f", g)),
           colour = "#16241d", fontface = "bold", size = 4.2, hjust = 0) +
  scale_fill_manual(values = c("mean sample richness (alpha)" = forest,
                               "among samples within region (beta 1)" = sage,
                               "among regions (beta 2)" = gold),
                    guide = guide_legend(reverse = TRUE)) +
  scale_y_continuous(limits = c(0, 72), expand = expansion(mult = c(0, 0))) +
  coord_flip() +
  labs(x = NULL, y = "species richness",
       title = "Additive partition: gamma = alpha + beta, in species",
       subtitle = "total richness splits into mean local richness plus two turnover layers") +
  theme_te() +
  theme(legend.position = "top", legend.title = element_blank(),
        legend.text = element_text(colour = "#2c3a31", size = 8.5),
        axis.text.y = element_blank())

## ---- null-test ----
z  <- ap$oecosimu$z;    names(z)  <- names(S)
p  <- ap$oecosimu$pval; names(p)  <- names(S)
mn <- ap$oecosimu$means; names(mn) <- names(S)
round(c(among_region_obs = b2, among_region_null = mn[["beta.2"]],
        z = z[["beta.2"]], p = p[["beta.2"]]), 2)

## ---- fig-null ----
dfb <- data.frame(beta2 = ap$oecosimu$simulated[5, ])

ggplot(dfb, aes(beta2)) +
  geom_histogram(bins = 40, fill = forest, colour = NA, alpha = 0.85) +
  geom_vline(xintercept = b2, colour = red, linewidth = 0.8) +
  annotate("text", x = b2 - 1, y = Inf, label = paste0("observed = ", sprintf("%.0f", b2)),
           hjust = 1, vjust = 1.8, colour = red, size = 3.6, fontface = "bold") +
  annotate("text", x = 6, y = Inf,
           label = paste0("null mean = ", sprintf("%.1f", mn[["beta.2"]]),
                          "\nz = ", sprintf("%.0f", z[["beta.2"]])),
           hjust = 0, vjust = 1.6, colour = faint, size = 3.5) +
  scale_y_continuous(expand = expansion(mult = c(0, 0.08))) +
  labs(x = "among-region beta under the individual-based null", y = "count",
       title = "Among-region beta far exceeds the individual-based null",
       subtitle = "observed among-region beta against 999 randomised communities") +
  theme_te()

## ---- demo ----
N <- 3; Sseq <- 2:30
demo <- data.frame(
  S         = Sseq,
  add_GS    = (1 - 1 / (N * Sseq)) - (1 - 1 / Sseq),   # additive Gini-Simpson
  mult_Hill = (N * Sseq) / Sseq)                       # multiplicative Hill, q = 2
c(add_GS_low = demo$add_GS[1], add_GS_high = demo$add_GS[length(Sseq)],
  mult_Hill  = demo$mult_Hill[1])

## ---- fig-index ----
dd <- rbind(
  data.frame(S = demo$S, beta = demo$add_GS,    panel = "additive (Gini-Simpson index)"),
  data.frame(S = demo$S, beta = demo$mult_Hill, panel = "multiplicative (Hill numbers, q = 2)"))
dd$panel <- factor(dd$panel, levels = c("additive (Gini-Simpson index)",
                                        "multiplicative (Hill numbers, q = 2)"))

ggplot(dd, aes(S, beta)) +
  geom_line(colour = forest, linewidth = 1) +
  geom_point(colour = forest, size = 1.3) +
  facet_wrap(~panel, scales = "free_y") +
  labs(x = "species per region (local richness)", y = "beta diversity",
       title = "Why the choice of index matters",
       subtitle = "three fully distinct regions throughout; only the index and the partition differ") +
  theme_te() +
  theme(strip.text = element_text(size = 10.5))
