# HSCI 410 Lesson 3, Activity 3.2: fit, read and check a multivariable linear model
# 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.
# install.packages(c("lmtest", "car", "sandwich"))   # run once, if not yet installed
library(lmtest); library(car); library(sandwich)

# 1. Read the data and fit the five-predictor model
phaa <- read.csv("https://heal-learn.ca/r-activities/data/phaa_survey_clean.csv")   # course data, read from the website
phaa$smoker <- factor(phaa$smoker, levels = c("No", "Yes"))   # "No" = reference
phaa$gender <- factor(phaa$gender, levels = c("Man", "Woman", "Non-binary"))
cc <- na.omit(phaa[, c("systolic_bp", "age", "gender", "smoker", "bmi", "dep_score")])
nrow(cc)                     # people with complete data for the model
model <- lm(systolic_bp ~ age + gender + smoker + bmi + dep_score, data = cc)
summary(model)
round(confint(model), 2)     # 95% confidence intervals

# 2. Check the assumptions
par(mfrow = c(2, 2))         # four plots on one screen
plot(model)                  # the four diagnostic plots
par(mfrow = c(1, 1))         # back to one plot per screen
model_sq <- lm(systolic_bp ~ age + I(age^2) + gender + smoker + bmi + dep_score, data = cc)
anova(model, model_sq)       # linearity: does a squared age term help?
bptest(model)                # equal spread (Breusch-Pagan test)
shapiro.test(residuals(model))   # normality of the residuals

# 3. Influence, collinearity and standard errors without equal spread
cooks <- cooks.distance(model)
sum(cooks > 4 / nrow(cc))    # rows above the 4/n screening line
round(max(cooks), 3)         # the largest Cook's distance
vif(model)                   # collinearity (values near 1 are good)
round(coeftest(model, vcov = vcovHC(model, type = "HC3"))[, 1:2], 3)   # sandwich SEs
