Applied Health Economics, RWE & HTA
Overview / Module 1 / Day 8
Module 1 · Health system & data · Day 8 of 100

R Day: The Cohort in R

Canadian health research runs on R as well as Python. Many ICES analysts, most HTA modellers, and every package from Module 5 onward use it. Today you rebuild Days 5–7 in R: the diabetes definition, the base cohort and its costs. Each result is checked against the Python number to the last person and the last cent. You will see that R and Python are two front ends to the same engine. dbplyr turns dplyr code into SQL, and DuckDB runs it.

▶
Video for Day 8 coming soon

By the end of today you can

  • R, the packages and an editor are installed, and Rscript day08/case_definition.R runs
  • explain why the hand-off between tools is Parquet, not the DuckDB file
  • translate pandas and SQL operations into dplyr, and read dbplyr's SQL with show_query()
  • My R diabetes definition, attrition and costs match Python exactly
  • handle NA explicitly in every filter on a column that can be missing

Today's 5.5-hour plan

LessonProjectBreakCommitFrançais
0:00–0:30
8.1 Set up R
0:30–0:55
8.2 Hand the warehouse to R as Parquet
0:55–1:35
8.3 R for a Python programmer
1:35–1:50
Break
1:50–2:30
8.4 dbplyr: dplyr in, SQL out
2:30–3:10
8.5 The diabetes definition in R
3:10–3:25
Break
3:25–4:00
8.6 The cohort and its costs in R
4:00–4:20
8.7 NA is not FALSE
4:20–4:50
8.8 Mini-project: Table 1 as an R function
4:50–5:00
8.9 Save your work
5:00–5:30
Bloc français

In this lesson

8.1 Set up R (30 min)

Windows. Install R (4.5 or newer) from CRAN, then an editor: Positron (Posit's newer editor, which feels like VS Code) or RStudio. VS Code with the R extension also works. Then install the course packages once, from the repository folder:

# Day 8: install the R packages the course uses (run once).
install.packages(c("DBI", "duckdb", "dplyr", "dbplyr", "tidyr", "ggplot2", "scales"))

Run course scripts from the repository root, in a terminal:

Rscript day08/case_definition.R

or open them in Positron/RStudio with the working directory set to the repository. The course was tested with R 4.5.3, duckdb 1.5.5, DBI 1.3.0, dplyr 1.2.1, dbplyr 2.6.0 and ggplot2 4.0.4.

You will see a note from duckdb about a temporary directory for extensions. It is informational and does not affect the results.


8.2 Hand the warehouse to R as Parquet (25 min)

The warehouse is a DuckDB database file, and a DuckDB file can only be opened by a DuckDB version that understands its storage format. The Python package (2.0.1) wrote it. The R package available here (1.5.5) is older and refuses to open it. Version mismatches between tools are routine in real projects. The robust hand-off is Parquet: an open, typed, compressed column format that every tool reads (R, Python, Spark, Power BI, even recent SAS Viya).

"""Day 8.2: hand the warehouse to R (and anything else) as Parquet files in warehouse/export/.

Also writes warehouse/export/python_reference.csv: key numbers from the Python lessons,
which the R scripts check themselves against.
"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.cohort import diabetes_case_dates, build_base_cohort  # noqa: E402
from corridor.costs import cohort_follow_up, window_costs_sql  # noqa: E402
from corridor.db import ROOT, warehouse  # noqa: E402

TABLES = ["dim_person", "fct_physician_claims", "fct_hospital_diagnoses", "fct_hospital_stays",
          "fct_drug_dispensations", "fct_person_years", "int_cost_items", "stg_drug_plan_eligibility"]
out = os.path.join(ROOT, "warehouse", "export")
os.makedirs(out, exist_ok=True)
con = warehouse()
for t in TABLES:
    path = os.path.join(out, f"{t}.parquet").replace("\\", "/")
    con.execute(f"COPY (SELECT * FROM {t}) TO '{path}' (FORMAT parquet)")
    print(f"{t:<28}{con.sql(f'SELECT count(*) FROM {t}').fetchall()[0][0]:>12,} rows")
for name in ("cohort_base", "cohort_costs"):
    src = os.path.join(ROOT, "warehouse", f"{name}.parquet").replace("\\", "/")
    dst = os.path.join(out, f"{name}.parquet").replace("\\", "/")
    con.execute(f"COPY (SELECT * FROM read_parquet('{src}')) TO '{dst}' (FORMAT parquet)")
    print(f"{name:<28}{con.sql(f'SELECT count(*) FROM read_parquet(' + chr(39) + dst + chr(39) + ')').fetchall()[0][0]:>12,} rows")

# reference numbers from the Python lessons (Days 5-7)
END = "2024-12-31"
pop = f"""SELECT person_id FROM dim_person
          WHERE registry_start <= DATE '{END}' AND (death_date IS NULL OR death_date > DATE '{END}')"""
ref = {}
for d in ("two_claims", "ontario"):
    ref[f"diabetes_{d}_found"] = con.sql(f"""SELECT count(*) FROM ({pop}) JOIN ({diabetes_case_dates(con, d, END)})
                                              USING (person_id)""").fetchall()[0][0]
attrition = build_base_cohort(con)
for i, (label, n, _) in enumerate(attrition.steps):
    ref[f"attrition_step_{i}"] = n
cohort_follow_up(con)
END25 = "DATE '2025-12-31'"
con.execute(f"CREATE TEMP TABLE f AS {window_costs_sql('fu', 'i.index_date', END25)}")
for prov, total, days in con.sql("""SELECT coalesce(province, 'All'), sum(total), sum(days)
                                    FROM fu JOIN f USING (person_id) GROUP BY ROLLUP (province)""").fetchall():
    ref[f"fu_cost_per_py_{prov}"] = round(total / (days / 365.25), 2)
with open(os.path.join(out, "python_reference.csv"), "w", encoding="utf-8") as fh:
    fh.write("name,value\n")
    for k in sorted(ref):
        fh.write(f"{k},{ref[k]}\n")
print(f"\npython_reference.csv: {len(ref)} numbers")
dim_person                       262,711 rows
fct_physician_claims           6,886,737 rows
fct_hospital_diagnoses           323,570 rows
fct_hospital_stays               185,123 rows
fct_drug_dispensations         4,499,768 rows
fct_person_years               1,717,853 rows
int_cost_items                11,571,628 rows
stg_drug_plan_eligibility        118,784 rows
cohort_base                        6,224 rows
cohort_costs                       6,224 rows

python_reference.csv: 13 numbers

The export also writes python_reference.csv, the key numbers from Days 5–7. The R scripts check themselves against it, so "the R version gives the same answer" is a test, not an impression.

The R helper file opens an in-memory DuckDB with one view per Parquet file, just like corridor.db.connect() did for CSVs on Day 1:

# Corridor Health helpers for R (Day 8).
# Run scripts from the repository root, e.g.  Rscript day08/case_definition.R

suppressPackageStartupMessages({
  library(DBI)
  library(duckdb)
  library(dplyr)
  library(dbplyr)
})
options(width = 140, dplyr.summarise.inform = FALSE)

# An in-memory DuckDB with one view per Parquet file in warehouse/export/.
corridor_connect <- function(root = ".") {
  con <- dbConnect(duckdb())
  files <- list.files(file.path(root, "warehouse", "export"), pattern = "\\.parquet$", full.names = TRUE)
  if (length(files) == 0) stop("No Parquet files: run  python day08/build_exports.py  first")
  for (f in files) {
    name <- sub("\\.parquet$", "", basename(f))
    path <- normalizePath(f, winslash = "/")
    dbExecute(con, sprintf("CREATE VIEW %s AS SELECT * FROM read_parquet('%s')", name, path))
  }
  con
}

# Exact age in whole years on date d (same rule as age_on() in Python), as SQL for mutate(age = sql(...)).
age_on_sql <- function(birth_col, d) {
  sprintf("date_diff('year', %s, DATE '%s') - (strftime(DATE '%s', '%%m-%%d') < strftime(%s, '%%m-%%d'))::INT",
          birth_col, d, d, birth_col)
}

# Print a data frame the way the Python lessons do: no row names, all rows.
show <- function(df) {
  print(as.data.frame(df), row.names = FALSE)
  invisible(df)
}

# The Python lessons' reference numbers (written by day08/build_exports.py).
python_reference <- function(root = ".") {
  ref <- read.csv(file.path(root, "warehouse", "export", "python_reference.csv"))
  setNames(ref$value, ref$name)
}

8.3 R for a Python programmer (40 min)

Python (pandas)R (dplyr)SQL
df[df.age >= 80]filter(df, age >= 80)WHERE age >= 80
df[["a", "b"]]select(df, a, b)SELECT a, b
df.assign(x=...)mutate(df, x = ...)SELECT ..., ... AS x
df.groupby("g").agg(...)group_by(df, g) |> summarise(...)GROUP BY g
df.sort_values("x")arrange(df, x)ORDER BY x
a.merge(b, on="id")inner_join(a, b, by = "id")JOIN ... USING (id)
None / NaNNANULL
method chainingthe pipe |>nesting

R counts from 1, <- assigns, and a "vector" (c(1, 2, 3)) is the basic unit: every column is one.

# Day 8.3: R for a Python programmer - the base cohort as a data frame.
source("r/corridor.R")
con <- corridor_connect()

cohort <- tbl(con, "cohort_base") |> collect()   # 6,224 rows: small enough to pull into R
cat("Rows and columns:", nrow(cohort), ncol(cohort), "\n")
cat("Column classes:\n")
print(vapply(cohort[, c("person_id", "age", "rural", "index_date", "prior_stays")], function(x) class(x)[1], ""))

cat("\n--- Base R: a vector, a mean, a table\n")
ages <- cohort$age
cat("mean age", round(mean(ages), 1), "| median", median(ages), "| range", range(ages), "\n")
print(table(cohort$province, cohort$sex))

cat("\n--- dplyr: the same verbs as SQL, joined with the pipe |>\n")
cohort |>
  filter(age >= 80) |>
  group_by(province) |>
  summarise(people = n(),
            mean_age = round(mean(age), 1),
            pct_heart_failure = round(100 * mean(heart_failure), 1),
            pct_sglt2 = round(100 * mean(sglt2), 1)) |>
  arrange(province) |>
  show()
Rows and columns: 6224 20 
Column classes:
  person_id         age       rural  index_date prior_stays 
"character"   "numeric"   "logical"      "Date"   "numeric" 

--- Base R: a vector, a mean, a table
mean age 79.2 | median 78 | range 66 100 
    
        F    M
  ON 1908 2048
  QC 1091 1177

--- dplyr: the same verbs as SQL, joined with the pipe |>
 province people mean_age pct_heart_failure pct_sglt2
       ON   1779     87.1              23.3      43.2
       QC   1018     86.9              22.4      38.3

Three things to notice: rural arrives from Parquet as a true R logical, index_date as a Date, and age as a double (numeric) because DuckDB's 64-bit integers map to doubles in R. collect() pulled 6,224 rows into R memory. For the 6.9 million claims you will not do that.


8.4 dbplyr: dplyr in, SQL out (40 min)

tbl(con, "fct_physician_claims") does not read anything. It is a lazy reference. dplyr verbs on it build a SQL query, which runs only when you collect() (or print) the result.

# Day 8.4: dbplyr - write dplyr, DuckDB runs SQL. Nothing is computed until collect().
source("r/corridor.R")
con <- corridor_connect()

claims <- tbl(con, "fct_physician_claims")
by_year <- claims |>
  filter(dx_code == "250") |>
  group_by(service_year) |>
  summarise(claims = n(), people = n_distinct(person_id)) |>
  arrange(service_year)

cat("--- The query dbplyr wrote\n")
show_query(by_year)
cat("\n--- The result (7 rows came back to R, not 6.9 million)\n")
by_year |> collect() |> show()
--- The query dbplyr wrote
<SQL>
SELECT
  service_year,
  COUNT(*) AS claims,
  COUNT(DISTINCT row(person_id)) AS people
FROM fct_physician_claims
WHERE (dx_code = '250')
GROUP BY service_year
ORDER BY service_year

--- The result (7 rows came back to R, not 6.9 million)
 service_year claims people
         2019  65378  21772
         2020  70095  23114
         2021  76471  24847
         2022  83564  26853
         2023  94258  29709
         2024 101218  27648
         2025 117737  35945

show_query() is your friend. When a dbplyr result looks wrong, read the SQL it wrote. Two dbplyr rules prevent most surprises:

  1. Functions dbplyr knows (n(), n_distinct(), lag(), pmin(), is.na(), %in%, %LIKE%) become SQL. Any other function name is passed to the database as-is. To use an R value, compute it first and inject it with !!, or write SQL directly with sql("...").
  2. Aggregates in SQL skip missing values. Write min(x, na.rm = TRUE) to say you know.

Try it (10 min). With dbplyr, find the five most common main diagnoses of the cohort's hospital stays in 2025. Look at the SQL first.

Solution
# Day 8 exercise: the cohort's five most common reasons for a hospital stay in 2025 (dbplyr).
source("r/corridor.R")
con <- corridor_connect()

top <- tbl(con, "fct_hospital_stays") |>
  filter(admit_date >= sql("DATE '2025-01-01'")) |>
  semi_join(tbl(con, "cohort_base"), by = "person_id") |>
  count(mrdx, sort = TRUE) |>
  head(5)
show_query(top)
cat("\n")
show(collect(top))
<SQL>
SELECT mrdx, COUNT(*) AS n
FROM (
  SELECT LHS.*
  FROM (
    SELECT *
    FROM fct_hospital_stays
    WHERE (admit_date >= DATE '2025-01-01')
) AS LHS
  WHERE EXISTS (
    SELECT 1 FROM cohort_base
    WHERE (LHS.person_id = cohort_base.person_id)
  )
) AS q01
GROUP BY mrdx
ORDER BY n DESC
LIMIT 5

 mrdx   n
 I500 425
 N179 349
 N184 300
 E112 230
 J189 222

semi_join() became WHERE EXISTS, the efficient way to say "only people in the cohort". Heart failure, acute kidney injury and CKD lead, as you would expect in this population.


8.5 The diabetes definition in R (40 min)

The Day 5 window function, lag() over each person's claims in date order, is group_by() |> window_order() |> mutate(previous = lag(...)) in dbplyr:

# Day 8.5: the Ontario diabetes definition (Day 5) in dplyr - and a check against Python.
source("r/corridor.R")
con <- corridor_connect()
ref <- python_reference()
end <- "2024-12-31"

# two physician claims (ICD-9 250) within 730 days: the date of the second
two_claims <- tbl(con, "fct_physician_claims") |>
  filter(dx_code == "250", service_date <= sql(sprintf("DATE '%s'", end))) |>
  group_by(person_id) |>
  window_order(service_date) |>
  mutate(previous = lag(service_date)) |>
  ungroup() |>
  filter(!is.na(previous), sql("date_diff('day', previous, service_date)") <= 730) |>
  group_by(person_id) |>
  summarise(case_date = min(service_date, na.rm = TRUE))

# one hospital stay with type 2 diabetes (E11*) in any position
hospital <- tbl(con, "fct_hospital_diagnoses") |>
  filter(code %LIKE% "E11%", admit_date <= sql(sprintf("DATE '%s'", end))) |>
  group_by(person_id) |>
  summarise(case_date = min(admit_date, na.rm = TRUE))

ontario <- union_all(two_claims, hospital) |>
  group_by(person_id) |>
  summarise(case_date = min(case_date, na.rm = TRUE))

population <- tbl(con, "dim_person") |>
  filter(registry_start <= sql(sprintf("DATE '%s'", end)),
         is.na(death_date) | death_date > sql(sprintf("DATE '%s'", end))) |>
  select(person_id)

n_two <- population |> semi_join(two_claims, by = "person_id") |> count() |> pull(n)
n_ont <- population |> semi_join(ontario, by = "person_id") |> count() |> pull(n)
cat(sprintf("two claims within 2 years: %s people (Python %s)\n", format(n_two, big.mark = ","),
            format(ref[["diabetes_two_claims_found"]], big.mark = ",")))
cat(sprintf("Ontario definition:        %s people (Python %s)\n", format(n_ont, big.mark = ","),
            format(ref[["diabetes_ontario_found"]], big.mark = ",")))
stopifnot(n_two == ref[["diabetes_two_claims_found"]], n_ont == ref[["diabetes_ontario_found"]])
cat("Both match.\n")
two claims within 2 years: 28,110 people (Python 28,110)
Ontario definition:        28,239 people (Python 28,239)
Both match.

Same people, to the last one. When two implementations in two languages agree on 28,239 people, you can be confident that both implement the definition you wrote down.


8.6 The cohort and its costs in R (35 min)

The Day 6 rules, written as R functions over lazy tables. keep() records the count after each step, like Attrition in Python:

# Day 8: the Day 5-6 cohort rules in dplyr (lazy: DuckDB does the work).

d <- function(x) sql(sprintf("DATE '%s'", x))

diabetes_cases <- function(con, end = "2099-12-31") {
  two <- tbl(con, "fct_physician_claims") |>
    filter(dx_code == "250", service_date <= !!d(end)) |>
    group_by(person_id) |> window_order(service_date) |>
    mutate(previous = lag(service_date)) |> ungroup() |>
    filter(!is.na(previous), sql("date_diff('day', previous, service_date)") <= 730) |>
    group_by(person_id) |> summarise(case_date = min(service_date, na.rm = TRUE))
  hosp <- tbl(con, "fct_hospital_diagnoses") |>
    filter(code %LIKE% "E11%", admit_date <= !!d(end)) |>
    group_by(person_id) |> summarise(case_date = min(admit_date, na.rm = TRUE))
  union_all(two, hosp) |> group_by(person_id) |> summarise(case_date = min(case_date, na.rm = TRUE))
}

ckd_cases <- function(con, end = "2099-12-31") {
  two <- tbl(con, "fct_physician_claims") |>
    filter(dx_code == "585", service_date <= !!d(end)) |>
    group_by(person_id) |> window_order(service_date) |>
    mutate(previous = lag(service_date)) |> ungroup() |>
    filter(!is.na(previous), sql("date_diff('day', previous, service_date)") <= 730) |>
    group_by(person_id) |> summarise(case_date = min(service_date, na.rm = TRUE))
  hosp <- tbl(con, "fct_hospital_diagnoses") |>
    filter(code %LIKE% "N18%" | code == "Z491", admit_date <= !!d(end)) |>
    group_by(person_id) |> summarise(case_date = min(admit_date, na.rm = TRUE))
  dial <- tbl(con, "fct_physician_claims") |>
    filter(fee_code %in% c("CH103", "Q0103"), service_date <= !!d(end)) |>
    group_by(person_id) |> summarise(case_date = min(service_date, na.rm = TRUE))
  union_all(two, hosp, dial) |> group_by(person_id) |> summarise(case_date = min(case_date, na.rm = TRUE))
}

# Days on a public drug plan in the 365 days before the index date.
covered_days <- function(con, index) {
  w_start <- format(as.Date(index) - 365)
  w_end <- format(as.Date(index) - 1)
  tbl(con, "stg_drug_plan_eligibility") |>
    mutate(s = pmax(start_date, !!d(w_start)), e = pmin(coalesce(end_date, !!d(w_end)), !!d(w_end))) |>
    filter(e >= s) |>
    group_by(person_id) |>
    summarise(covered_days = sum(sql("date_diff('day', s, e) + 1"), na.rm = TRUE))
}

# The base cohort, one step at a time; returns the remaining people (lazy) and the counts.
build_base_cohort_r <- function(con, index = "2025-01-01") {
  before <- format(as.Date(index) - 1)
  steps <- list()
  keep <- function(x, label) {
    n <- x |> count() |> pull(n)
    steps[[length(steps) + 1]] <<- data.frame(step = length(steps), criterion = label, remaining = n)
    x
  }
  dx_before <- diabetes_cases(con) |> filter(case_date <= !!d(before))
  ckd_before <- ckd_cases(con) |> filter(case_date <= !!d(before))
  dialysis <- union_all(
    tbl(con, "fct_physician_claims") |> filter(fee_code %in% c("CH103", "Q0103"), service_date <= !!d(before)) |>
      select(person_id),
    tbl(con, "fct_hospital_diagnoses") |> filter(code == "Z491", admit_date <= !!d(before)) |> select(person_id))
  x <- tbl(con, "dim_person") |> keep("Start")
  x <- x |> filter(registry_start <= !!d(index), is.na(death_date) | death_date >= !!d(index)) |>
    keep("Alive and registered on the index date")
  x <- x |> filter(registry_start <= !!d(format(as.Date(index) - 365))) |>
    keep("Registered for at least 365 days before the index date")
  x <- x |> mutate(age = sql(age_on_sql("birth_date", index))) |> filter(age >= 66) |>
    keep("Aged 66 or older on the index date")
  x <- x |> semi_join(dx_before, by = "person_id") |> keep("Diabetes before the index date (Ontario definition)")
  x <- x |> semi_join(ckd_before, by = "person_id") |> keep("Chronic kidney disease before the index date")
  x <- x |> semi_join(covered_days(con, index) |> filter(covered_days >= 365), by = "person_id") |>
    keep("On a public drug plan for all 365 days before the index date")
  x <- x |> anti_join(dialysis, by = "person_id") |> keep("No dialysis before the index date")
  list(cohort = x, attrition = do.call(rbind, steps))
}
# Day 8.6: the Day 6 base cohort, rebuilt in R, step by step - and checked against Python.
source("r/corridor.R")
source("r/cohort.R")
con <- corridor_connect()
ref <- python_reference()

res <- build_base_cohort_r(con)
att <- res$attrition
att$python <- vapply(att$step, function(i) ref[[paste0("attrition_step_", i)]], numeric(1))
att$match <- att$remaining == att$python
show(att)
stopifnot(all(att$match))
cat("\nEvery step matches the Python cohort.\n")
 step                                                    criterion remaining python match
    0                                                        Start    262711 262711  TRUE
    1                       Alive and registered on the index date    247521 247521  TRUE
    2       Registered for at least 365 days before the index date    246147 246147  TRUE
    3                           Aged 66 or older on the index date     58608  58608  TRUE
    4          Diabetes before the index date (Ontario definition)     15574  15574  TRUE
    5                 Chronic kidney disease before the index date      6664   6664  TRUE
    6 On a public drug plan for all 365 days before the index date      6521   6521  TRUE
    7                            No dialysis before the index date      6224   6224  TRUE

Every step matches the Python cohort.

And Day 7's follow-up costs, with a ggplot2 chart:

# Day 8.7: follow-up costs of the cohort (Day 7) in R, and a ggplot2 chart.
source("r/corridor.R")
suppressPackageStartupMessages(library(ggplot2))
con <- corridor_connect()
ref <- python_reference()

fu <- tbl(con, "cohort_base") |>
  select(person_id, province, index_date) |>
  inner_join(tbl(con, "dim_person") |> select(person_id, death_date), by = "person_id") |>
  mutate(end_date = pmin(coalesce(death_date, sql("DATE '2025-12-31'")), sql("DATE '2025-12-31'")),
         days = sql("date_diff('day', index_date, end_date) + 1"))

costs <- fu |>
  inner_join(tbl(con, "int_cost_items") |> select(person_id, cost_date, component, payer_cost_2025),
             by = "person_id") |>
  filter(cost_date >= index_date, cost_date <= end_date) |>
  group_by(province, component) |>
  summarise(cost = sum(payer_cost_2025, na.rm = TRUE)) |>
  collect()
person_years <- fu |> group_by(province) |> summarise(py = sum(days, na.rm = TRUE) / 365.25) |> collect()

by_component <- costs |>
  inner_join(person_years, by = "province") |>
  mutate(per_py = cost / py) |>
  arrange(province, component)
show(by_component |> mutate(cost = round(cost), py = round(py, 1), per_py = round(per_py)))

totals <- by_component |>
  group_by(province) |> summarise(per_py = round(sum(cost) / first(py), 2))
all_py <- round(sum(costs$cost) / sum(person_years$py), 2)
cat("\nTotal per person-year, R vs Python:\n")
check <- data.frame(group = c(totals$province, "All"), r = c(totals$per_py, all_py),
                    python = c(ref[["fu_cost_per_py_ON"]], ref[["fu_cost_per_py_QC"]], ref[["fu_cost_per_py_All"]]))
show(check)
stopifnot(isTRUE(all.equal(check$r, check$python, tolerance = 1e-6)))

p <- ggplot(by_component, aes(x = province, y = per_py, fill = component)) +
  geom_col(width = 0.6) +
  scale_y_continuous(labels = scales::dollar) +
  scale_fill_manual(values = c(drug = "#d97706", hospital = "#2563eb", physician = "#059669")) +
  labs(x = NULL, y = "Public payer cost per person-year (2025 $)", fill = NULL,
       title = "Base cohort, 2025 follow-up") +
  theme_minimal(base_size = 11)
ggsave("figures/day08_costs_r.png", p, width = 5.5, height = 3.6, dpi = 130)
cat("\nSaved figures/day08_costs_r.png\n")
 province component     cost     py per_py
       ON      drug  4166106 3825.0   1089
       ON  hospital 15033938 3825.0   3930
       ON physician  2151300 3825.0    562
       QC      drug  1736348 2178.8    797
       QC  hospital  7945497 2178.8   3647
       QC physician  1192667 2178.8    547

Total per person-year, R vs Python:
 group       r  python
    ON 5582.10 5582.10
    QC 4991.00 4991.00
   All 5367.59 5367.59

Saved figures/day08_costs_r.png

Follow-up cost per person-year by component, made in R


8.7 NA is not FALSE (20 min)

Bug of the day. A colleague keeps people "alive on the index date" with filter(death_date >= index):

# Day 8 bug of the day: a comparison with a missing value is neither TRUE nor FALSE.
# A colleague keeps people "alive on the index date" with death_date >= index.
source("r/corridor.R")
con <- corridor_connect()
index <- "2025-01-01"
people <- tbl(con, "dim_person") |> filter(registry_start <= sql(sprintf("DATE '%s'", index)))

wrong <- people |> filter(death_date >= sql(sprintf("DATE '%s'", index))) |> count() |> pull(n)
right <- people |> filter(is.na(death_date) | death_date >= sql(sprintf("DATE '%s'", index))) |> count() |> pull(n)
cat(sprintf("death_date >= index:                   %7s people\n", format(wrong, big.mark = ",")))
cat(sprintf("is.na(death_date) | death_date >= index: %5s people\n", format(right, big.mark = ",")))

cat("\nIn R itself:\n")
x <- as.Date(c("2025-06-01", NA))
print(x >= as.Date(index))
print(subset(data.frame(x = x), x >= as.Date(index)))
death_date >= index:                     2,495 people
is.na(death_date) | death_date >= index: 247,521 people

In R itself:
[1] TRUE   NA
           x
1 2025-06-01

The cohort collapses from 247,521 to 2,495: only people who die later are kept. Everyone still alive has death_date = NA, and NA >= index is NA, not TRUE. filter(), subset() and SQL WHERE all drop rows where the condition is NA. Python's Attrition.keep() guards against this with coalesce(condition, false), which turns unknown into excluded. In R, write the missing case out: is.na(death_date) | death_date >= index. The step counts in 8.6 would have caught it, which is one more reason to count after every step.


8.8 Mini-project: Table 1 as an R function (30 min)

Write table_one_r(): means (SD) and counts (%) by group, small cells hidden, standardized differences. Check it against Day 6, and save it as a CSV a report can use.

# Day 8 mini-project: Table 1 (Day 6) as an R function, checked against the Python numbers,
# and saved as a CSV for a report.
source("r/corridor.R")
con <- corridor_connect()
cohort <- tbl(con, "cohort_base") |> collect()

smd_mean <- function(a, b) (mean(a) - mean(b)) / sqrt((var(a) + var(b)) / 2)
smd_prop <- function(a, b) {
  p1 <- mean(a); p2 <- mean(b)
  (p1 - p2) / sqrt((p1 * (1 - p1) + p2 * (1 - p2)) / 2)
}
cell <- function(x, small = 6) {
  n <- sum(x)
  if (n > 0 && n < small) sprintf("<%d", small) else sprintf("%s (%.1f%%)", format(n, big.mark = ","), 100 * mean(x))
}

table_one_r <- function(df, group, binary, continuous) {
  g <- sort(unique(df[[group]]))
  a <- df[df[[group]] == g[1], ]
  b <- df[df[[group]] == g[2], ]
  rows <- list(data.frame(characteristic = "People", A = format(nrow(a), big.mark = ","),
                          B = format(nrow(b), big.mark = ","), smd = ""))
  for (v in continuous) {
    rows[[length(rows) + 1]] <- data.frame(
      characteristic = paste0(v, ", mean (SD)"),
      A = sprintf("%.1f (%.1f)", mean(a[[v]]), sd(a[[v]])), B = sprintf("%.1f (%.1f)", mean(b[[v]]), sd(b[[v]])),
      smd = sprintf("%.2f", smd_mean(a[[v]], b[[v]])))
  }
  for (v in binary) {
    rows[[length(rows) + 1]] <- data.frame(
      characteristic = paste0(v, ", n (%)"), A = cell(a[[v]]), B = cell(b[[v]]),
      smd = sprintf("%.2f", smd_prop(a[[v]], b[[v]])))
  }
  out <- do.call(rbind, rows)
  names(out)[2:3] <- g
  out
}

cohort$female <- cohort$sex == "F"
t1 <- table_one_r(cohort, "province",
                  binary = c("female", "rural", "heart_failure", "sglt2", "insulin"),
                  continuous = c("age", "physician_visits"))
show(t1)

# the same values as Day 6's Python Table 1
stopifnot(t1$smd[t1$characteristic == "rural, n (%)"] == "-0.22",
          t1$smd[t1$characteristic == "age, mean (SD)"] == "0.02",
          t1$ON[t1$characteristic == "sglt2, n (%)"] == "1,648 (41.7%)")
write.csv(t1, "docs/table_one_r.csv", row.names = FALSE)
cat("\nMatches Day 6. Saved docs/table_one_r.csv\n")
              characteristic            ON            QC   smd
                      People         3,956         2,268      
              age, mean (SD)    79.3 (8.5)    79.1 (8.4)  0.02
 physician_visits, mean (SD)    11.3 (4.3)    11.3 (4.3) -0.00
               female, n (%) 1,908 (48.2%) 1,091 (48.1%)  0.00
                rural, n (%)   468 (11.8%)   452 (19.9%) -0.22
        heart_failure, n (%)   605 (15.3%)   346 (15.3%)  0.00
                sglt2, n (%) 1,648 (41.7%)   865 (38.1%)  0.07
              insulin, n (%) 1,067 (27.0%)   568 (25.0%)  0.04

Matches Day 6. Saved docs/table_one_r.csv

8.9 Save your work

git add .
git commit -m "Day 8: the cohort in R, checked against Python"

warehouse/export/ is generated, so it stays out of Git, like the warehouse itself.

Day 8 checklist

  • R, the packages and an editor are installed, and Rscript day08/case_definition.R runs
  • I can explain why the hand-off between tools is Parquet, not the DuckDB file
  • I can translate pandas and SQL operations into dplyr, and read dbplyr's SQL with show_query()
  • My R diabetes definition, attrition and costs match Python exactly
  • I handle NA explicitly in every filter on a column that can be missing