# =============================================================================
# HSCI 841 Qualitative Research Methods and Analysis in Public Health  -  Lesson 3:
#   Sampling in Qualitative Research
# Answer key for the in-lesson R activities
# Data file(s): term projects/HSCI_841/participant_attributes.csv
# Packages: tidyverse  (install once with install.packages("tidyverse"))
# Reproduces every code block in the lesson.
#
# Paths are relative to the course repository root. Set your working directory there
# (Session > Set Working Directory > Choose Directory, or open the course .Rproj) before running.
# =============================================================================

# ==== Section 4: Documenting a Sample in R / Document the loneliness dataset's sample structure ====
library(tidyverse)

# Read the per-participant attribute file you built by hand from the transcripts
# NOTE (answer key): path corrected from "../term projects/..." to the repository-root convention.
attrs <- read_csv("term projects/HSCI_841/participant_attributes.csv", show_col_types = FALSE)

glimpse(attrs)
# Should show 20 rows and the columns: pid, name, age, gender, life_stage,
# immigration_status, caregiving_role, identity_notes

# Quick age distribution
ggplot(attrs, aes(x = age)) +
  geom_histogram(binwidth = 10, fill = "#0B7B6B", colour = "white") +
  labs(title = "Age distribution of loneliness sample (n = 20)",
       x = "Age (years)", y = "Count") +
  theme_minimal()

# Variation across gender x life-stage (a 2-way summary of the sample's coverage)
attrs |>
  count(gender, life_stage) |>
  ggplot(aes(x = life_stage, y = n, fill = gender)) +
  geom_col(position = "dodge") +
  coord_flip() +
  labs(title = "Sample coverage: gender x life-stage",
       x = NULL, y = "Number of participants") +
  theme_minimal()

# Sample matrix table (the kind that goes in your appendix)
attrs |>
  select(pid, age, gender, life_stage, immigration_status,
         caregiving_role, identity_notes) |>
  arrange(age) |>
  print(n = 20)

# ---- What the sampling matrix shows (the paragraph that goes with the figure) ----
cat("n =", nrow(attrs), "participants; ages", min(attrs$age), "to", max(attrs$age),
    "(median", median(attrs$age), ")\n")
print(count(attrs, life_stage))
print(count(attrs, gender))
print(count(attrs, immigration_status))
print(count(attrs, caregiving_role))
# Variation captured: all four life stages, three gender categories, three immigrants, five
# caregivers. Variation not captured: no participants under 18, none living outside British
# Columbia, no interviews conducted in a language other than English.
