# HSCI 410 Lesson 1, Activity 1.1: from a causal diagram to clean 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.
# install.packages(c("dagitty", "mediation", "dplyr"))   # once per computer

# 1. Write the causal diagram and read off the adjustment sets
library(dagitty)
g <- dagitty("dag {
  age -> smoker ; age -> cvd
  sex -> smoker ; sex -> cvd
  smoker -> bp ; bp -> cvd
  smoker -> cvd
  smoker -> hospital ; cvd -> hospital
}")
adjustmentSets(g, exposure = "smoker", outcome = "cvd", effect = "total")
adjustmentSets(g, exposure = "smoker", outcome = "cvd", effect = "direct")

# 2. A collider: studying only hospital patients (simulated)
set.seed(2026)
n        <- 10000
smoker   <- rbinom(n, 1, 0.30)   # 1 = smokes (30% of people)
diabetes <- rbinom(n, 1, 0.10)   # 1 = diabetes, unrelated to smoking
p_admit  <- 0.05 + 0.30 * smoker + 0.30 * diabetes   # each raises admission
hospital <- rbinom(n, 1, p_admit)
pop      <- data.frame(smoker, diabetes, hospital)
round(100 * prop.table(table(smoker = pop$smoker,
                             diabetes = pop$diabetes), margin = 1), 1)
inpatients <- subset(pop, hospital == 1)   # conditions on the collider
nrow(inpatients)
round(100 * prop.table(table(smoker = inpatients$smoker,
                             diabetes = inpatients$diabetes), margin = 1), 1)

# 3. A mediator: education -> income -> health (simulated)
library(mediation)
set.seed(410)
n         <- 800
education <- rnorm(n)
income    <- 0.6 * education + rnorm(n)                  # path a
health    <- 0.3 * education + 0.5 * income + rnorm(n)   # c' and path b
dat       <- data.frame(education, income, health)
coef(lm(health ~ education, data = dat))["education"]    # total effect c
fit_M <- lm(income ~ education, data = dat)              # mediator model
fit_Y <- lm(health ~ education + income, data = dat)     # outcome model
coef(fit_M)                                              # a
coef(fit_Y)                                              # c' and b
a <- coef(fit_M)["education"]
b <- coef(fit_Y)["income"]
a * b                                                    # indirect effect
med <- mediate(fit_M, fit_Y, treat = "education", mediator = "income",
               boot = TRUE, sims = 1000)
summary(med)

# 4. Read, clean and log the cohort file
library(dplyr)
raw <- read.csv("https://heal-learn.ca/r-activities/data/cohort.csv")   # course data, read from the website
glimpse(raw)
clean <- raw |>
  filter(!is.na(outcome)) |>
  mutate(age_grp = cut(age, c(0, 30, 50, 70, Inf)),
         smoker  = factor(smoker, levels = c("No", "Yes")))
nrow(raw)
nrow(clean)
count(clean, age_grp)
cat(format(Sys.Date()), "cohort_clean:", nrow(raw) - nrow(clean),
    "participants with no recorded outcome excluded;", nrow(clean), "remain\n")
