Compute duration between two dates, e.g., duration of an adverse event, relative day, age, ...
Usage
compute_duration(
start_date,
end_date,
in_unit = "days",
out_unit = "days",
floor_in = TRUE,
add_one = TRUE,
trunc_out = FALSE
)
Arguments
- start_date
The start date
A date or date-time object is expected.
Refer to
derive_vars_dt()
to impute and derive a date from a date character vector to a date object.Refer to
convert_dtc_to_dt()
to obtain a vector of imputed dates.- end_date
The end date
A date or date-time object is expected.
Refer to
derive_vars_dt()
to impute and derive a date from a date character vector to a date object.Refer to
convert_dtc_to_dt()
to obtain a vector of imputed dates.- in_unit
Input unit
See floor_in and add_one parameter for details.
Default: 'days'
Permitted Values: 'years', 'months', 'days', 'hours', 'minutes', 'min', 'seconds', 'sec'
- out_unit
Output unit
The duration is derived in the specified unit
Default: 'days'
Permitted Values: 'years', 'months', 'weeks', 'days', 'hours', 'minutes', 'min', 'seconds', 'sec'
- floor_in
Round down input dates?
The input dates are round down with respect to the input unit, e.g., if the input unit is 'days', the time of the input dates is ignored.
Default: `TRUE``
Permitted Values:
TRUE
,FALSE
- add_one
Add one input unit?
If the duration is non-negative, one input unit is added. i.e., the duration can not be zero.
Default:
TRUE
Permitted Values:
TRUE
,FALSE
- trunc_out
Return integer part
The fractional part of the duration (in output unit) is removed, i.e., the integer part is returned.
Default:
FALSE
Permitted Values:
TRUE
,FALSE
Details
The output is a numeric vector providing the duration as time from start to end date in the specified unit. If the end date is before the start date, the duration is negative.
See also
Date/Time Computation Functions that returns a vector:
compute_dtf()
,
compute_tmf()
,
convert_date_to_dtm()
,
convert_dtc_to_dtm()
,
convert_dtc_to_dt()
,
impute_dtc_dtm()
,
impute_dtc_dt()
Examples
library(lubridate)
#>
#> Attaching package: ‘lubridate’
#> The following objects are masked from ‘package:base’:
#>
#> date, intersect, setdiff, union
# Derive duration in days (integer), i.e., relative day
compute_duration(
start_date = ymd_hms("2020-12-06T15:00:00"),
end_date = ymd_hms("2020-12-24T08:15:00")
)
#> [1] 19
# Derive duration in days (float)
compute_duration(
start_date = ymd_hms("2020-12-06T15:00:00"),
end_date = ymd_hms("2020-12-24T08:15:00"),
floor_in = FALSE,
add_one = FALSE
)
#> [1] 17.71875
# Derive age in years
compute_duration(
start_date = ymd("1984-09-06"),
end_date = ymd("2020-02-24"),
trunc_out = TRUE,
out_unit = "years",
add_one = FALSE
)
#> [1] 35
# Derive duration in hours
compute_duration(
start_date = ymd_hms("2020-12-06T9:00:00"),
end_date = ymd_hms("2020-12-06T13:30:00"),
out_unit = "hours",
floor_in = FALSE,
add_one = FALSE,
)
#> [1] 4.5