# HSCI 410 Lesson 5, Activity 5.3: a GLMM and GEE for specialist referral
# Run-along script for the narrated walkthrough. It reads the course data
# directly from the course website, so there is nothing to set up: open it
# in RStudio and run each part with Ctrl+Enter when the narration asks.

# 1. Packages, data and the checks before fitting
library(lme4); library(geepack)   # glmer() for the GLMM, geeglm() for GEE
clinics <- read.csv("https://heal-learn.ca/r-activities/data/phaa_clinics.csv")   # course data, read from the website
clinics$clinic_id <- factor(clinics$clinic_id)
clinics$smoker <- factor(clinics$smoker, levels = c("No", "Yes"))   # "No" = reference
clinics$clinic_urban <- factor(clinics$clinic_urban, levels = c("rural", "urban"))
table(clinics$referred)        # 1 = referred: how many events?
nlevels(clinics$clinic_id)     # how many clusters?

# 2. Ordinary logistic regression, which ignores the clinics
naive <- glm(referred ~ age + smoker + clinic_urban, family = binomial, data = clinics)

# 3. The GLMM: logistic regression with a random intercept for each clinic
glmm <- glmer(referred ~ age + smoker + clinic_urban + (1 | clinic_id),
              family = binomial, data = clinics)
summary(glmm)
round(exp(cbind(OR = fixef(glmm), confint(glmm, parm = "beta_", method = "Wald"))), 3)

# 4. GEE: sort by clinic, then fit with an exchangeable working correlation
clinics <- clinics[order(clinics$clinic_id), ]   # each clinic's rows together
gee <- geeglm(referred ~ age + smoker + clinic_urban, id = clinic_id,
              family = binomial, corstr = "exchangeable", data = clinics)
summary(gee)
round(exp(cbind(OR = coef(gee), confint.default(gee))), 3)

# 5. Odds ratios and standard errors (log-odds scale) from the three models
or_se <- function(fit, x) {
  b <- summary(fit)$coefficients[x, 1:2]   # estimate and its SE
  c(OR = exp(b[[1]]), SE = b[[2]])
}
three <- function(x) rbind(glm = or_se(naive, x), glmer = or_se(glmm, x), geeglm = or_se(gee, x))
round(three("smokerYes"), 3)           # a patient-level predictor
round(three("clinic_urbanurban"), 3)   # a clinic-level predictor
