# Setting up R and RStudio for ecology
# https://tidyecology.com/posts/setting-up-r-for-ecology/
#
# 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-15

## ---- plot-counts ----
counts <- c(`Carex flava` = 12, `Juncus effusus` = 5,
            `Poa pratensis` = 8, `Festuca rubra` = 1)
N <- sum(counts)              # this plot's total: 26 individuals
p <- counts / N               # relative abundances
H_correct <- -sum(p * log(p)) # Shannon diversity
round(H_correct, 3)

## ---- stale-state ----
# the workspace still holds N <- 40 from an earlier, different plot
N_stale <- 40
p_stale <- counts / N_stale         # divides by the wrong total
H_stale <- -sum(p_stale * log(p_stale))
round(H_stale, 3)                   # a Shannon value, but the wrong one

## ---- stale-numbers ----
H_correct <- -sum((counts / sum(counts)) * log(counts / sum(counts)))
H_stale   <- -sum((counts / 40) * log(counts / 40))
pct       <- (H_stale - H_correct) / H_correct * 100
sum_stale <- sum(counts / 40)

## ---- clean-session ----
clean <- new.env(parent = baseenv())  # an empty workspace, as a fresh session would have
clean$counts <- counts
result <- tryCatch(
  eval(quote(counts / N), envir = clean),   # N does not exist here
  error = function(e) conditionMessage(e)
)
result

## ---- fig-abundance ----
library(ggplot2)
te_green <- "#275139"
df <- data.frame(species = names(counts),
                 prop = as.numeric(counts) / sum(counts))
df$species <- factor(df$species, levels = df$species[order(-df$prop)])
ggplot(df, aes(x = species, y = prop)) +
  geom_col(fill = te_green, width = 0.68) +
  scale_y_continuous(expand = expansion(mult = c(0, 0.05))) +
  labs(x = NULL, y = "relative abundance") +
  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(),
        axis.text.x = element_text(face = "italic", colour = "grey20"),
        axis.title = element_text(colour = "grey25"))
