time_is_regular: Is time a regular sequence? (Experimental)

View source: R/time_is_regular.R

time_is_regularR Documentation

Is time a regular sequence? (Experimental)

Description

This function is a fast way to check if a time vector is a regular sequence, possibly for many groups. Regular in this context means that the lagged time differences are a whole multiple of the specified time unit.
This means x can be a regular sequence with or without gaps in time.

Usage

time_is_regular(
  x,
  time_by = NULL,
  g = NULL,
  use.g.names = TRUE,
  na.rm = TRUE,
  time_type = getOption("timeplyr.time_type", "auto"),
  allow_gaps = TRUE,
  allow_dups = TRUE
)

Arguments

x

A vector. Can be a Date, POSIXt, numeric, integer, yearmon, or yearqtr.

time_by

Time unit.
Must be one of the three:

  • 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.

g

Grouping object passed directly to collapse::GRP(). This can for example be a vector or data frame.
Note that when g is supplied the output is a logical with length matching the number of unique groups.

use.g.names

Should the result include group names? Default is TRUE.

na.rm

Should NA values be removed before calculation? Default is TRUE.

time_type

If "auto", periods are used for the time expansion when days, weeks, months or years are specified, and durations are used otherwise. If durations are used the output is always of class POSIXt.

allow_gaps

Should gaps be allowed? Default is TRUE.

allow_dups

Should duplicates be allowed? Default is TRUE.

Value

A logical vector the same length as the number of supplied groups.

Examples

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

x <- 1:5
y <- c(1, 1, 2, 3, 5)

time_is_regular(x)
time_is_regular(y)

increment <- 1

# No duplicates allowed
time_is_regular(x, increment, allow_dups = FALSE)
time_is_regular(y, increment, allow_dups = FALSE)

# No gaps allowed
time_is_regular(x, increment, allow_gaps = FALSE)
time_is_regular(y, increment, allow_gaps = FALSE)

# Grouped
eu_stock <- ts_as_tibble(EuStockMarkets)
eu_stock <- eu_stock %>%
  mutate(date = as_date(
    date_decimal(time)
  ))

time_is_regular(eu_stock$date, g = eu_stock$group,
                time_by = 1)
# This makes sense as no trading occurs on weekends and holidays
time_is_regular(eu_stock$date, g = eu_stock$group,
                time_by = 1,
                allow_gaps = FALSE)


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