# Reading field data into R
# https://tidyecology.com/posts/reading-field-data-into-r/
#
# 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

## ---- sheet ----
sheet_lines <- c(
  "plot,Festuca,Trifolium,Plantago,Achillea,Bromus,notes",
  "P1,42,7,3,5,11,",
  "P2,38,,4,6,9,",
  "P3,51,2,1,,14,",
  "P4,n/a,5,6,4,12,no time for the grass",
  "P5,29,9,7,3,,",
  "P6,44,4,2,8,10,"
)
csv_path <- file.path(tempdir(), "quadrats.csv")
writeLines(sheet_lines, csv_path)

## ---- read-naive ----
naive <- read.csv(csv_path)
str(naive)

## ---- class-check ----
class(naive$Festuca)

## ---- sum-fails ----
try(sum(naive$Festuca))

## ---- text-loud ----
try(naive$Festuca * 2)
tryCatch(mean(naive$Festuca), warning = conditionMessage)
tryCatch(as.numeric(naive$Festuca), warning = conditionMessage)

## ---- text-compare ----
fest_num <- suppressWarnings(as.numeric(naive$Festuca))
data.frame(plot = naive$plot, as_read = naive$Festuca,
           text_over_5 = naive$Festuca > 5, count_over_5 = fest_num > 5,
           text_over_40 = naive$Festuca > 40, count_over_40 = fest_num > 40)
naive$plot[naive$Festuca > 5]
max(naive$Festuca)
stopifnot(identical(naive$plot[naive$Festuca > 5], c("P3", "P4")),
          identical(naive$plot[naive$Festuca > 40], c("P1", "P3", "P4", "P6")),
          identical(max(naive$Festuca), "n/a"),
          sum((naive$Festuca > 40) != (fest_num > 40), na.rm = TRUE) == 0,
          all(nchar(naive$Festuca[!is.na(fest_num)]) == 2),
          !("100" > 40))

## ---- read-fixed ----
sheet <- read.csv(csv_path, na.strings = c("", "n/a", "NA"))
str(sheet)
colSums(is.na(sheet))

## ---- diversity-na ----
suppressPackageStartupMessages(library(vegan))

m <- as.matrix(sheet[, 2:6])
rownames(m) <- sheet$plot
round(diversity(m), 3)

## ---- fill-zero ----
m0 <- m
m0[is.na(m0)] <- 0
round(diversity(m0), 3)

## ---- zero-identity ----
p4_zero <- m0["P4", ]
p4_drop <- p4_zero[p4_zero > 0]
c(with_zero = diversity(p4_zero), species_dropped = diversity(p4_drop))
diversity(p4_zero) - diversity(p4_drop)

## ---- truth ----
truth <- 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)
)
m_true <- as.matrix(truth[, -1])
rownames(m_true) <- truth$plot
H_true <- diversity(m_true)
H_zero <- diversity(m0)

round(cbind(truth = H_true, filled = H_zero, difference = H_zero - H_true), 4)

## ---- p4-error ----
c(true_H = unname(H_true["P4"]), filled_H = unname(H_zero["P4"]))
round(unname(100 * (H_zero["P4"] / H_true["P4"] - 1)), 1)
c(true_richness = sum(m_true["P4", ] > 0), filled_richness = sum(m0["P4", ] > 0))

## ---- ranks ----
rank_true <- names(sort(H_true, decreasing = TRUE))
rank_zero <- names(sort(H_zero, decreasing = TRUE))
rbind(truth = rank_true, filled = rank_zero)

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

cmp <- rbind(
  data.frame(plot = names(H_true), H = as.numeric(H_true), source = "true counts"),
  data.frame(plot = names(H_zero), H = as.numeric(H_zero), source = "blanks filled with zero")
)
gap <- data.frame(plot = names(H_true), lo = as.numeric(H_true), hi = as.numeric(H_zero))

ggplot(cmp, aes(plot, H)) +
  geom_segment(data = gap, aes(x = plot, xend = plot, y = lo, yend = hi),
               inherit.aes = FALSE, colour = "#dad9ca", linewidth = 1.2) +
  geom_point(aes(colour = source, shape = source), size = 3.4) +
  scale_colour_manual(values = c("true counts" = "#275139",
                                 "blanks filled with zero" = "#b5534e"),
                      breaks = c("true counts", "blanks filled with zero")) +
  scale_shape_manual(values = c("true counts" = 16, "blanks filled with zero" = 17),
                     breaks = c("true counts", "blanks filled with zero")) +
  labs(x = NULL, y = "Shannon index", colour = NULL, shape = NULL) +
  theme_minimal(base_size = 12) + te_canvas +
  theme(legend.position = "top", panel.grid.minor = element_blank())

## ---- good-sheet ----
good_lines <- c(
  "plot,Festuca,Trifolium,Plantago,Achillea,Bromus",
  "P1,42,7,3,5,11",
  "P2,38,0,4,6,9",
  "P3,51,2,1,0,14",
  "P4,NS,5,6,4,12",
  "P5,29,9,7,3,0",
  "P6,44,4,2,8,10"
)
good_path <- file.path(tempdir(), "quadrats_ns.csv")
writeLines(good_lines, good_path)

good <- read.csv(good_path, na.strings = "NS")
mg <- as.matrix(good[, -1])
rownames(mg) <- good$plot
H_good <- diversity(mg)
round(H_good, 3)

## ---- good-check ----
complete <- setdiff(rownames(mg), "P4")
max(abs(H_good[complete] - H_true[complete]))

## ---- checks ----
str(sheet)
colSums(is.na(sheet))
sapply(sheet[, 2:6], function(x) range(x, na.rm = TRUE))

## ---- fig-gaps ----
long <- data.frame(
  plot    = rep(sheet$plot, times = 5),
  species = rep(names(sheet)[2:6], each = nrow(sheet)),
  count   = as.vector(as.matrix(sheet[, 2:6]))
)
long$species <- factor(long$species, levels = names(sheet)[2:6])
long$plot <- factor(long$plot, levels = rev(sheet$plot))

ggplot(long, aes(species, plot, fill = count)) +
  geom_tile(colour = "white", linewidth = 1.1) +
  geom_text(aes(label = ifelse(is.na(count), "NA", count)),
            colour = "white", size = 3.6) +
  scale_fill_gradient(low = "#93a87f", high = "#1d5b4e", na.value = "#b5534e") +
  labs(x = NULL, y = NULL, fill = "count") +
  theme_minimal(base_size = 12) + te_canvas +
  theme(panel.grid = element_blank())
