# Temporal autocorrelation and effective sample size
# https://tidyecology.com/posts/autocorrelation-in-time-series/
#
# 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-14

## ---- setup ----
library(ggplot2)

theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) + theme(
    text = element_text(colour = "#2c3a31"),
    plot.title = element_text(colour = "#16241d", face = "bold", size = rel(0.95)),
    plot.subtitle = element_text(colour = "#46604a", size = rel(0.80)),
    axis.title = element_text(colour = "#46604a", size = rel(0.88)),
    axis.text = element_text(colour = "#5d6b61", size = rel(0.78)),
    panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3),
    panel.grid.minor = element_blank(),
    plot.background = element_rect(fill = "#f5f4ee", colour = NA),
    panel.background = element_rect(fill = "#f5f4ee", colour = NA),
    legend.title = element_text(colour = "#46604a", size = rel(0.80)),
    legend.text = element_text(colour = "#5d6b61", size = rel(0.78)),
    legend.position = "top")
}
FOREST <- "#275139"; GOLD <- "#c9b458"; RUST <- "#b5534e"; MOWN <- "#2f8f63"; SAGE <- "#93a87f"

# ACF by hand (biased estimator, matching stats::acf)
acf_hand <- function(x, kmax) {
  x <- x - mean(x); d0 <- sum(x^2)
  sapply(0:kmax, function(k) sum(x[(k + 1):length(x)] * x[1:(length(x) - k)]) / d0)
}
# PACF by the Durbin-Levinson recursion
pacf_dl <- function(rho, kmax) {
  phi_kk <- numeric(kmax); phi_prev <- numeric(0)
  for (k in 1:kmax) {
    if (k == 1) { phi_kk[1] <- rho[2] } else {
      phi_kk[k] <- (rho[k + 1] - sum(phi_prev * rho[k:2])) / (1 - sum(phi_prev * rho[2:k]))
    }
    phi_new <- numeric(k); phi_new[k] <- phi_kk[k]
    if (k > 1) phi_new[1:(k - 1)] <- phi_prev - phi_kk[k] * rev(phi_prev)
    phi_prev <- phi_new
  }
  phi_kk
}
# ACF at lags 1..kmax (no lag 0), for the effective-df correction
acf_est <- function(x, kmax) {
  x <- x - mean(x); d0 <- sum(x^2)
  sapply(1:kmax, function(k) sum(x[(k + 1):length(x)] * x[1:(length(x) - k)]) / d0)
}
# Dutilleul (1993) modified t-test p-value for cor(x, y)
mod_t_p <- function(x, y) {
  r <- cor(x, y); m <- length(x); kmax <- floor(m / 5)
  rx <- acf_est(x, kmax); ry <- acf_est(y, kmax)
  ne <- max(1 + m / (1 + 2 * sum(rx * ry)), 3)
  tstat <- r * sqrt((ne - 2) / (1 - r^2))
  2 * pt(-abs(tstat), df = ne - 2)
}

## ---- sim-acf ----
set.seed(4240)
phi <- 0.7; n <- 120
y <- as.numeric(arima.sim(list(ar = phi), n = n))

K <- 20
acf_h <- acf_hand(y, K)                 # by hand
acf_b <- as.numeric(acf(y, lag.max = K, plot = FALSE)$acf)
pacf_h <- pacf_dl(acf_h, K)
pacf_b <- as.numeric(pacf(y, lag.max = K, plot = FALSE)$acf)

acf_match  <- max(abs(acf_h - acf_b))
pacf_match <- max(abs(pacf_h - pacf_b))

## ---- fp-guard-1 ----
stopifnot(max(abs(acf_match)) < 1e-10, max(abs(pacf_match)) < 1e-10)

## ---- fig-correlogram ----
band <- 1.96 / sqrt(n)
dfA <- data.frame(lag = 1:K, acf = acf_h[2:(K + 1)], theo = phi^(1:K))
pA <- ggplot(dfA, aes(lag, acf)) +
  geom_hline(yintercept = 0, colour = "#46604a", linewidth = 0.4) +
  geom_hline(yintercept = c(-band, band), colour = RUST, linetype = "dashed", linewidth = 0.4) +
  geom_segment(aes(xend = lag, yend = 0), colour = FOREST, linewidth = 0.8) +
  geom_point(colour = FOREST, size = 1.6) +
  geom_line(aes(y = theo), colour = GOLD, linewidth = 0.7) +
  geom_point(aes(y = theo), colour = GOLD, size = 1.0) +
  labs(title = "Sample ACF (green) vs theoretical phi^k (gold)",
       subtitle = "Dashed rust: naive white-noise band (1.96 / sqrt(n))",
       x = "Lag (months)", y = "Autocorrelation") +
  coord_cartesian(ylim = c(-0.35, 1)) + theme_te()
dfB <- data.frame(lag = 1:K, pacf = pacf_h)
pB <- ggplot(dfB, aes(lag, pacf)) +
  geom_hline(yintercept = 0, colour = "#46604a", linewidth = 0.4) +
  geom_hline(yintercept = c(-band, band), colour = RUST, linetype = "dashed", linewidth = 0.4) +
  geom_segment(aes(xend = lag, yend = 0), colour = FOREST, linewidth = 0.8) +
  geom_point(colour = FOREST, size = 1.6) +
  labs(title = "Sample PACF: one spike at lag 1, then silence",
       subtitle = "The AR(1) fingerprint: PACF cuts off after the order p",
       x = "Lag (months)", y = "Partial autocorrelation") +
  coord_cartesian(ylim = c(-0.35, 1)) + theme_te()
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 2)))
print(pA, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pB, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2))

## ---- eff-n ----
vif_mean <- (1 + phi) / (1 - phi)
n_eff <- n * (1 - phi) / (1 + phi)

## ---- mean-coverage ----
B <- 4000
means <- naive_se <- numeric(B)
set.seed(4240)
for (b in seq_len(B)) {
  z <- as.numeric(arima.sim(list(ar = phi), n = n))
  means[b] <- mean(z)
  naive_se[b] <- sd(z) / sqrt(n)
}
emp_sd <- sd(means)
ratio_se <- emp_sd / mean(naive_se)
cover_naive <- mean(abs(means) <= 1.96 * naive_se)
cover_eff <- mean(abs(means) <= 1.96 * naive_se * sqrt(vif_mean))

## ---- spurious-demo ----
set.seed(4240)
x1 <- as.numeric(arima.sim(list(ar = phi), n = n))
y1 <- as.numeric(arima.sim(list(ar = phi), n = n))   # generated independently of x1
r_demo <- cor(x1, y1)
p_ols <- summary(lm(y1 ~ x1))$coefficients[2, 4]
p_corr <- mod_t_p(x1, y1)

## ---- spurious-mc ----
B <- 3000
p_naive <- p_dutil <- p_white <- numeric(B)
set.seed(4241)
for (b in seq_len(B)) {
  x <- as.numeric(arima.sim(list(ar = phi), n = n))
  y <- as.numeric(arima.sim(list(ar = phi), n = n))
  p_naive[b] <- summary(lm(y ~ x))$coefficients[2, 4]
  p_dutil[b] <- mod_t_p(x, y)
  xw <- rnorm(n); yw <- rnorm(n)                       # white-noise control
  p_white[b] <- summary(lm(yw ~ xw))$coefficients[2, 4]
}
rej_naive <- mean(p_naive < 0.05)
rej_dutil <- mean(p_dutil < 0.05)
rej_white <- mean(p_white < 0.05)

set.seed(4242)
r_ar <- r_wn <- numeric(B)
for (b in seq_len(B)) {
  r_ar[b] <- cor(as.numeric(arima.sim(list(ar = phi), n = n)),
                 as.numeric(arima.sim(list(ar = phi), n = n)))
  r_wn[b] <- cor(rnorm(n), rnorm(n))
}

## ---- fig-spurious ----
dfR <- rbind(data.frame(r = r_ar, kind = "AR(1) series (phi = 0.7)"),
             data.frame(r = r_wn, kind = "White noise"))
pA <- ggplot(dfR, aes(r, fill = kind, colour = kind)) +
  geom_density(alpha = 0.35, linewidth = 0.6) +
  scale_fill_manual(values = c("AR(1) series (phi = 0.7)" = FOREST, "White noise" = GOLD)) +
  scale_colour_manual(values = c("AR(1) series (phi = 0.7)" = FOREST, "White noise" = GOLD)) +
  geom_vline(xintercept = c(-0.2, 0.2), colour = RUST, linetype = "dashed", linewidth = 0.4) +
  labs(title = "Null distribution of the sample correlation r",
       subtitle = "Two INDEPENDENT series; autocorrelation widens the spurious range",
       x = "Correlation r between two independent series", y = "Density",
       fill = NULL, colour = NULL) +
  theme_te()
dfT <- data.frame(
  method = factor(c("Naive OLS\nt-test", "Effective-df\ncorrection", "White-noise\ncontrol"),
                  levels = c("Naive OLS\nt-test", "Effective-df\ncorrection", "White-noise\ncontrol")),
  rate = c(rej_naive, rej_dutil, rej_white))
pB <- ggplot(dfT, aes(method, rate, fill = method)) +
  geom_col(width = 0.62) +
  geom_hline(yintercept = 0.05, colour = RUST, linetype = "dashed", linewidth = 0.5) +
  geom_text(aes(label = sprintf("%.3f", rate)), vjust = -0.5, colour = "#16241d", size = 3.3) +
  annotate("text", x = 3.4, y = 0.078, label = "nominal 0.05", colour = RUST, size = 2.9, hjust = 1) +
  scale_fill_manual(values = c(RUST, MOWN, SAGE), guide = "none") +
  labs(title = "Type I error rate for the slope",
       subtitle = "Naive test rejects far too often; the correction comes near nominal",
       x = NULL, y = "Rejection rate at 0.05") +
  coord_cartesian(ylim = c(0, 0.27)) + theme_te()
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 2)))
print(pA, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pB, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2))
