# Functional diversity in R with the FD package
# https://tidyecology.com/posts/functional-diversity-fd/
#
# 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(FD)
library(ggplot2)
library(dplyr)
library(tidyr)

## ---- traits ----
set.seed(77)
herbs <- data.frame(
  sla    = rnorm(10, 20, 3),
  height = rnorm(10, 0.30, 0.06),
  seed   = rnorm(10, 1.2, 0.4),
  form   = "herb", nfix = "no"
)
herbs$height <- pmax(herbs$height, 0.1); herbs$seed <- pmax(herbs$seed, 0.2)

extremes <- data.frame(
  sla    = c(16,   7,   7,  15,  30),
  height = c(0.6,  3,  22,   2, 0.15),
  seed   = c(0.3, 400, 250, 30, 0.1),
  form   = c("grass","shrub","tree","shrub","herb"),
  nfix   = c("no","no","no","yes","no")
)
traits <- rbind(herbs, extremes)
traits$form <- factor(traits$form); traits$nfix <- factor(traits$nfix)
rownames(traits) <- sprintf("sp%02d", 1:15)

c(species = nrow(traits), traits = ncol(traits),
  SLA_lo = round(min(traits$sla),0), SLA_hi = round(max(traits$sla),0))

## ---- communities ----
comm <- matrix(0, nrow = 3, ncol = 15,
               dimnames = list(c("Redundant","Diverse","Clumped"),
                               rownames(traits)))
comm["Redundant", 1:10] <- c(8,7,9,6,8,7,10,6,7,8)
ext <- sprintf("sp%02d", 11:15)
comm["Diverse", ext]    <- c(6,5,6,5,6)
comm["Clumped", ext]    <- c(40,3,3,3,3)

rowSums(comm > 0)   # species richness per community

## ---- gower ----
traits_an <- traits
traits_an$height <- log10(traits_an$height)
traits_an$seed   <- log10(traits_an$seed)

gd <- gowdis(traits_an)
c(min = round(min(gd),3), max = round(max(gd),3), mean = round(mean(gd),3))

## ---- dbfd ----
fd <- dbFD(traits_an, comm, corr = "cailliez", stand.FRic = TRUE,
           calc.FRic = TRUE, calc.FDiv = TRUE, calc.CWM = FALSE,
           messages = FALSE)
cwm <- functcomp(traits, comm)   # community-weighted means, raw scale

data.frame(
  community = rownames(comm), nbsp = fd$nbsp,
  FRic = round(fd$FRic, 3), FEve = round(fd$FEve, 3),
  FDiv = round(fd$FDiv, 3), FDis = round(fd$FDis, 3),
  RaoQ = round(fd$RaoQ, 3), row.names = NULL
)

## ---- fig-traitspace ----
te_paper <- "#f5f4ee"; te_ink <- "#16241d"; te_body <- "#2c3a31"; te_line <- "#dad9ca"
base_theme <- theme_minimal(base_size = 12) +
  theme(panel.grid.minor = element_blank(),
        panel.grid.major = element_line(color = te_line, linewidth = 0.3),
        plot.background  = element_rect(fill = te_paper, color = NA),
        panel.background = element_rect(fill = te_paper, color = NA),
        axis.text = element_text(color = te_body), axis.title = element_text(color = te_ink),
        plot.title = element_text(color = te_ink, face = "bold", size = 12),
        legend.title = element_text(color = te_ink, size = 9),
        legend.text = element_text(color = te_body, size = 8))

pco <- ade4::dudi.pco(ade4::cailliez(gd), scannf = FALSE, nf = 2)
ax  <- pco$li; colnames(ax) <- c("A1","A2"); ax$species <- rownames(traits)
sel <- c("Redundant","Diverse")
hull_df <- do.call(rbind, lapply(sel, function(cm){
  sp <- colnames(comm)[comm[cm,] > 0]; sub <- ax[ax$species %in% sp, c("A1","A2")]
  data.frame(sub[chull(sub$A1, sub$A2), ], community = cm)
}))
pt_df <- do.call(rbind, lapply(sel, function(cm){
  sp <- colnames(comm)[comm[cm,] > 0]
  data.frame(ax[ax$species %in% sp, c("A1","A2")], community = cm)
}))
cols3 <- c("Redundant"="#b5534e","Diverse"="#2f8f63","Clumped"="#c9a227")

ggplot() +
  geom_polygon(data = hull_df, aes(A1, A2, fill = community, color = community),
               alpha = 0.18, linewidth = 0.8) +
  geom_point(data = pt_df, aes(A1, A2, color = community), size = 2.6) +
  scale_fill_manual(values = cols3, name = NULL) +
  scale_color_manual(values = cols3, name = NULL) +
  labs(x = "PCoA axis 1", y = "PCoA axis 2",
       title = "Trait space: ten clustered species, five spread ones") +
  base_theme

## ---- fig-indices ----
res <- data.frame(
  community = rownames(comm),
  FRic = fd$FRic, FEve = fd$FEve, FDiv = fd$FDiv, FDis = fd$FDis, RaoQ = fd$RaoQ
)
ind_long <- res |>
  pivot_longer(-community, names_to = "index", values_to = "value") |>
  mutate(community = factor(community, levels = c("Redundant","Diverse","Clumped")),
         index = factor(index, levels = c("FRic","FEve","FDiv","FDis","RaoQ")))

ggplot(ind_long, aes(community, value, fill = community)) +
  geom_col(width = 0.7) +
  facet_wrap(~ index, scales = "free_y", nrow = 1) +
  scale_fill_manual(values = cols3, guide = "none") +
  labs(x = NULL, y = NULL,
       title = "Functional diversity indices across the three communities") +
  base_theme +
  theme(axis.text.x = element_text(angle = 35, hjust = 1, size = 8),
        strip.text = element_text(color = te_ink, face = "bold"))

## ---- cwm ----
cwm
