R/episodes_by_gap.R
episodes_by_gap.RdConstructs episodes for each individual based on gaps between consecutive date records. A new episode is started when the gap between dates exceeds a specified threshold, measured in complete calendar units.
episodes_by_gap(
data,
id_col,
date_col,
calendar_unit = c("years", "months", "days"),
gap_threshold = 2,
run_arrange = TRUE,
collapse_episodes = FALSE
)A data frame containing longitudinal or event-level records.
Column identifying individuals (unquoted).
Column containing dates or date-time values (unquoted).
Character. Calendar unit used to compute gaps between
consecutive dates. One of "years", "months", or "days".
Numeric. Maximum allowed gap (in complete calendar units) between consecutive dates before a new episode is started.
Logical. If TRUE, the data are sorted by
id_col and date_col before episode construction.
Logical. If TRUE, returns one row per episode;
otherwise returns the original data with episode identifiers.
If collapse_episodes = FALSE, returns the input data with additional
columns:
Gap between consecutive dates (in complete calendar units)
Logical indicator for the start of a new episode
Episode identifier (unique within each individual)
If collapse_episodes = TRUE, returns one row per episode with:
First date in the episode
Last date in the episode
Number of records in the episode
Episodes are defined as contiguous sequences of records where the gap between
consecutive dates does not exceed gap_threshold.
Gaps are calculated as the number of complete calendar units between dates
using count_calendar_units(). The first record for each individual
always starts a new episode.
Records must be sortable by id_col and date_col, and all records
for each individual must be contiguous after sorting.