# Joining ecological tables without losing zeros
# https://tidyecology.com/posts/joining-ecological-tables/
#
# 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-26

## ---- site-table ----
library(dplyr)
library(tidyr)
sites <- data.frame(
  site    = paste0("S", 1:10),
  habitat = c(rep("forest", 5), rep("open", 5))
)
sites

## ---- obs-table ----
obs <- data.frame(
  site  = c("S1", "S2", "S3", "S4", "S5", "S6"),
  count = c(  12,    9,   15,    8,   11,    6)
)
obs

## ---- inner ----
inner <- inner_join(sites, obs, by = "site")
nrow(inner)

## ---- inner-numbers ----
mean_inner <- mean(inner$count)

## ---- inner-mean ----
mean(inner$count)      # mean over the six sites where the species was seen

## ---- left ----
full <- left_join(sites, obs, by = "site") |>
  mutate(count = replace_na(count, 0))
full

## ---- full-numbers ----
mean_full <- mean(full$count)
bias <- (mean_inner - mean_full) / mean_full * 100

## ---- full-mean ----
mean(full$count)       # mean over every surveyed site

## ---- dup-visits ----
visits <- data.frame(site  = rep(sites$site, each = 2),
                     visit = rep(1:2, times = 10))
sites_twice <- rbind(sites, sites[sites$site == "S7", ])   # S7 is on both sheets
visits_joined <- left_join(visits, sites_twice, by = "site")
table(visits_joined$habitat)
nrow(merge(visits, sites_twice, by = "site"))   # base R: same rows, no warning

## ---- dup-appended ----
obs_appended <- rbind(obs, data.frame(site = "S3", count = 5))   # old S3 row still there
full_appended <- left_join(sites, obs_appended, by = "site") |>
  mutate(count = replace_na(count, 0))
nrow(full_appended)
full_appended |> group_by(habitat) |> summarise(mean_count = mean(count), n_sites = n())

## ---- dup-guards ----
said <- function(expr) {                      # every warning or message an expression gives
  out <- character(0)
  keep <- function(cnd) { out <<- c(out, conditionMessage(cnd)); tryInvokeRestart("muffleWarning"); tryInvokeRestart("muffleMessage") }
  withCallingHandlers(expr, warning = keep, message = keep)
  out
}
said_visits <- said(left_join(visits, sites_twice, by = "site"))
obs_corrected <- transform(obs, count = ifelse(site == "S3", 5, count))
forest_mean <- function(tab) {   # forest mean count after the left join and zero fill
  joined <- left_join(sites, tab, by = "site") |> mutate(count = replace_na(count, 0))
  mean(joined$count[joined$habitat == "forest"]) }
error_text <- function(expr) tryCatch({ expr; "" }, error = function(e) conditionMessage(e))
stopifnot(length(said_visits) == 1, grepl("many-to-many", said_visits),
          length(said(merge(visits, sites_twice, by = "site"))) == 0,
          length(said(left_join(sites, obs_appended, by = "site"))) == 0,
          grepl("Row 3 of `x`", error_text(left_join(sites, obs_appended, by = "site", relationship = "one-to-one"))),
          grepl("Row 13 of `x`", error_text(left_join(visits, sites_twice, by = "site", relationship = "many-to-one"))),
          grepl("Row 13 of `x` matches multiple rows in `y`", said_visits), grepl("Row 1 of `y` matches multiple rows in `x`", said_visits),
          sites_twice$site[1] == "S1", sum(visits$site == "S1") == 2, sum(sites_twice$site == "S7") == 2,
          visits$site[13] == "S7", visits$visit[13] == 1, anyDuplicated(obs_appended$site) == 7, obs_appended$site[7] == "S3")

## ---- dup-checks ----
anyDuplicated(obs_appended$site)   # 0 would mean every site appears once
checked <- tryCatch(
  left_join(sites, obs_appended, by = "site", relationship = "one-to-one"),
  error = function(e) conditionMessage(e)   # print the error instead of stopping
)
cat(checked)
first_only <- left_join(sites, obs_appended, by = "site", multiple = "first")
first_only$count[first_only$site == "S3"]

## ---- by-habitat ----
by_habitat <- bind_rows(
  inner |> mutate(join = "inner") ,
  full  |> mutate(join = "left+0")
) |>
  group_by(join, habitat) |>
  summarise(mean_count = mean(count), n_sites = n(), .groups = "drop")
by_habitat

## ---- ratio-numbers ----
gi <- inner |> group_by(habitat) |> summarise(m = mean(count), .groups="drop")
gf <- full  |> group_by(habitat) |> summarise(m = mean(count), .groups="drop")
ri <- gi$m[gi$habitat=="forest"] / gi$m[gi$habitat=="open"]
rf <- gf$m[gf$habitat=="forest"] / gf$m[gf$habitat=="open"]
open_inner <- gi$m[gi$habitat=="open"]
open_full  <- gf$m[gf$habitat=="open"]

## ---- fig-habitat ----
library(ggplot2)
te_green <- "#275139"
te_grey  <- "#9aa79a"
pd <- by_habitat
pd$join <- factor(pd$join, levels = c("inner", "left+0"),
                  labels = c("inner join (drops zeros)", "left join + fill 0"))
ggplot(pd, aes(x = habitat, y = mean_count, fill = habitat)) +
  geom_col(width = 0.62) +
  facet_wrap(~ join) +
  scale_fill_manual(values = c(forest = te_green, open = te_grey)) +
  scale_y_continuous(expand = expansion(mult = c(0, 0.06))) +
  labs(x = NULL, y = "mean focal count") +
  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 = "none",
        strip.text = element_text(colour = "grey20"),
        axis.title = element_text(colour = "grey25"))
