# HSCI 410 Lesson 3, Activity 3.4: compare models and test an interaction
# 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. One complete-case data set for all twelve candidate variables
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"))
vars <- c("systolic_bp", "age", "gender", "smoker", "dep_score", "bmi", "phys_act_min",
          "anx_score", "social_support_score", "discrimination_score", "education", "region")
build <- na.omit(phaa[, vars])   # the same people for every model compared
nrow(build)

# 2. Two nested models: do BMI and physical activity improve the fit?
m_small <- lm(systolic_bp ~ age + gender + smoker + dep_score, data = build)
m_large <- lm(systolic_bp ~ age + gender + smoker + dep_score + bmi + phys_act_min, data = build)
anova(m_small, m_large)          # partial F-test for the two added terms
round(c(adjR2_small = summary(m_small)$adj.r.squared,
        adjR2_large = summary(m_large)$adj.r.squared), 3)
AIC(m_small, m_large); AIC(m_large) - AIC(m_small)   # lower is better
BIC(m_small, m_large); BIC(m_large) - BIC(m_small)   # a larger penalty per term

# 3. Gender: each indicator, then the variable as a whole
round(summary(m_small)$coefficients, 4)
m_nogen <- lm(systolic_bp ~ age + smoker + dep_score, data = build)
anova(m_nogen, m_small)          # both gender indicators tested together

# 4. Backward elimination by AIC from all eleven candidates
m_full <- lm(systolic_bp ~ ., data = build)   # every other column of build
m_back <- step(m_full, direction = "backward", trace = 0)
formula(m_back)
round(sapply(list(confounders = m_small, backward = m_back),
             function(m) coef(m)[["smokerYes"]]), 2)   # smoking estimates

# 5. Does the smoking effect depend on age?
m_int <- lm(systolic_bp ~ age * smoker + gender + dep_score, data = build)
anova(m_small, m_int)            # tests the product term age:smoker
round(summary(m_int)$coefficients, 4)
