# HSCI 410 Lesson 5, Activity 5.1: detecting clustering in the clinic data
# 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 the package, read the data and count the clinics
# install.packages("lmerTest")   # run once if needed; it also installs lme4
library(lmerTest)    # loads lme4 (for lmer()) and adds p-values
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)   # a label for each clinic
clinics$clinic_urban <- factor(clinics$clinic_urban, levels = c("rural", "urban"))
nlevels(clinics$clinic_id)                     # how many clinics?
summary(as.vector(table(clinics$clinic_id)))   # patients per clinic

# 2. The ICC from a model with clinics only
m0 <- lmer(sbp ~ 1 + (1 | clinic_id), data = clinics)
vc <- as.data.frame(VarCorr(m0))
vc[, c("grp", "vcov")]                # variance between and within clinics
icc <- vc$vcov[1] / sum(vc$vcov)      # intracluster correlation coefficient
icc

# 3. The design effect and the effective sample size
m_bar <- mean(table(clinics$clinic_id))   # average clinic size
deff <- 1 + (m_bar - 1) * icc             # design effect
deff
nrow(clinics) / deff                      # effective sample size

# 4. Ignoring the clinics, and allowing for them
naive <- lm(sbp ~ clinic_urban, data = clinics)                      # ignores clinics
mixed <- lmer(sbp ~ clinic_urban + (1 | clinic_id), data = clinics)   # allows for clinics
summary(naive)$coefficients
summary(mixed)$coefficients
