# HSCI 410 Lesson 3, Activity 3.1: two-variable tests and the first regressions
# 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 data and set the reference group
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

# 2. Four two-variable tests
cor.test(phaa$age, phaa$systolic_bp)          # two numeric variables
t.test(systolic_bp ~ smoker, data = phaa, var.equal = TRUE)   # two group means
round(tapply(phaa$systolic_bp, phaa$region, mean, na.rm = TRUE), 1)
summary(aov(systolic_bp ~ region, data = phaa))   # three or more means
phaa$elevated_bp <- factor(ifelse(phaa$systolic_bp >= 120, "Yes", "No"),
                           levels = c("No", "Yes"))   # 120 mmHg or more
tab <- table(phaa$smoker, phaa$elevated_bp)
tab                                       # counts
round(prop.table(tab, margin = 1), 3)     # share with elevated BP
chisq.test(tab)                           # two categorical variables

# 3. The t-test as a regression
fit_smk <- lm(systolic_bp ~ smoker, data = phaa)
summary(fit_smk)$coefficients

# 4. Physical activity, before and after adjusting for age
act <- na.omit(phaa[, c("systolic_bp", "phys_act_min", "age")])
nrow(act)                                 # the same people in both models
crude <- lm(systolic_bp ~ phys_act_min, data = act)
adjusted <- lm(systolic_bp ~ phys_act_min + age, data = act)
round(summary(crude)$coefficients, 4)
round(summary(adjusted)$coefficients, 4)
100 * coef(crude)[["phys_act_min"]]       # per 100 minutes, crude
100 * coef(adjusted)[["phys_act_min"]]    # per 100 minutes, adjusted
