# Fourth-corner trait-environment analysis
# https://tidyecology.com/posts/fourth-corner-trait-environment/
#
# 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-07

## ---- setup ----
library(MASS)
library(ggplot2)

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

## ---- stat ----
r4 <- function(E, T, L) {
  W <- sum(L); rs <- rowSums(L); cs <- colSums(L)
  Eb <- sum(rs * E) / W; Tb <- sum(cs * T) / W        # abundance-weighted means
  Ec <- E - Eb; Tc <- T - Tb
  cov <- as.numeric(Ec %*% L %*% Tc) / W               # weighted covariance
  vE  <- sum(rs * Ec^2) / W; vT <- sum(cs * Tc^2) / W  # weighted variances
  cov / sqrt(vE * vT)
}

## ---- test ----
fourth_test <- function(E, T, L, B = 199, seed = 1) {
  set.seed(seed); obs <- abs(r4(E, T, L)); n <- nrow(L); S <- ncol(L)
  p2 <- (1 + sum(replicate(B, abs(r4(E, T, L[sample(n), , drop = FALSE]))) >= obs)) / (B + 1)
  p4 <- (1 + sum(replicate(B, abs(r4(E, T, L[, sample(S), drop = FALSE]))) >= obs)) / (B + 1)
  c(obs = obs, p2 = p2, p4 = p4, pmax = max(p2, p4))
}

## ---- datasets ----
gen <- function(seed, gamma = 0, n = 40, S = 30, size = 2) {
  set.seed(seed)
  E <- rnorm(n); T <- rnorm(S)
  cj   <- rnorm(S, log(c(rep(6,10), rep(2,10), rep(0.8,10))), 0.2)   # species abundances
  beta <- gamma * T + rnorm(S, 0, 0.9)                               # env-response of each species
  mu   <- exp(outer(rep(1,n), cj) + outer(E, beta))
  list(E = E, T = T, L = matrix(rnbinom(n*S, mu = as.vector(mu), size = size), n, S))
}
dn <- gen(seed = 11, gamma = 0)     # no trait-environment link
dr <- gen(seed = 11, gamma = 1.1)   # trait modulates the response
pn <- fourth_test(dn$E, dn$T, dn$L, B = 999, seed = 5)
pr <- fourth_test(dr$E, dr$T, dr$L, B = 999, seed = 5)
rbind(null = round(pn, 3), real = round(pr, 3))

## ---- typeone ----
M <- 300; n <- 40; S <- 30; B <- 199
p2v <- p4v <- pmv <- numeric(M)
for (m in 1:M) {
  d <- gen(seed = 1000 + m, gamma = 0, n = n, S = S)
  pv <- fourth_test(d$E, d$T, d$L, B = B, seed = m)
  p2v[m] <- pv["p2"]; p4v[m] <- pv["p4"]; pmv[m] <- pv["pmax"]
}
rate2 <- mean(p2v < 0.05); rate4 <- mean(p4v < 0.05); ratem <- mean(pmv < 0.05)
c(sites_only = round(rate2, 3), species_only = round(rate4, 3), max_of_p = round(ratem, 3))

## ---- fig-rates ----
rd <- data.frame(test = factor(c("permute sites","permute species","max-of-p"),
                               levels = c("permute sites","permute species","max-of-p")),
                 rate = c(rate2, rate4, ratem))
ggplot(rd, aes(test, rate, fill = test)) +
  geom_col(width = 0.6) + geom_hline(yintercept = 0.05, colour = te_ink, linetype = "dashed") +
  geom_text(aes(label = sprintf("%.2f", rate)), vjust = -0.4, colour = te_ink, size = 4) +
  annotate("text", x = 3, y = 0.10, label = "nominal 0.05", colour = te_ink, size = 3.4, hjust = 1) +
  scale_fill_manual(values = c(te_warm, te_sage, te_green)) +
  labs(title = "False-positive rate of the fourth-corner test",
       x = NULL, y = "rejection rate at 0.05") + theme_te() + theme(legend.position = "none")

## ---- fig-pdist ----
pd <- rbind(data.frame(p = p2v, which = "permute sites only"),
            data.frame(p = pmv, which = "max-of-p (ter Braak)"))
ggplot(pd, aes(p, fill = which)) +
  geom_histogram(breaks = seq(0, 1, 0.05), colour = "white", linewidth = 0.2) +
  facet_wrap(~which) + geom_vline(xintercept = 0.05, colour = te_ink, linetype = "dashed") +
  scale_fill_manual(values = c(te_green, te_warm)) +
  labs(title = "Where the p-values fall under the null",
       x = "p-value", y = "count") + theme_te() + theme(legend.position = "none")
