# From a field sheet to your first analysis
# https://tidyecology.com/posts/from-field-sheet-to-first-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-10-07

## ---- read-raw ----
library(dplyr)
library(tidyr)
raw_csv <- "site,species,count
S1,Carex flava,20
S1,Carex flacca,8
S1,Juncus effusus,5
S1,Poa pratensis,3
S2,Carex flava,15
S2,Juncus effusus,20
S2,Festuca rubra,10
S3,Carex flava,10
S3,carex flava,10
S3,Carex  flava,10
S3,Poa pratensis,10"
raw <- read.csv(text = raw_csv, stringsAsFactors = FALSE)
raw

## ---- survey-frame ----
sites <- data.frame(
  site    = paste0("S", 1:4),
  habitat = c("fen", "fen", "meadow", "meadow"),
  stringsAsFactors = FALSE
)
sites

## ---- shannon-fn ----
shannon <- function(x) {
  p <- x[x > 0]
  p <- p / sum(p)
  -sum(p * log(p))
}

## ---- naive-pipeline ----
naive_wide <- raw |>
  group_by(site, species) |>
  summarise(count = sum(count), .groups = "drop") |>
  pivot_wider(names_from = species, values_from = count, values_fill = 0)

naive <- naive_wide |>
  rowwise() |>
  mutate(richness = sum(c_across(-site) > 0),
         shannon  = shannon(c_across(-c(site, richness)))) |>
  ungroup() |>
  select(site, richness, shannon)

# inner join with the survey frame: S4 has no observations, so it is dropped
naive_out <- inner_join(sites, naive, by = "site")
naive_out |> mutate(shannon = round(shannon, 3))

## ---- naive-numbers ----
naive_top   <- naive_out$site[which.max(naive_out$shannon)]
naive_meanR <- mean(naive_out$richness)
naive_nsite <- nrow(naive_out)
naive_s3    <- naive_out$shannon[naive_out$site == "S3"]
naive_s3R   <- naive_out$richness[naive_out$site == "S3"]

## ---- clean-pipeline ----
normalise <- function(x) tolower(gsub("\\s+", " ", trimws(x)))
lookup <- c("carex flava"    = "Carex flava",
            "carex flacca"   = "Carex flacca",
            "juncus effusus" = "Juncus effusus",
            "poa pratensis"  = "Poa pratensis",
            "festuca rubra"  = "Festuca rubra")

raw_clean <- raw |> mutate(species = lookup[normalise(species)])
stopifnot(!anyNA(raw_clean$species))   # every raw string matched the lookup

clean_wide <- raw_clean |>
  group_by(site, species) |>
  summarise(count = sum(count), .groups = "drop") |>
  pivot_wider(names_from = species, values_from = count, values_fill = 0)

clean <- clean_wide |>
  rowwise() |>
  mutate(richness = sum(c_across(-site) > 0),
         shannon  = shannon(c_across(-c(site, richness)))) |>
  ungroup() |>
  select(site, richness, shannon)

# left join keeps S4 (surveyed, nothing found): richness 0, Shannon 0
clean_out <- left_join(sites, clean, by = "site") |>
  mutate(richness = replace_na(richness, 0L),
         shannon  = replace_na(shannon, 0))
clean_out |> mutate(shannon = round(shannon, 3))

## ---- clean-numbers ----
clean_top   <- clean_out$site[which.max(clean_out$shannon)]
clean_meanR <- mean(clean_out$richness)
clean_nsite <- nrow(clean_out)
clean_s3    <- clean_out$shannon[clean_out$site == "S3"]
clean_s3R   <- clean_out$richness[clean_out$site == "S3"]

## ---- fig-compare ----
library(ggplot2)
te_green <- "#275139"
te_grey  <- "#9aa79a"
cmp <- bind_rows(
  naive_out |> select(site, shannon) |> mutate(pipeline = "naive"),
  clean_out |> select(site, shannon) |> mutate(pipeline = "clean")
)
cmp$pipeline <- factor(cmp$pipeline, levels = c("naive", "clean"),
                       labels = c("naive (no name clean, inner join)", "clean (names + left join)"))
cmp <- tidyr::complete(cmp, site, pipeline)   # give the dropped naive S4 a slot to label
ggplot(cmp, aes(x = site, y = shannon, fill = pipeline)) +
  geom_col(position = position_dodge2(preserve = "single"), width = 0.7, na.rm = TRUE) +
  geom_text(aes(y = ifelse(is.na(shannon), 0, shannon),
                label = ifelse(is.na(shannon), "dropped by\nthe inner join",
                               sprintf("%.2f", shannon))),
            position = position_dodge2(width = 0.7, preserve = "single"),
            vjust = -0.3, size = 2.8, colour = "grey25", lineheight = 0.9) +
  scale_fill_manual(values = c(te_grey, te_green)) +
  scale_y_continuous(expand = expansion(mult = c(0, 0.12))) +
  labs(x = NULL, y = "Shannon diversity", fill = NULL) +
  theme_minimal(base_size = 13) +
  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.x = element_blank(),
        legend.position = "top",
        axis.title = element_text(colour = "grey25"))
