Skip to contents

Study data often record calendar dates (enrollment, last contact, death) rather than follow-up times. duration() gives the time from start to end in the chosen unit, so it can be the time of a response, such as Surv(duration(enroll, exit, unit = "years"), died) ~ 1.

Usage

duration(start, end, unit = "days")

Arguments

start

The origin of each time, such as the enrollment date. A Date, a date-time (POSIXct or POSIXlt), or character dates.

end

The end of each time, such as the date of the event or of last contact, of the same length as start (or length one).

unit

The unit of the result: "days" (the default), "weeks", "months", "years", "hours", "minutes", or "seconds".

Value

A numeric vector of elapsed times, missing where either date is missing.

Details

Dates are taken as midnight UTC, and character values are read as ISO 8601 dates or date-times (such as "2021-03-01" or "2021-03-01 14:30:00") in UTC. Months and years have their average lengths, 30.4375 and 365.25 days.

Errors

An end earlier than its start is an error, since a negative time can't be a survival time. Numbers are an error too. If they're already elapsed times, use them directly.

See also

Surv() and event_time(), which take the result as their time.

Examples

study <- data.frame(
  enroll = as.Date(c("2021-03-01", "2021-03-15", "2021-04-01")),
  exit = as.Date(c("2022-01-10", "2021-09-22", "2023-01-01")),
  died = c(TRUE, FALSE, TRUE)
)
duration(study$enroll, study$exit, unit = "years")
#> [1] 0.8624230 0.5229295 1.7522245

# In a formula, with the columns found in `data`
kaplan_meier(Surv(duration(enroll, exit, unit = "years"), died) ~ 1, data = study)
#> <kaplan_meier> Surv(duration(enroll, exit, unit = "years"), died) ~ 1
#> 
#>     n events   median 0.95 LCL 0.95 UCL
#> all 3      2 0.862423 0.862423       NA