# GEE or a mixed model? Marginal and conditional
# https://tidyecology.com/posts/gee-or-a-mixed-model/
#
# 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-01

## ---- setup ----
library(lme4)
library(geepack)
library(ggplot2)

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"

theme_datasheet <- function() {
  theme_minimal(base_size = 12) +
    theme(plot.background  = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          text             = element_text(colour = te_body),
          plot.title       = element_text(colour = te_ink, face = "bold"),
          axis.text        = element_text(colour = te_body))
}

sim_binary <- function(n_site = 60, n_visit = 12, sigma = 1.2, beta = 1.0) {
  site <- rep(seq_len(n_site), each = n_visit)
  u    <- rnorm(n_site, 0, sigma)[site]
  x    <- rnorm(n_site * n_visit)
  data.frame(site = factor(site), x = x,
             y = rbinom(length(x), 1, plogis(-0.3 + beta * x + u)))
}

set.seed(20260812)
d  <- sim_binary()
ds <- d[order(d$site), ]      # geeglm needs the clusters contiguous
table(table(d$site))

## ---- fits ----
m_glmm <- glmer(y ~ x + (1 | site), family = binomial, data = d)
m_gee  <- geeglm(y ~ x, id = site, family = binomial,
                 corstr = "exchangeable", data = ds)

round(c(glmm_slope = fixef(m_glmm)[["x"]],
        gee_slope  = coef(m_gee)[["x"]],
        site_sd    = sqrt(unlist(VarCorr(m_glmm))[[1]]),
        alpha      = summary(m_gee)$corr[1, 1]), 3)

## ---- icc ----
sig2 <- unlist(VarCorr(m_glmm))[[1]]
round(c(gee_alpha  = summary(m_gee)$corr[1, 1],
        site_var   = sig2,
        latent_icc = sig2 / (sig2 + pi^2 / 3)), 3)

## ---- attenuation ----
s <- sqrt(unlist(VarCorr(m_glmm))[[1]])
round(c(observed_ratio = coef(m_gee)[["x"]] / fixef(m_glmm)[["x"]],
        approximation  = (1 + 0.346 * s^2)^(-0.5)), 3)

## ---- sweep ----
one_rep <- function(sigma) {
  dd <- sim_binary(sigma = sigma)
  g  <- glmer(y ~ x + (1 | site), family = binomial, data = dd)
  e  <- geeglm(y ~ x, id = site, family = binomial, corstr = "exchangeable",
               data = dd[order(dd$site), ])
  c(glmm = fixef(g)[["x"]], gee = coef(e)[["x"]])
}
sigmas <- c(0, 0.5, 1, 1.5, 2, 3)
set.seed(9)
sw <- t(vapply(sigmas, function(s0) rowMeans(replicate(30, one_rep(s0))),
               numeric(2)))
sweep_tab <- data.frame(sigma = sigmas, glmm = sw[, 1], gee = sw[, 2],
                        ratio = sw[, 2] / sw[, 1],
                        approx = (1 + 0.346 * sigmas^2)^(-0.5))
round(sweep_tab, 3)

## ---- fig-attenuation ----
top <- rbind(
  data.frame(sigma = sigmas, value = sweep_tab$glmm, what = "mixed model slope"),
  data.frame(sigma = sigmas, value = sweep_tab$gee,  what = "GEE slope"))
bot <- rbind(
  data.frame(sigma = sigmas, value = sweep_tab$ratio,  what = "measured ratio"),
  data.frame(sigma = sigmas, value = sweep_tab$approx, what = "approximation"))
top$panel <- "estimated slope"
bot$panel <- "GEE slope divided by mixed model slope"
both <- rbind(top, bot)
both$panel <- factor(both$panel, levels = unique(both$panel))
both$what  <- factor(both$what, levels = c("mixed model slope", "GEE slope",
                                           "measured ratio", "approximation"))

ggplot(both, aes(x = sigma, y = value, colour = what, linetype = what)) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 2) +
  facet_wrap(~ panel, ncol = 1, scales = "free_y") +
  scale_colour_manual(values = c(te_forest, te_rust, te_gold, te_ink)) +
  scale_linetype_manual(values = c("solid", "solid", "solid", "dashed")) +
  labs(x = "between-site standard deviation on the logit scale",
       y = NULL, colour = NULL, linetype = NULL,
       title = "The gap is the between-site variation") +
  theme_datasheet() +
  theme(legend.position = "bottom",
        strip.text = element_text(colour = te_ink, face = "bold"))

## ---- marginalise ----
b  <- fixef(m_glmm)
xs <- seq(-2.5, 2.5, length.out = 60)
marginal_of_glmm <- vapply(xs, function(xx)
  integrate(function(u) plogis(b[[1]] + b[[2]] * xx + u) * dnorm(u, 0, s),
            -6 * s, 6 * s)$value, numeric(1))
gee_fit <- plogis(coef(m_gee)[[1]] + coef(m_gee)[[2]] * xs)

round(c(largest_gap = max(abs(gee_fit - marginal_of_glmm)),
        at_x_zero_gee = gee_fit[which.min(abs(xs))],
        at_x_zero_integrated = marginal_of_glmm[which.min(abs(xs))]), 4)

## ---- fig-curves ----
site_u <- ranef(m_glmm)$site[, 1]
per_site <- do.call(rbind, lapply(seq_along(site_u), function(i)
  data.frame(x = xs, p = plogis(b[[1]] + b[[2]] * xs + site_u[i]), site = i)))
avg <- data.frame(x = xs, p = marginal_of_glmm)
gee <- data.frame(x = xs, p = gee_fit)

ggplot() +
  geom_line(data = per_site, aes(x = x, y = p, group = site),
            colour = te_forest, alpha = 0.22, linewidth = 0.4) +
  geom_line(data = avg, aes(x = x, y = p), colour = te_ink,
            linewidth = 1.4, linetype = "dashed") +
  geom_line(data = gee, aes(x = x, y = p), colour = te_rust, linewidth = 1) +
  annotate("text", x = -2.4, y = 0.93, hjust = 0, size = 3.5, colour = te_ink,
           label = "dashed: mixed model curves averaged over sites") +
  annotate("text", x = -2.4, y = 0.85, hjust = 0, size = 3.5, colour = te_rust,
           label = "solid: the GEE fit") +
  labs(x = "covariate", y = "probability of detection",
       title = "Sixty site curves and the one curve through their middle") +
  theme_datasheet()

## ---- poisson ----
sim_pois <- function(n_site = 60, n_visit = 12, sigma = 0.8, beta = 0.5) {
  site <- rep(seq_len(n_site), each = n_visit)
  u <- rnorm(n_site, 0, sigma)[site]
  x <- rnorm(n_site * n_visit)
  data.frame(site = factor(site), x = x,
             y = rpois(length(x), exp(0.8 + beta * x + u)))
}
set.seed(20260812)
dp <- sim_pois()
p_glmm <- glmer(y ~ x + (1 | site), family = poisson, data = dp)
p_gee  <- geeglm(y ~ x, id = site, family = poisson, corstr = "exchangeable",
                 data = dp[order(dp$site), ])

round(c(glmm_slope     = fixef(p_glmm)[["x"]],
        gee_slope      = coef(p_gee)[["x"]],
        glmm_intercept = fixef(p_glmm)[[1]],
        gee_intercept  = coef(p_gee)[[1]],
        half_variance  = unlist(VarCorr(p_glmm))[[1]] / 2), 3)

## ---- sandwich ----
sim_level <- function(level, n_site = 60, n_visit = 12, sigma = 1.2, beta = 1) {
  site <- rep(seq_len(n_site), each = n_visit)
  u <- rnorm(n_site, 0, sigma)[site]
  x <- if (level == "site") rnorm(n_site)[site] else rnorm(n_site * n_visit)
  data.frame(site = factor(site), x = x,
             y = rbinom(length(x), 1, plogis(-0.3 + beta * x + u)))
}
one_se <- function(level) {
  dd <- sim_level(level)
  dd <- dd[order(dd$site), ]
  g  <- geeglm(y ~ x, id = site, family = binomial, corstr = "exchangeable",
               data = dd)
  gi <- glm(y ~ x, family = binomial, data = dd)
  c(gee_est = coef(g)[["x"]],   sandwich = coef(summary(g))[2, 2],
    glm_est = coef(gi)[["x"]],  naive    = coef(summary(gi))[2, 2])
}
se_tab <- do.call(rbind, lapply(c("visit", "site"), function(lv) {
  set.seed(55)
  R <- t(replicate(300, one_se(lv)))
  # each standard error is compared with the spread of ITS OWN estimator
  data.frame(covariate    = lv,
             gee_spread   = sd(R[, "gee_est"]),   # equal to glm_spread for a site-level
                                                  # covariate with balanced clusters
             sandwich     = mean(R[, "sandwich"]),
             glm_spread   = sd(R[, "glm_est"]),
             naive_glm    = mean(R[, "naive"]))
}))
se_tab$naive_over_true <- se_tab$naive_glm / se_tab$glm_spread
data.frame(covariate = se_tab$covariate,
           round(se_tab[, -1], 4))

## ---- fig-se ----
bars <- data.frame(
  covariate = rep(c("visit-level covariate", "site-level covariate"), each = 4),
  what = rep(c("GEE spread", "sandwich SE", "glm spread", "plain glm SE"), 2),
  value = c(se_tab$gee_spread[1], se_tab$sandwich[1],
            se_tab$glm_spread[1], se_tab$naive_glm[1],
            se_tab$gee_spread[2], se_tab$sandwich[2],
            se_tab$glm_spread[2], se_tab$naive_glm[2]))
bars$covariate <- factor(bars$covariate,
                         levels = c("visit-level covariate", "site-level covariate"))
bars$what <- factor(bars$what,
                    levels = c("GEE spread", "sandwich SE",
                               "glm spread", "plain glm SE"))

ggplot(bars, aes(x = covariate, y = value, fill = what)) +
  geom_col(position = position_dodge(width = 0.8), width = 0.72) +
  scale_fill_manual(values = c(te_forest, "#8fae94", te_gold, te_rust)) +
  labs(x = NULL, y = "standard error of the slope", fill = NULL,
       title = "Where ignoring the clusters actually costs you") +
  theme_datasheet() +
  theme(legend.position = "bottom")
