time_elapsed {timeplyr} | R Documentation |
Fast grouped time elapsed
Description
Calculate how much time has passed
on a rolling or cumulative basis.
Usage
time_elapsed(
x,
time_by = NULL,
g = NULL,
time_type = getOption("timeplyr.time_type", "auto"),
rolling = TRUE,
fill = NA,
na_skip = TRUE
)
Arguments
x |
Time variable. |
time_by |
Must be one of the three:
|
g |
Object to be used for grouping |
time_type |
Time type, either "auto", "duration" or "period".
With larger data, it is recommended to use |
rolling |
If |
fill |
When |
na_skip |
Should |
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_by = "3 days")
time_elapsed(x)
time_elapsed(x, rolling = FALSE, time_by = "day")
# Grouped example
set.seed(99)
# ~ 100k groups, 1m rows
x <- sample(time_seq_v2(20, today(), "day"), 10^6, TRUE)
g <- sample.int(10^5, 10^6, TRUE)
time_elapsed(x, time_by = "day", g = g)