time_elapsed: Fast grouped time elapsed

View source: R/time_elapsed.R

time_elapsedR Documentation

Fast grouped time elapsed

Description

Calculate how much time has passed on a rolling or cumulative basis.

Usage

time_elapsed(
  x,
  timespan = granularity(x),
  g = NULL,
  rolling = TRUE,
  fill = NA,
  na_skip = TRUE
)

Arguments

x

Time vector.
E.g. a Date, POSIXt, numeric or any time-based vector.

timespan

timespan.

g

Object to be used for grouping x, passed onto collapse::GRP().

rolling

If TRUE (the default) then lagged time differences are calculated on a rolling basis, essentially like diff().
If FALSE then time differences compared to the index (first) time are calculated.

fill

When rolling = TRUE, this is the value that fills the first elapsed time. The default is NA.

na_skip

Should NA values be skipped? Default is TRUE.

Details

time_elapsed() is quite efficient when there are many groups, especially if your data is sorted in order of those groups. In the case that g is supplied, it is most efficient when your data is sorted by g . When na_skip is TRUE and rolling is also TRUE, NA values are simply skipped and hence the time differences between the current value and the previous non-NA value are calculated. For example, c(3, 4, 6, NA, NA, 9) becomes c(NA, 1, 2, NA, NA, 3).
When na_skip is TRUE and rolling is FALSE, time differences between the current value and the first non-NA value of the series are calculated. For example, c(NA, NA, 3, 4, 6, NA, 8) becomes c(NA, NA, 0, 1, 3, NA, 5).

Value

A numeric vector the same length as x.

Examples

library(timeplyr)
library(dplyr)
library(lubridate)

x <- time_seq(today(), length.out = 25, time = "3 days")
time_elapsed(x)
time_elapsed(x, "days", rolling = FALSE)

# Grouped example
set.seed(99)
g <- sample.int(3, 25, TRUE)

time_elapsed(x, "days", g = g)


timeplyr documentation built on April 3, 2025, 6:15 p.m.