# Checking a trait environment analysis
# https://tidyecology.com/posts/checking-a-trait-environment-analysis/
#
# 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

## ---- stat ----
fc <- function(L, e, t) {
  P <- L / sum(L); wi <- rowSums(P); wj <- colSums(P)
  es <- e - sum(wi * e); es <- es / sqrt(sum(wi * es^2))     # weighted standardisation
  ts <- t - sum(wj * t); ts <- ts / sqrt(sum(wj * ts^2))
  sum(P * outer(es, ts))
}

## ---- design ----
sim <- function(seed, env_drives, trait_drives, n_site = 30, n_sp = 25, tol = 0.25) {
  set.seed(seed)
  e <- runif(n_site)                                  # the environment you measured
  g <- if (env_drives) e else runif(n_site)           # the gradient the species actually track
  o <- runif(n_sp, -0.1, 1.1)                         # species optima on that gradient
  t <- if (trait_drives) 12 * o + rnorm(n_sp, 0, 1.5) else rnorm(n_sp, 6, 4)
  mu <- outer(g, o, function(x, y) exp(-(x - y)^2 / (2 * tol^2)))
  L  <- matrix(rpois(n_site * n_sp, sweep(mu, 2, rlnorm(n_sp, log(20), 0.4), "*")), n_site, n_sp)
  ok_i <- rowSums(L) > 0; ok_j <- colSums(L) > 0
  list(L = L[ok_i, ok_j, drop = FALSE], e = e[ok_i], t = t[ok_j])
}
pv <- function(s, nperm = 199) {
  r0 <- fc(s$L, s$e, s$t)
  d2 <- replicate(nperm, fc(s$L[sample(nrow(s$L)), , drop = FALSE], s$e, s$t))   # shuffle sites
  d4 <- replicate(nperm, fc(s$L[, sample(ncol(s$L)), drop = FALSE], s$e, s$t))   # shuffle species
  c(r = r0, p_sites = (1 + sum(abs(d2) >= abs(r0))) / (nperm + 1),
    p_species = (1 + sum(abs(d4) >= abs(r0))) / (nperm + 1))
}

## ---- rates ----
rate <- function(env_drives, trait_drives, nrep = 400, base = 0) {
  m <- t(vapply(seq_len(nrep), function(k)
    pv(sim(base + k, env_drives, trait_drives)), numeric(3)))
  c(mean_abs_r = mean(abs(m[, 1])), by_sites = mean(m[, 2] <= 0.05),
    by_species = mean(m[, 3] <= 0.05), max_test = mean(pmax(m[, 2], m[, 3]) <= 0.05))
}
tab <- rbind(
  "environment drives, trait random" = rate(TRUE,  FALSE, base = 3110000),
  "trait drives, environment random" = rate(FALSE, TRUE,  base = 3120000),
  "both (a real link)"               = rate(TRUE,  TRUE,  base = 3130000),
  "neither"                          = rate(FALSE, FALSE, base = 3140000))
print(round(tab, 3))

## ---- nulls ----
s  <- sim(3110001, env_drives = TRUE, trait_drives = FALSE)
r0 <- fc(s$L, s$e, s$t)
n_sites   <- replicate(1999, fc(s$L[sample(nrow(s$L)), , drop = FALSE], s$e, s$t))
n_species <- replicate(1999, fc(s$L[, sample(ncol(s$L)), drop = FALSE], s$e, s$t))
two <- c(observed = r0, sd_sites = sd(n_sites), sd_species = sd(n_species),
         width_ratio = sd(n_species) / sd(n_sites),
         p_sites = (1 + sum(abs(n_sites) >= abs(r0))) / 2000,
         p_species = (1 + sum(abs(n_species) >= abs(r0))) / 2000)
print(round(two, 4))

## ---- fig-nulls ----
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),
        plot.title = element_text(face = "bold", colour = "#16241d"),
        plot.subtitle = element_text(colour = "#5d6b61"),
        legend.position = "top", legend.title = element_blank())
nd <- data.frame(r = c(n_sites, n_species),
                 null = rep(c("shuffle the sites", "shuffle the species"), each = 1999))
ggplot(nd, aes(r, colour = null, fill = null)) +
  geom_density(alpha = 0.18, linewidth = 0.9) +
  geom_vline(xintercept = r0, colour = "#16241d", linewidth = 0.8, linetype = "22") +
  annotate("text", x = r0 + 0.012, y = 15, hjust = 0, size = 3.4, colour = "#16241d",
           label = sprintf("observed  %.3f", r0)) +
  scale_colour_manual(values = c("shuffle the sites" = "#b5534e", "shuffle the species" = "#275139")) +
  scale_fill_manual(values = c("shuffle the sites" = "#b5534e", "shuffle the species" = "#275139")) +
  labs(x = "fourth corner correlation", y = "density",
       title = "Same number, two verdicts",
       subtitle = "the true trait to environment link in this data set is zero") +
  theme_te

## ---- nsite ----
grow <- t(vapply(c(20, 40, 80, 160), function(n) {
  m <- t(vapply(1:250, function(k) pv(sim(3170000 + k, TRUE, FALSE, n_site = n)), numeric(3)))
  c(n_site = n, mean_abs_r = mean(abs(m[, 1])), by_sites = mean(m[, 2] <= 0.05),
    max_test = mean(pmax(m[, 2], m[, 3]) <= 0.05))
}, numeric(4)))
print(round(grow, 3))

## ---- fig-n ----
gd <- data.frame(n = rep(grow[, "n_site"], 2),
                 y = 100 * c(grow[, "by_sites"], grow[, "max_test"]),
                 which = rep(c("shuffle the sites", "max of the two"), each = nrow(grow)))
ggplot(gd, aes(n, y, colour = which)) +
  geom_hline(yintercept = 5, colour = "#93a87f", linewidth = 0.4, linetype = "22") +
  geom_line(linewidth = 1.05) + geom_point(size = 2) +
  scale_x_log10(breaks = grow[, "n_site"], labels = grow[, "n_site"]) +
  scale_y_continuous(limits = c(0, 100)) +
  scale_colour_manual(values = c("shuffle the sites" = "#b5534e", "max of the two" = "#275139")) +
  labs(x = "number of sites", y = "% of runs rejecting at 0.05, true link zero",
       title = "The reflex that does not work",
       subtitle = "the dashed line is the rate the test claims to have") +
  theme_te

## ---- breadth ----
bray <- function(L) {
  R <- L / rowSums(L); n <- nrow(R); s <- 0; k <- 0
  for (i in 1:(n - 1)) for (j in (i + 1):n) { s <- s + sum(abs(R[i, ] - R[j, ])) / 2; k <- k + 1 }
  s / k
}
grid <- c(0.05, 0.10, 0.18, 0.30, 0.50, 0.90, 2.00)
br <- t(vapply(grid, function(tl) {
  m <- t(vapply(1:250, function(k) pv(sim(3150000 + k, TRUE, FALSE, tol = tl)), numeric(3)))
  c(niche_width = tl,
    turnover = mean(vapply(1:20, function(k) bray(sim(3160000 + k, TRUE, FALSE, tol = tl)$L), 0)),
    by_sites = mean(m[, 2] <= 0.05), max_test = mean(pmax(m[, 2], m[, 3]) <= 0.05))
}, numeric(4)))
print(round(br, 3))

## ---- fig-breadth ----
bd <- data.frame(x = rep(br[, "niche_width"], 2),
                 y = 100 * c(br[, "by_sites"], br[, "max_test"]),
                 which = rep(c("shuffle the sites", "max of the two"), each = nrow(br)))
ggplot(bd, aes(x, y, colour = which)) +
  geom_hline(yintercept = 5, colour = "#93a87f", linewidth = 0.4, linetype = "22") +
  geom_line(linewidth = 1.05) + geom_point(size = 2) +
  scale_x_log10(breaks = br[, "niche_width"], labels = br[, "niche_width"]) +
  scale_y_continuous(limits = c(0, 100)) +
  scale_colour_manual(values = c("shuffle the sites" = "#b5534e", "max of the two" = "#275139")) +
  labs(x = "niche width: sd of the species response curve (the gradient is one unit long)",
       y = "% of runs rejecting at 0.05, true link zero",
       title = "Worst in the middle",
       subtitle = "the rate is a property of the turnover in your table, not of your hypothesis") +
  theme_te
