time_diff: Time differences by any time unit

View source: R/time_diff.R

time_diffR Documentation

Time differences by any time unit

Description

The time difference between 2 date or date-time vectors.

Usage

time_diff(
  x,
  y,
  time_by = 1L,
  time_type = getOption("timeplyr.time_type", "auto")
)

Arguments

x

Start date or datetime.

y

End date or datetime.

time_by

Must be one of the three (Default is 1):

  • string, specifying either the unit or the number and unit, e.g time_by = "days" or time_by = "2 weeks"

  • named list of length one, the unit being the name, and the number the value of the list, e.g. list("days" = 7). For the vectorized time functions, you can supply multiple values, e.g. list("days" = 1:10).

  • Numeric vector. If time_by is a numeric vector and x is not a date/datetime, then arithmetic is used, e.g time_by = 1.

time_type

Time difference type: "auto", "duration" or "period".

Details

When time_by is a numeric vector, e.g time_by = 1 then base arithmetic using base::`-` is used, otherwise 'lubridate' style durations and periods are used.
Some more exotic time units such as quarters, fortnights, etcetera can be specified. See .time_units for more choices.

Value

A numeric vector recycled to the length of max(length(x), length(y)).

Examples

library(timeplyr)
library(lubridate)

time_diff(today(), today() + days(10),
          time_by = "days")
time_diff(today(), today() + days((0:3) * 7),
          time_by = weeks(1))
time_diff(today(), today() + days(100),
          time_by = list("days" = 1:100))
time_diff(1, 1 + 0:100, time_by = 3)

library(nycflights13)
library(bench)

# Period differences are much faster
# check = FALSE because the results are fractionally different.
# lubridate:::adjust_estimate likely has a typo in the first while loop

mark(timeplyr = time_diff(flights$time_hour, today(), "weeks", time_type = "period"),
     lubridate = interval(flights$time_hour, today()) / weeks(1),
     check = FALSE)



timeplyr documentation built on Sept. 12, 2024, 7:37 a.m.