time_seq_id: Generate a unique identifier for a regular time sequence with...

View source: R/time_seq_id.R

time_seq_idR Documentation

Generate a unique identifier for a regular time sequence with gaps

Description

A unique identifier is created every time a specified amount of time has passed, or in the case of regular sequences, when there is a gap in time.

Usage

time_seq_id(
  x,
  timespan = granularity(x),
  threshold = 1,
  g = NULL,
  na_skip = TRUE,
  rolling = TRUE,
  switch_on_boundary = FALSE
)

Arguments

x

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

timespan

timespan.

threshold

Threshold such that when the time elapsed exceeds this, the sequence ID is incremented by 1. For example, if timespan = "days" and threshold = 2, then when 2 days have passed, a new ID is created. Furthermore, threshold generally need not be supplied as
timespan = "3 days" & threshold = 1
is identical to
timespan = "days" & threshold = 3.

g

Object used for grouping x. This can for example be a vector or data frame. g is passed directly to collapse::GRP().

na_skip

Should NA values be skipped? Default is TRUE.

rolling

When this is FALSE, a new ID is created every time a cumulative amount of time has passed. Once that amount of time has passed, a new ID is created, the clock "resets" and we start counting from that point.

switch_on_boundary

When an exact amount of time (specified in time_by) has passed, should there an increment in ID? The default is FALSE. For example, if time_by = "days" and switch_on_boundary = FALSE, > 1 day must have passed, otherwise >= 1 day must have passed.

Details

time_seq_id() Assumes x is regular and in ascending or descending order. To check this condition formally, use time_is_regular().

Value

An integer vector of length(x).

Examples

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

# Weekly sequence, with 2 gaps in between
x <- time_seq(today(), length.out = 10, time = "week")
x <- x[-c(3, 7)]
# A new ID when more than a week has passed since the last time point
time_seq_id(x)
# A new ID when >= 2 weeks has passed since the last time point
time_seq_id(x, threshold = 2, switch_on_boundary = TRUE)
# A new ID when at least 4 cumulative weeks have passed
time_seq_id(x, timespan = "4 weeks",
            switch_on_boundary = TRUE, rolling = FALSE)
# A new ID when more than 4 cumulative weeks have passed
time_seq_id(x, timespan = "4 weeks",
            switch_on_boundary = FALSE, rolling = FALSE)


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