Community-weighted mean (CWM) traits for each community. Abundance-weighted average of trait values across species present.
compute_CWM <- function(comm, traits) {
sp <- intersect(colnames(comm), rownames(traits))
comm <- comm[, sp, drop = FALSE]
traits <- traits[sp, , drop = FALSE]
# Row-normalise community (relative abundances)
comm_rel <- comm / rowSums(comm)
# CWM = comm_rel %*% traits
cwm <- as.matrix(comm_rel) %*% as.matrix(traits)
as.data.frame(cwm)
}
# Example
comm <- matrix(c(1,2,0,1,3,0,1,1), nrow=2, dimnames=list(c("A","B"), c("sp1","sp2","sp3","sp4")))
traits <- matrix(rnorm(12), nrow=4, dimnames=list(c("sp1","sp2","sp3","sp4"), c("t1","t2","t3")))
compute_CWM(comm, traits)
# ── Example ──────────────────────────────────────────────────────
# Build a toy community matrix from iris
set.seed(1)
comm <- matrix(rbinom(30, 1, 0.6), nrow = 3, ncol = 10,
dimnames = list(c("site1","site2","site3"),
paste0("sp", 1:10)))
traits <- as.data.frame(matrix(rnorm(40), 10, 4,
dimnames = list(paste0("sp", 1:10),
c("t1","t2","t3","t4"))))
compute_CWM(comm, traits)