# Summarising ecological data by group
# https://tidyecology.com/posts/grouped-summaries-in-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-09-27

## ---- data ----
library(dplyr)
surv <- data.frame(
  quadrat = c("Q1", "Q2", "Q3", "Q4", "Q5", "Q6"),
  habitat = c("edge", "edge", "interior", "interior", "interior", "edge"),
  total   = c(200,  180,   40,   30,   25,  220),   # all arthropods counted
  focal   = c( 20,   27,   20,   18,   10,   22)    # the focal beetle
)
surv

## ---- by-habitat ----
surv |>
  group_by(habitat) |>
  summarise(quadrats = n(), individuals = sum(total), focal_total = sum(focal))

## ---- per-quadrat ----
surv <- surv |> mutate(prop = focal / total)
round(surv$prop, 3)

## ---- two-summaries ----
summary_tbl <- surv |>
  summarise(
    pooled         = sum(focal) / sum(total),  # ratio of the pooled totals
    mean_of_ratios = mean(focal / total),      # average of the per-quadrat proportions
    n              = n()
  )
summary_tbl

## ---- gap-numbers ----
pooled <- sum(surv$focal) / sum(surv$total)
mor    <- mean(surv$focal / surv$total)
ratio  <- mor / pooled
rho    <- cor(surv$total, surv$prop)
wm     <- weighted.mean(surv$prop, surv$total)

## ---- weighted-mean ----
weighted.mean(surv$prop, w = surv$total)   # equals the pooled proportion

## ---- fig-props ----
library(ggplot2)
te_green <- "#275139"
ggplot(surv, aes(x = quadrat, y = prop)) +
  geom_col(fill = te_green, width = 0.66) +
  geom_hline(yintercept = pooled, linewidth = 0.9, colour = "grey15") +
  geom_hline(yintercept = mor, linewidth = 0.9, linetype = "dashed", colour = "grey15") +
  annotate("text", x = 6.35, y = pooled, label = "pooled", hjust = 1, vjust = -0.5, size = 3.3, colour = "grey15") +
  annotate("text", x = 6.35, y = mor, label = "mean of ratios", hjust = 1, vjust = -0.5, size = 3.3, colour = "grey15") +
  scale_y_continuous(expand = expansion(mult = c(0, 0.08))) +
  labs(x = NULL, y = "focal proportion") +
  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.title = element_text(colour = "grey25"))

## ---- per-q ----
per_q <- surv |>
  group_by(habitat, quadrat) |>
  summarise(focal = sum(focal), total = sum(total))
group_vars(per_q)

## ---- leftover ----
by_hab <- per_q |> summarise(pooled = sum(focal) / sum(total))
by_hab
share_sum <- per_q |> mutate(share = focal / sum(focal)) |> pull(share) |> sum()
share_sum

## ---- three-fixes ----
surv |>
  group_by(habitat, quadrat) |>
  summarise(focal = sum(focal), total = sum(total), .groups = "drop") |>
  summarise(pooled = sum(focal) / sum(total))
per_q |> ungroup() |> summarise(pooled = sum(focal) / sum(total))
surv |>
  summarise(focal = sum(focal), total = sum(total), .by = c(habitat, quadrat)) |>
  summarise(pooled = sum(focal) / sum(total))

## ---- by-on-grouped ----
tryCatch(per_q |> summarise(pooled = sum(focal) / sum(total), .by = habitat),
         error = function(e) conditionMessage(e))

## ---- grouping-checks ----
msgs <- character(0); warns <- 0
again <- withCallingHandlers(
  surv |> group_by(habitat, quadrat) |> summarise(focal = sum(focal), total = sum(total)),
  message = function(m) { msgs <<- c(msgs, conditionMessage(m)); invokeRestart("muffleMessage") },
  warning = function(w) { warns <<- warns + 1; invokeRestart("muffleWarning") })
stopifnot(length(msgs) == 1, grepl("habitat", msgs), warns == 0, identical(group_vars(per_q), "habitat"))
stopifnot(nrow(per_q) == nrow(surv), nrow(by_hab) == 2, isTRUE(all.equal(share_sum, n_distinct(surv$habitat))))
fix_drop <- surv |> group_by(habitat, quadrat) |> summarise(focal = sum(focal), total = sum(total), .groups = "drop")
fix_by <- surv |> summarise(focal = sum(focal), total = sum(total), .by = c(habitat, quadrat))
stopifnot(!is_grouped_df(fix_drop), !is_grouped_df(fix_by), is.data.frame(fix_by), !inherits(fix_by, "tbl_df"))
for (tab in list(fix_drop, ungroup(per_q), fix_by)) stopifnot(all.equal(sum(tab$focal) / sum(tab$total), pooled))
stopifnot(inherits(tryCatch(summarise(per_q, n = n(), .by = habitat), error = function(e) e), "error"))
stopifnot(length(unique(table(surv$habitat))) == 1, all(tapply(surv$total, surv$habitat, function(x) max(x) / min(x)) < 2))
stopifnot(packageVersion("dplyr") >= "1.1.0")
