Skip to contents

Port of the epiENGAGE count-file algorithm (Ramona Lall and Alison Levin-Rector, NYC DOHMH). Starting from visit-level data it:

Usage

ts_counts(
  visits,
  end_date,
  tree_wide,
  study_days = 90L,
  lookback_days = 365L,
  ineligible = ts_ineligible_pattern(),
  seed = NULL
)

ts_ineligible_pattern()

Arguments

visits

Output of ts_visits().

end_date

Last day of the study period (e.g., Sys.Date() - lag).

tree_wide

Wide-format tree (path or data.frame) with columns Name1 (code without dot), Level2, and Level3.

study_days

Length of the study period in days.

lookback_days

Window used to define incident diagnoses.

ineligible

Regular expression of codes to exclude.

seed

Optional seed for the tie-break. The global RNG state is restored on exit.

Value

A data.table with columns code, date (yyyy/mm/dd), and n, with attributes end_date, study_days, and incident (the incident visit-code table, one row per date, key, dispo, code).

Details

  1. splits diagnosis codes and removes ineligible ones (ineligible);

  2. keeps codes present in the tree and looks up their level-3 parent;

  3. keeps only incident diagnoses: a level-3 group seen for the same patient within lookback_days is dropped, with special handling of admissions;

  4. restricts to the study_days ending on end_date;

  5. keeps the rarest code per level-3 group within a visit (random tie-break, see seed);

  6. aggregates counts by node (0- = not admitted, 1- = admitted) and day.

visits should cover study_days + lookback_days so every day in the study period has a full lookback.

ts_ineligible_pattern() returns the default exclusions: COVID-19, influenza, allergic rhinitis, asthma, anaphylaxis, most Z codes, neoplasms, and congenital malformations.

Examples

ex <- function(f) system.file("extdata", f, package = "treescanr")
counts <- read.csv(ex("toy_visits.csv")) |>
  ts_visits() |>
  ts_counts(end_date = "2026-06-30", tree_wide = ex("toy_tree_wide.txt"), seed = 1)
head(counts)
#>       code       date     n
#>     <char>     <char> <int>
#> 1: 0-A08.4 2026/06/22     4
#> 2: 0-R11.2 2026/06/22     4
#> 3: 0-A08.4 2026/06/21     3
#> 4: 0-R11.2 2026/06/21     3
#> 5: 0-A08.4 2026/06/25     4
#> 6: 0-R11.2 2026/06/25     4