Learn R Programming

utile.tools (version 0.2.7)

calc_duration: Calculate durations of time

Description

Calculates the duration of time between two provided date objects. Supports vectorized data (i.e. dplyr::mutate()).

Usage

calc_duration(x, y, units = NULL)

Value

If 'units' specified, returns numeric. If 'units' unspecified, returns an object of class 'Duration'.

Arguments

x

A date or datetime. The start date(s)/timestamp(s).

y

A date or datetime. The end date(s)/timestamp(s).

units

A character. Units of the returned duration (i.e. 'seconds', 'days', 'years').

Examples

Run this code
library(lubridate)
library(purrr)

# Dates -> duration in years
calc_duration(
  x = mdy(map_chr(sample(1:9, 5), ~ paste0('01/01/199', .x))),
  y = mdy(map_chr(sample(1:9, 5), ~ paste0('01/01/200', .x))),
  units = 'years'
)

# datetimes -> durations
calc_duration(
  x = mdy_hm(map_chr(sample(1:9, 5), ~ paste0('01/01/199', .x, ' 1', .x, ':00'))),
  y = mdy_hm(map_chr(sample(1:9, 5), ~ paste0('01/01/200', .x, ' 0', .x, ':00')))
)

# Mixed date classes -> durations
calc_duration(
  x = mdy(map_chr(sample(1:9, 5), ~ paste0('01/01/199', .x))),
  y = mdy_hm(map_chr(sample(1:9, 5), ~ paste0('01/01/200', .x, ' 0', .x, ':00')))
)

Run the code above in your browser using DataLab