# Community weighted means in R
# https://tidyecology.com/posts/community-weighted-means/
#
# 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

## ---- data ----
set.seed(308)
n_site <- 40; n_sp <- 36
moist <- seq(0, 1, length.out = n_site)
opt   <- runif(n_sp, -0.10, 1.10)              # species optima on the gradient
sla   <- 10 + 18 * opt + rnorm(n_sp, 0, 2.2)   # the trait: tied to the optimum
amax  <- rlnorm(n_sp, log(28), 0.40)           # how common each species is
mu <- outer(moist, opt, function(e, o) exp(-(e - o)^2 / (2 * 0.18^2)))
L  <- matrix(rpois(n_site * n_sp, sweep(mu, 2, amax, "*")), n_site, n_sp)
dim(L); sum(L); range(rowSums(L > 0))

## ---- cwm ----
cwm <- function(A, t) as.vector(A %*% t / rowSums(A))
cwm_ab <- cwm(L, sla)
cwm_pa <- cwm((L > 0) * 1, sla)
fit <- lm(cwm_ab ~ moist)
round(coef(summary(fit)), 3)

## ---- fig-gradient ----
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),
        legend.position = "top", legend.title = element_blank(),
        legend.text = element_text(colour = "#2c3a31"))
gd <- data.frame(moist = rep(moist, 2), cwm = c(cwm_ab, cwm_pa),
                 w = rep(c("weighted by abundance", "weighted by presence"), each = n_site))
ggplot(gd, aes(moist, cwm, colour = w)) +
  geom_point(size = 1.9, alpha = 0.85) +
  geom_smooth(method = "lm", formula = y ~ x, se = FALSE, linewidth = 0.9) +
  scale_colour_manual(values = c("weighted by abundance" = "#275139",
                                 "weighted by presence"  = "#cda23f")) +
  labs(x = "soil moisture (gradient position)", y = "community weighted mean SLA",
       title = "The regression everyone runs",
       subtitle = "the weighting is a decision, and it moves the slope") +
  theme_te

## ---- hidden ----
comm <- rbind(A = c(25, 25, 25, 25), B = c(25, 25, 25, 25))
tr_A <- c(18, 19, 21, 22)          # four species with similar leaves
tr_B <- c(8, 9, 31, 32)            # two tough species and two soft ones
cwv  <- function(a, t) sum(a * (t - sum(a * t) / sum(a))^2) / sum(a)
c(CWM_A = sum(comm["A", ] * tr_A) / 100, CWM_B = sum(comm["B", ] * tr_B) / 100,
  sd_A  = sqrt(cwv(comm["A", ], tr_A)),  sd_B = sqrt(cwv(comm["B", ], tr_B)))

## ---- cwvsim ----
cwv_site <- vapply(seq_len(n_site), function(i) cwv(L[i, ], sla), 0)
round(c(mean_within_sd = mean(sqrt(cwv_site)),
        sd_of_cwm = sd(cwm_ab), total_sd = sd(rep(sla, colSums(L)))), 2)

## ---- inflated ----
ii <- rep(seq_len(n_site), times = rowSums(L))
jj <- unlist(lapply(seq_len(n_site), function(i) rep(seq_len(n_sp), times = L[i, ])))
length(ii)                                   # one row per individual
r_inf <- cor(moist[ii], sla[jj])
r_inf

## ---- cwmcor ----
c(cwm_correlation = cor(cwm_ab, moist), fourth_corner = r_inf)

## ---- identity ----
P  <- L / sum(L); w <- rowSums(P); cj <- colSums(P)
eb <- sum(w * moist);  Ve <- sum(w * (moist - eb)^2)      # weighted by site total
tb <- sum(cj * sla);   Vt <- sum(cj * (sla - tb)^2)       # weighted by species total
Vc <- sum(w * (cwm_ab - tb)^2)                            # variance of the CWM values
Vwithin <- sum(vapply(seq_len(n_site), function(i) sum(P[i, ] * (sla - cwm_ab[i])^2), 0))
cov_w <- sum(w * (moist - eb) * (cwm_ab - tb))
r_fc  <- cov_w / sqrt(Ve * Vt)
r_cwm <- cov_w / sqrt(Ve * Vc)
shrink <- sqrt(Vc / Vt)
c(inflated = r_inf, weighted_formula = r_fc, gap = abs(r_inf - r_fc))

## ---- split ----
c(Vt = Vt, Vc = Vc, Vwithin = Vwithin, gap = abs(Vt - Vc - Vwithin))
c(r_cwm = r_cwm, times_shrink = shrink, product = r_cwm * shrink,
  r_fc = r_fc, gap = abs(r_fc - r_cwm * shrink))

## ---- sweep ----
wcor_parts <- function(A, e, t) {
  P <- A / sum(A); w <- rowSums(P); cj <- colSums(P)
  eb <- sum(w * e); Ve <- sum(w * (e - eb)^2)
  tb <- sum(cj * t); Vt <- sum(cj * (t - tb)^2)
  m  <- as.vector(A %*% t / rowSums(A)); Vc <- sum(w * (m - tb)^2)
  cw <- sum(w * (e - eb) * (m - tb))
  c(r_fc = cw / sqrt(Ve * Vt), r_cwm = cw / sqrt(Ve * Vc), shrink = sqrt(Vc / Vt))
}
set.seed(3082)
sw <- as.data.frame(t(replicate(80, {
  ns <- sample(20:45, 1); nsp <- sample(15:40, 1)
  e2 <- runif(ns); op2 <- runif(nsp, -0.2, 1.2); tl <- runif(1, 0.10, 0.60)
  t2 <- rnorm(nsp, 20, 6) + runif(1, -20, 20) * op2
  m2 <- outer(e2, op2, function(a, b) exp(-(a - b)^2 / (2 * tl^2)))
  A  <- matrix(rpois(ns * nsp, sweep(m2, 2, rlnorm(nsp, log(20), 0.6), "*")), ns, nsp)
  ok <- rowSums(A) > 0; A <- A[ok, , drop = FALSE]; e2 <- e2[ok]
  kp <- colSums(A) > 0
  wcor_parts(A[, kp, drop = FALSE], e2, t2[kp])
})))
sw$gap <- abs(sw$r_fc - sw$r_cwm * sw$shrink)
c(max_gap = max(sw$gap), fc_never_larger = mean(abs(sw$r_fc) <= abs(sw$r_cwm) + 1e-12),
  shrink_min = min(sw$shrink), shrink_max = max(sw$shrink))

## ---- fig-identity ----
ggplot(sw, aes(abs(r_cwm), abs(r_fc), colour = shrink)) +
  geom_abline(slope = 1, intercept = 0, linetype = 2, colour = "#93a87f") +
  geom_point(size = 2.6, alpha = 0.9) +
  scale_colour_gradient(low = "#c9b458", high = "#1d5b4e",
                        name = "between-plot share\nof trait variance (sqrt)") +
  coord_cartesian(xlim = c(0, 1), ylim = c(0, 1)) +
  labs(x = "|CWM correlation|", y = "|fourth corner correlation|",
       title = "One covariance, two denominators",
       subtitle = "the fourth corner is the weighted CWM correlation times the square root of the between-plot share") +
  theme_te + theme(legend.position = "right",
                   legend.title = element_text(colour = "#46604a", size = 8.5))

## ---- noturnover ----
set.seed(3083)
nt <- t(replicate(400, {
  A <- matrix(rpois(30 * 25, 6), 30, 25)     # every plot from the same pool
  wcor_parts(A, runif(30), rnorm(25, 20, 5))
}))
c(mean_abs_r_cwm = mean(abs(nt[, "r_cwm"])), mean_abs_r_fc = mean(abs(nt[, "r_fc"])),
  cwm_above_0.3 = mean(abs(nt[, "r_cwm"]) > 0.30), fc_above_0.3 = mean(abs(nt[, "r_fc"]) > 0.30))

## ---- coversim ----
sim <- function(seed, rare_wet) {
  set.seed(seed)
  o <- runif(36, -0.10, 1.10)
  t <- 10 + 18 * o + rnorm(36, 0, 2.2)
  a <- rlnorm(36, log(28) - rare_wet * o, 0.40)        # rare_wet tilts abundance
  m <- outer(seq(0, 1, length.out = 40), o, function(e, x) exp(-(e - x)^2 / (2 * 0.18^2)))
  list(A = matrix(rpois(40 * 36, sweep(m, 2, a, "*")), 40, 36),
       e = seq(0, 1, length.out = 40), t = t, opt = o)
}
cover_curve <- function(s) {
  ord  <- order(colSums(s$A), decreasing = TRUE)       # measure the common ones first
  b0   <- unname(coef(lm(cwm(s$A, s$t) ~ s$e))[2])   # named coefs poison c()
  out <- t(vapply(seq_along(ord), function(k) {
    keep <- ord[seq_len(k)]; sub <- s$A[, keep, drop = FALSE]
    ok <- rowSums(sub) > 0
    b  <- unname(coef(lm(cwm(sub[ok, , drop = FALSE], s$t[keep]) ~ s$e[ok]))[2])
    c(k = k, cover = sum(colSums(s$A)[keep]) / sum(s$A), slope = b,
      worst_local = min(rowSums(sub) / rowSums(s$A)))
  }, numeric(4)))
  data.frame(out, rel = out[, "slope"] / b0, b0 = b0)
}
cc_flat <- cover_curve(sim(308, 0));  cc_tilt <- cover_curve(sim(308, 2.2))
k1 <- which(cc_flat$cover >= 0.80)[1]; k2 <- which(cc_tilt$cover >= 0.80)[1]
rbind(unrelated = c(species = k1, coverage = cc_flat$cover[k1], slope = cc_flat$slope[k1],
                    percent_of_true = 100 * cc_flat$rel[k1], worst_local = cc_flat$worst_local[k1]),
      rare_wet  = c(species = k2, coverage = cc_tilt$cover[k2], slope = cc_tilt$slope[k2],
                    percent_of_true = 100 * cc_tilt$rel[k2], worst_local = cc_tilt$worst_local[k2]))

## ---- fig-coverage ----
cd <- rbind(data.frame(cc_flat, case = "rarity unrelated to habitat"),
            data.frame(cc_tilt, case = "wet end specialists are rare"))
cd <- subset(cd, cover >= 0.20)   # below three species the slope is not defined
ggplot(cd, aes(100 * cover, 100 * rel, colour = case)) +
  geom_hline(yintercept = 100, linetype = 3, colour = "#93a87f") +
  geom_vline(xintercept = 80, linetype = 2, colour = "#b5534e") +
  geom_line(linewidth = 1.1) + geom_point(size = 1.4) +
  annotate("text", x = 79, y = 20, hjust = 1, size = 3.1, colour = "#b5534e",
           label = "the 80% rule") +
  scale_colour_manual(values = c("rarity unrelated to habitat" = "#2f8f63",
                                 "wet end specialists are rare" = "#b5534e")) +
  coord_cartesian(xlim = c(20, 100), ylim = c(0, 115)) +
  labs(x = "% of individuals whose species has a trait value",
       y = "recovered slope (% of the full data slope)",
       title = "Coverage against recovered slope, two surveys",
       subtitle = "coverage is one factor; the trait contrast with the missing species is the other") +
  theme_te
