# Indicator species analysis with IndVal in R
# https://tidyecology.com/posts/indicator-species-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-11-04

## ---- data ----
library(indicspecies)
library(dplyr)
library(tidyr)
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))

set.seed(7)
habitats <- rep(c("Forest", "Grassland", "Wetland"), each = 8)   # 24 sites

make_sp <- function(means_by_hab) {
  sapply(habitats, function(h) rpois(1, means_by_hab[[h]]))
}
sp_list <- list(
  For1 = c(Forest=10,Grassland=0, Wetland=0), For2 = c(Forest=9, Grassland=0, Wetland=0),
  For3 = c(Forest=11,Grassland=0, Wetland=0), For4 = c(Forest=8, Grassland=0, Wetland=1),
  Gra1 = c(Forest=0, Grassland=10,Wetland=0), Gra2 = c(Forest=0, Grassland=9, Wetland=0),
  Gra3 = c(Forest=1, Grassland=11,Wetland=0), Gra4 = c(Forest=0, Grassland=8, Wetland=0),
  Wet1 = c(Forest=0, Grassland=0, Wetland=10),Wet2 = c(Forest=0, Grassland=0, Wetland=9),
  Wet3 = c(Forest=0, Grassland=1, Wetland=11),Wet4 = c(Forest=0, Grassland=0, Wetland=8),
  FoGr1= c(Forest=7, Grassland=7, Wetland=0), FoGr2= c(Forest=8, Grassland=6, Wetland=0),
  Gen1 = c(Forest=5, Grassland=5, Wetland=5), Gen2 = c(Forest=6, Grassland=4, Wetland=5),
  Gen3 = c(Forest=4, Grassland=5, Wetland=6),
  Rar1 = c(Forest=0.4,Grassland=0.4,Wetland=0.4), Rar2 = c(Forest=0.3,Grassland=0.5,Wetland=0.3),
  Rar3 = c(Forest=0.5,Grassland=0.3,Wetland=0.4)
)
comm <- as.data.frame(lapply(sp_list, make_sp))
rownames(comm) <- paste0(substr(habitats, 1, 1),
                         ave(seq_along(habitats), habitats, FUN = seq_along))

## ---- fig-heatmap ----
hm <- comm %>% mutate(site = rownames(comm), habitat = habitats) %>%
  pivot_longer(-c(site, habitat), names_to = "species", values_to = "abund")
hm$site    <- factor(hm$site, levels = rev(rownames(comm)))
hm$species <- factor(hm$species, levels = colnames(comm))
hm$habitat <- factor(hm$habitat, levels = c("Forest","Grassland","Wetland"))

ggplot(hm, aes(species, site, fill = abund)) +
  geom_tile(color = "white", linewidth = 0.3) +
  facet_grid(habitat ~ ., scales = "free_y", space = "free_y", switch = "y") +
  scale_fill_gradient(low = "#f5f4ee", high = "#275139", name = "abundance") +
  labs(x = NULL, y = NULL) +
  theme_minimal(base_size = 12) + te_canvas +
  theme(panel.grid = element_blank(),
        axis.text.x = element_text(angle = 45, hjust = 1, size = 9),
        strip.placement = "outside", legend.position = "top")

## ---- multipatt ----
set.seed(42)   # fixes the permutation p-values
res <- multipatt(comm, habitats, func = "IndVal.g", control = how(nperm = 999))
summary(res)

## ---- fig-indicators ----
idx <- res$sign$index
lab <- colnames(res$comb)[idx]
A_best <- sapply(seq_along(idx), function(i) res$A[i, idx[i]])
B_best <- sapply(seq_along(idx), function(i) res$B[i, idx[i]])
ind <- data.frame(species = rownames(res$sign), cluster = lab,
                  A = A_best, B = B_best, stat = res$sign$stat, p = res$sign$p.value)
ind <- ind[!is.na(ind$p) & ind$p <= 0.05, ]

clust_cols <- c("Forest"="#275139","Grassland"="#7d8a3c",
                "Wetland"="#3a7ca5","Forest+Grassland"="#c98a2e")
ind$cluster <- factor(ind$cluster, levels = names(clust_cols))
ind <- ind[order(ind$cluster, ind$stat), ]
ind$species <- factor(ind$species, levels = ind$species)

ggplot(ind, aes(stat, species, color = cluster)) +
  geom_segment(aes(x = 0, xend = stat, yend = species), linewidth = 0.6) +
  geom_point(size = 3) +
  scale_color_manual(values = clust_cols, name = "indicates") +
  scale_x_continuous(limits = c(0, 1.05), breaks = seq(0, 1, 0.25)) +
  labs(x = "IndVal stat", y = NULL) +
  theme_minimal(base_size = 12) + te_canvas + theme(legend.position = "right")

## ---- nonindicators ----
res$sign[c("Gen1","Gen3","Rar1","Rar2"), ]
