# Before-after-control-impact designs
# https://tidyecology.com/posts/before-after-control-impact/
#
# 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

## ---- setup ----
library(ggplot2)
paper <- "#f5f4ee"; ink <- "#16241d"; body <- "#2c3a31"
forest <- "#275139"; faint <- "#5d6b61"; line_col <- "#dad9ca"
red <- "#b5534e"; green <- "#2f8f63"
theme_te <- function(base_size = 12){
  theme_minimal(base_size = base_size) +
    theme(plot.background = element_rect(fill = paper, colour = NA),
          panel.background = element_rect(fill = paper, colour = NA),
          panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = line_col, linewidth = 0.3),
          text = element_text(colour = body),
          plot.title = element_text(colour = ink, face = "bold"),
          plot.subtitle = element_text(colour = faint),
          axis.text = element_text(colour = faint),
          legend.position = "top")
}

## ---- baci-fit ----
set.seed(161)
nrep  <- 40
mu0   <- 10     # control, before
site  <- 2      # impact site baseline higher (a pre-existing difference)
tim   <- 1      # common before -> after shift (e.g. a wet year)
delta <- -1.5   # TRUE impact: the disturbance lowers the impact site after
sdv   <- 1.5
mk <- function(mean, k) rnorm(k, mean, sdv)
CB <- mk(mu0, nrep); CA <- mk(mu0 + tim, nrep)
IB <- mk(mu0 + site, nrep); IA <- mk(mu0 + site + tim + delta, nrep)

dat <- data.frame(
  y = c(CB, CA, IB, IA),
  siteF = factor(rep(c("Control", "Impact"), each = 2 * nrep), levels = c("Control", "Impact")),
  timeF = factor(rep(rep(c("Before", "After"), each = nrep), 2), levels = c("Before", "After")))

mC <- c(mean(CB), mean(CA)); mI <- c(mean(IB), mean(IA))
ba_impact <- mI[2] - mI[1]      # before vs after, impact site only
ci_after  <- mI[2] - mC[2]      # impact vs control, after only
fit  <- lm(y ~ siteF * timeF, data = dat)
baci <- coef(fit)["siteFImpact:timeFAfter"]
baci_ci <- confint(fit)["siteFImpact:timeFAfter", ]

## ---- fig-interaction ----
cf  <- data.frame(x = c(1, 2), y = c(mI[1], mI[1] + (mC[2] - mC[1])))
seg <- data.frame(x = 2, xend = 2, y = mI[1] + (mC[2] - mC[1]), yend = mI[2])
means <- data.frame(
  x = c(1, 2, 1, 2), y = c(mC[1], mC[2], mI[1], mI[2]),
  siteF = rep(c("Control", "Impact"), each = 2))
ggplot(means, aes(x, y, colour = siteF)) +
  geom_line(linewidth = 1) + geom_point(size = 3) +
  geom_line(data = cf, aes(x, y), colour = faint, linetype = "dashed", inherit.aes = FALSE) +
  geom_segment(data = seg, aes(x = x, xend = xend, y = y, yend = yend), colour = ink,
               linewidth = 0.9, arrow = arrow(length = unit(0.12, "cm"), ends = "both"),
               inherit.aes = FALSE) +
  annotate("text", x = 2.02, y = mean(c(mI[1] + (mC[2] - mC[1]), mI[2])),
           label = "impact\n(BACI)", hjust = 0, size = 3.1, colour = ink) +
  scale_colour_manual(values = c(Control = green, Impact = red), name = NULL) +
  scale_x_continuous(breaks = c(1, 2), labels = c("Before", "After"), limits = c(0.9, 2.35)) +
  labs(x = NULL, y = "response (abundance)",
       title = "BACI reads the impact off the interaction",
       subtitle = "dashed line: where the impact site would sit if it tracked the control") +
  theme_te()

## ---- fig-estimates ----
fig2 <- data.frame(
  contrast = factor(c("Before-After\n(impact only)", "Control-Impact\n(after only)", "BACI\n(interaction)"),
                    levels = c("Before-After\n(impact only)", "Control-Impact\n(after only)", "BACI\n(interaction)")),
  est = c(ba_impact, ci_after, baci),
  lo  = c(NA, NA, baci_ci[1]), hi = c(NA, NA, baci_ci[2]),
  kind = c("wrong", "wrong", "right"))
ggplot(fig2, aes(contrast, est, colour = kind)) +
  geom_hline(yintercept = delta, linetype = "dashed", colour = ink) +
  geom_hline(yintercept = 0, colour = line_col, linewidth = 0.4) +
  geom_errorbar(aes(ymin = lo, ymax = hi), width = 0.14, linewidth = 0.8, na.rm = TRUE) +
  geom_point(size = 3) +
  scale_colour_manual(values = c(right = green, wrong = red), guide = "none") +
  labs(x = NULL, y = "estimated impact",
       title = "Single differences mislead; only BACI recovers the impact",
       subtitle = "dashed line: true impact (-1.5); thin line: zero") +
  theme_te()

## ---- parallel-trends ----
set.seed(1610)
diff_trend <- -1.2      # impact site drifting down for reasons unrelated to any impact
CB2 <- mk(mu0, nrep); CA2 <- mk(mu0 + tim, nrep)
IB2 <- mk(mu0 + site, nrep); IA2 <- mk(mu0 + site + tim + diff_trend, nrep)  # true impact = 0
dat2 <- data.frame(
  y = c(CB2, CA2, IB2, IA2),
  siteF = factor(rep(c("Control", "Impact"), each = 2 * nrep), levels = c("Control", "Impact")),
  timeF = factor(rep(rep(c("Before", "After"), each = nrep), 2), levels = c("Before", "After")))
fit2 <- lm(y ~ siteF * timeF, data = dat2)
baci2 <- coef(fit2)["siteFImpact:timeFAfter"]; baci2_ci <- confint(fit2)["siteFImpact:timeFAfter", ]
