## ----results='hide', message=FALSE, warning=FALSE-----------------------------
library(chmsflow)
library(recodeflow)
library(dplyr)


## -----------------------------------------------------------------------------
# Bundled dummy data is loaded automatically with library(chmsflow)
dim(cycle3)
dim(cycle3_meds)


## ----warning=FALSE------------------------------------------------------------
cycle3 <- recode_meds_cycles3to6(cycle3, cycle3_meds, c("any_htn_med", "diab_med"))


## -----------------------------------------------------------------------------
select(cycle3, clinicid, any_htn_med, diab_med) |> head()


## ----warning=FALSE------------------------------------------------------------
htn_variables <- c(
  # Blood pressure (raw + adjusted)
  "bpmdpbps", "bpmdpbpd", "sbp_adj_mmhg", "dbp_adj_mmhg",
  # Medication inputs (merged in step 2)
  "any_htn_med", "ccc_32",
  # Diabetes chain (input to hypertension functions)
  "lab_hba1", "diab_a1c", "ccc_51", "diab_med", "diab_status",
  # CVD chain
  "ccc_61", "ccc_63", "ccc_81", "cvd_status",
  # CKD chain
  "lab_bcre", "pgdcgt", "clc_sex", "clc_age", "gfr_ml_min", "ckd_status",
  # Hypertension outcomes
  "htn_status", "htn_adj_status", "htn_control_status", "htn_control_adj_status"
)

cycle3_htn <- recode_after_meds(cycle3, htn_variables)


## -----------------------------------------------------------------------------
cycle3_htn |>
  select(clinicid, htn_status, htn_adj_status) |>
  head(10)


## -----------------------------------------------------------------------------
table(cycle3_htn$htn_status, useNA = "always")

cycle3_htn |>
  filter(!is.na(htn_status)) |>
  summarise(
    n = n(),
    n_htn = sum(htn_status == 1),
    prevalence = mean(htn_status == 1)
  )


## ----eval=FALSE---------------------------------------------------------------
# # Repeat for cycles 4-6
# cycle4 <- recode_meds_cycles3to6(cycle4, cycle4_meds, c("any_htn_med", "diab_med"))
# cycle5 <- recode_meds_cycles3to6(cycle5, cycle5_meds, c("any_htn_med", "diab_med"))
# cycle6 <- recode_meds_cycles3to6(cycle6, cycle6_meds, c("any_htn_med", "diab_med"))
# 
# cycle4_htn <- recode_after_meds(cycle4, htn_variables)
# cycle5_htn <- recode_after_meds(cycle5, htn_variables)
# cycle6_htn <- recode_after_meds(cycle6, htn_variables)
# 
# # Add cycle identifiers and combine
# cycle3_htn$cycle <- 3
# cycle4_htn$cycle <- 4
# cycle5_htn$cycle <- 5
# cycle6_htn$cycle <- 6
# 
# combined <- bind_rows(cycle3_htn, cycle4_htn, cycle5_htn, cycle6_htn)
# 
# # Hypertension prevalence by cycle
# combined |>
#   filter(!is.na(htn_status)) |>
#   group_by(cycle) |>
#   summarise(
#     n = n(),
#     n_htn = sum(htn_status == 1),
#     prevalence = mean(htn_status == 1)
#   )

