# HSCI 410 Lesson 5, Activity 5.2: a random-intercept model for blood pressure
# 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. Load lmerTest and read the clinic data
library(lmerTest)   # loads lme4 and adds p-values to lmer() output
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"))
clinics$clinic_urban <- factor(clinics$clinic_urban, levels = c("rural", "urban"))
nlevels(clinics$clinic_id)   # how many clinics?

# 2. A random intercept for each clinic
lmm <- lmer(sbp ~ age + female + smoker + clinic_urban + (1 | clinic_id),
            data = clinics)
summary(lmm)
confint(lmm, parm = "beta_", method = "Wald")   # 95% CIs for the fixed effects
head(ranef(lmm)$clinic_id, 3)   # estimated shifts of clinics 1 to 3 (mmHg)

# 3. The variance components and the adjusted ICC
vc <- as.data.frame(VarCorr(lmm))
vc[, c("grp", "vcov")]       # variance between and within clinics
vc$vcov[1] / sum(vc$vcov)    # ICC after adjusting for the predictors

# 4. Check the model
par(mfrow = c(1, 3))         # three plots side by side
plot(fitted(lmm), resid(lmm), main = "Residuals vs fitted")
abline(h = 0, lty = 2)
qqnorm(resid(lmm), main = "Q-Q: residuals"); qqline(resid(lmm))
re <- ranef(lmm)$clinic_id[, 1]   # the 30 clinic shifts
qqnorm(re, main = "Q-Q: clinic effects"); qqline(re)
par(mfrow = c(1, 1))
isSingular(lmm)              # FALSE: the clinic variance was estimated

# 5. Try a random slope for age
lmm_rs <- lmer(sbp ~ age + female + smoker + clinic_urban + (age | clinic_id),
               data = clinics)
