Constructs 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
)

Arguments

data

A data frame containing longitudinal or event-level records.

id_col

Column identifying individuals (unquoted).

date_col

Column containing dates or date-time values (unquoted).

calendar_unit

Character. Calendar unit used to compute gaps between consecutive dates. One of "years", "months", or "days".

gap_threshold

Numeric. Maximum allowed gap (in complete calendar units) between consecutive dates before a new episode is started.

run_arrange

Logical. If TRUE, the data are sorted by id_col and date_col before episode construction.

collapse_episodes

Logical. If TRUE, returns one row per episode; otherwise returns the original data with episode identifiers.

Value

If collapse_episodes = FALSE, returns the input data with additional columns:

gap

Gap between consecutive dates (in complete calendar units)

new_episode

Logical indicator for the start of a new episode

episode_id

Episode identifier (unique within each individual)

If collapse_episodes = TRUE, returns one row per episode with:

episode_start

First date in the episode

episode_end

Last date in the episode

n_records

Number of records in the episode

Details

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.

Examples

if (FALSE) { # \dontrun{
df %>%
  episodes_by_gap(iain, paid_date, gap_threshold = 2,
                  calendar_unit = "months")
} # }

if (FALSE) { # \dontrun{
df %>%
  episodes_by_gap(iain, paid_date,
                  gap_threshold = 2,
                  calendar_unit = "months",
                  collapse_episodes = TRUE)
} # }