compute_duration {healthdb} | R Documentation |
Compute duration between two dates
Description
This function is meant to be for data frame input only and used with dplyr::mutate()
to compute age or duration between two character or Date columns. If a vector of breaks is given, the output will be converted to factor with labels generated automatically.
Usage
compute_duration(
from,
to,
lower_brks = NULL,
unit = c("year", "day", "week", "month"),
trans = FALSE,
.transfn = lubridate::ymd,
verbose = getOption("healthdb.verbose"),
...
)
Arguments
from |
A character or Date vector for start dates. |
to |
A character or Date vector for end dates. |
lower_brks |
A numeric vector for lower breaks passing to the base |
unit |
A character string specifying the unit of the output. One of "year" (default), "day", "week", or "month". |
trans |
A logical for whether transform both |
.transfn |
A function for transforming the inputs. Default is |
verbose |
A logical for whether print summary of the out and warning for missing values. Default is fetching from options. Use |
... |
Additional arguments passing to |
Value
A numeric or factor vector of the duration.
Examples
# toy data
n <- 5
df <- data.frame(id = 1:n,
start_dt = sample(seq(as.Date("1970-01-01"), as.Date("2000-12-31"), by = 1), size = n),
end_dt = sample(seq(as.Date("2001-01-01"), as.Date("2023-12-31"), by = 1), size = n))
# get age group at a cut-off
df %>% dplyr::mutate(
age_grp = compute_duration(start_dt, "2023-01-01", lower_brks = c(0, 19, 25, 35, 45, 55))
)
# compute gaps between two dates in weeks
df %>% dplyr::mutate(
gap_wks = compute_duration(start_dt, end_dt, unit = "week")
)