# HSCI 410 Lesson 5, Activity 5.4: repeated measures with a mixed model and GEE
# 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. Read the trial data and look at its layout
library(lmerTest)   # loads lme4 and adds p-values to lmer() output
visits <- read.csv("https://heal-learn.ca/r-activities/data/phaa_repeated.csv")   # course data, read from the website
visits$id  <- factor(visits$id)   # the person: the cluster
visits$arm <- factor(visits$arm, levels = c("control", "intervention"))
head(visits, 8)              # long format: one row per visit

# 2. Missed visits
table(visit = visits$visit, missing = is.na(visits$sbp_mmhg))
all4 <- tapply(!is.na(visits$sbp_mmhg), visits$id, all)   # all four visits?
table(all4)                  # FALSE: missed at least one visit
first <- visits[visits$visit == 0, ]           # each person's month-0 row
round(tapply(first$sbp_mmhg, all4[first$id], mean, na.rm = TRUE), 1)

# 3. A mixed model for blood pressure over time
round(tapply(visits$sbp_mmhg, list(visits$arm, visits$visit), mean, na.rm = TRUE), 1)
lmm_t <- lmer(sbp_mmhg ~ arm * visit + (1 | id), data = visits)
summary(lmm_t)

# 4. The ICC and the extra change over 18 months
vc <- as.data.frame(VarCorr(lmm_t))
vc$vcov[1] / sum(vc$vcov)                      # ICC: how alike a person's visits are
18 * fixef(lmm_t)[["armintervention:visit"]]   # extra change over 18 months

# 5. GEE for adherence, a repeated yes-or-no outcome
library(geepack)
adh <- visits[!is.na(visits$adherent), ]       # visits with adherence recorded
adh <- adh[order(adh$id, adh$visit), ]         # each person's rows together
round(tapply(adh$adherent, list(adh$arm, adh$visit), mean), 2)   # share adherent
gee_a <- geeglm(adherent ~ arm * visit, id = id, family = binomial,
                corstr = "exchangeable", data = adh)
summary(gee_a)
options(digits = 7)   # summary() lowers the printed digits; this restores them
round(exp(cbind(OR = coef(gee_a), confint.default(gee_a))), 3)   # odds ratios, 95% CIs
