# Wide and long: reshaping species data
# https://tidyecology.com/posts/wide-and-long-species-data/
#
# 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

## ---- shapes ----
wide <- data.frame(
  plot      = paste0("P", 1:6),
  Festuca   = c(42, 38, 51, 63, 29, 44),
  Trifolium = c(7, 0, 2, 5, 9, 4),
  Plantago  = c(3, 4, 1, 6, 7, 2),
  Achillea  = c(5, 6, 0, 4, 3, 8),
  Bromus    = c(11, 9, 14, 12, 0, 10)
)
wide

## ---- long ----
library(tidyr)

long <- pivot_longer(wide, cols = -plot, names_to = "species", values_to = "count")
head(long, 4)
dim(long)

## ---- fig-shapes ----
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))

cell <- function(x, y, lab, kind) data.frame(x = x, y = y, lab = lab, kind = kind)
w_tab <- rbind(
  cell(c(1, 2.2, 3.4), 7, c("plot", "Festuca", "Trifolium"), "head"),
  cell(rep(1, 3), 6:4, c("P1", "P2", "P3"), "key"),
  cell(rep(2.2, 3), 6:4, c("42", "38", "51"), "value"),
  cell(rep(3.4, 3), 6:4, c("7", "0", "2"), "value")
)
l_tab <- rbind(
  cell(c(5.6, 6.8, 8), 7, c("plot", "species", "count"), "head"),
  cell(rep(5.6, 6), 6:1, rep(c("P1", "P2", "P3"), 2), "key"),
  cell(rep(6.8, 6), 6:1, rep(c("Festuca", "Trifolium"), each = 3), "key"),
  cell(rep(8, 6), 6:1, c("42", "38", "51", "7", "0", "2"), "value")
)
tabs <- rbind(w_tab, l_tab)

ggplot(tabs, aes(x, y, fill = kind)) +
  geom_tile(width = 1.15, height = 0.85, colour = "white", linewidth = 1) +
  geom_text(aes(label = lab, colour = kind), size = 3.1) +
  annotate("text", x = 2.2, y = 8, label = "wide", fontface = "bold",
           colour = "#16241d", size = 4.6) +
  annotate("text", x = 6.8, y = 8, label = "long", fontface = "bold",
           colour = "#16241d", size = 4.6) +
  scale_fill_manual(values = c(head = "#16241d", key = "#93a87f", value = "#275139")) +
  scale_colour_manual(values = c(head = "white", key = "#16241d", value = "white")) +
  scale_y_continuous(limits = c(0.3, 8.5)) +
  guides(fill = "none", colour = "none") +
  theme_void() + te_canvas

## ---- roundtrip ----
back <- pivot_wider(long, names_from = species, values_from = count)
identical(as.data.frame(back), wide)

## ---- vegan-way ----
suppressPackageStartupMessages(library(vegan))

m <- as.matrix(wide[, -1])
rownames(m) <- wide$plot
round(diversity(m), 3)

## ---- vegan-trap ----
try(diversity(wide))

## ---- fig-long-plot ----
ggplot(long, aes(x = count, y = species)) +
  geom_col(fill = "#275139") +
  facet_wrap(~plot) +
  labs(x = "individuals counted", y = NULL) +
  theme_minimal(base_size = 11) + te_canvas +
  theme(panel.grid.minor = element_blank())

## ---- notebook ----
notebook <- subset(long, count > 0)
c(notebook_rows = nrow(notebook), full_grid = nrow(long))

## ---- notebook-wide ----
nb <- pivot_wider(notebook, names_from = species, values_from = count)
m_nb <- as.matrix(nb[, -1])
rownames(m_nb) <- nb$plot
m_nb

## ---- notebook-diversity ----
round(diversity(m_nb), 3)

## ---- notebook-fill ----
nb0 <- pivot_wider(notebook, names_from = species, values_from = count, values_fill = 0)
m_fill <- as.matrix(nb0[, -1])
rownames(m_fill) <- nb0$plot
m_fill <- m_fill[rownames(m), colnames(m)]
max(abs(m_fill - m))

## ---- xtabs ----
xt <- xtabs(count ~ plot + species, data = notebook)
identical(as.numeric(xt[rownames(m), colnames(m)]), as.numeric(m))

## ---- dup ----
dup <- rbind(as.data.frame(notebook),
             data.frame(plot = "P1", species = "Festuca", count = 8))
subset(dup, plot == "P1" & species == "Festuca")

## ---- dup-pivot ----
res <- pivot_wider(dup, names_from = species, values_from = count)
class(res$Festuca)
res$Festuca[[1]]

## ---- dup-error ----
try(pivot_wider(dup, names_from = species, values_from = count, values_fill = 0))

## ---- dup-xtabs ----
xd <- xtabs(count ~ plot + species, data = dup)
xd["P1", "Festuca"]

## ---- dup-rules ----
rules <- list(sum = sum, mean = mean, max = max)
out <- sapply(rules, function(f) {
  w <- suppressWarnings(pivot_wider(dup, names_from = species,
                                    values_from = count, values_fn = f))
  mm <- as.matrix(w[, -1])
  rownames(mm) <- w$plot
  mm <- mm[rownames(m), colnames(m)]
  c(P1_Festuca = unname(mm["P1", "Festuca"]), P1_Shannon = diversity(mm["P1", ]))
})
round(out, 4)

## ---- dup-scale ----
delta <- unname(out["P1_Shannon", "sum"] - out["P1_Shannon", "mean"])
pairs <- as.numeric(dist(diversity(m)))
c(rule_effect = round(abs(delta), 4),
  smaller_pairs = sum(pairs < abs(delta)),
  total_pairs = length(pairs),
  study_range = round(diff(range(diversity(m))), 4))
