# HSCI 410 Lesson 2, Activity 2.1: a first look at the raw survey file
# 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 raw file and check its size
# Blank cells and the text "NA" become missing values (NA)
phaa <- read.csv("https://heal-learn.ca/r-activities/data/phaa_survey.csv",   # course data, read from the website
                 stringsAsFactors = FALSE, na.strings = c("", "NA"))
dim(phaa)                 # rows (people) and columns (variables)

# 2. How R stores each variable
str(phaa)                 # each variable's type and first few values
table(phaa$income, useNA = "ifany")   # income bands, stored as text

# 3. Screen the ranges against the codebook (Table 2.1)
summary(phaa[, c("age", "systolic_bp", "bmi", "dep1")])
phaa[phaa$age < 18 | phaa$age > 100, c("id", "age")]       # valid: 18 to 100
phaa[phaa$systolic_bp < 80 | phaa$systolic_bp > 220,       # valid: 80 to 220
     c("id", "systolic_bp", "diastolic_bp")]
phaa[phaa$bmi < 13 | phaa$bmi > 60, c("id", "bmi")]        # valid: 13 to 60

# 4. Categories, duplicates and missing values
table(phaa$smoker, useNA = "ifany")   # counts for a text variable
sum(duplicated(phaa$id))              # IDs that appear more than once
colSums(is.na(phaa))                  # missing values in each column
