time_arithmetic: Add / Subtract (For Time Series)

time_arithmeticR Documentation

Add / Subtract (For Time Series)

Description

The easiest way to add / subtract a period to a time series date or date-time vector.

Usage

add_time(index, period)

subtract_time(index, period)

index %+time% period

index %-time% period

Arguments

index

A date or date-time vector. Can also accept a character representation.

period

A period to add. Accepts character strings like "5 seconds", "2 days", and complex strings like "1 month 4 days 34 minutes".

Details

A convenient wrapper for lubridate::period(). Adds and subtracts a period from a time-based index. Great for:

  • Finding a timestamp n-periods into the future or past

  • Shifting a time-based index. Note that NA values may be present where dates don't exist.

Period Specification

The period argument accepts complex strings like:

  • "1 month 4 days 43 minutes"

  • "second = 3, minute = 1, hour = 2, day = 13, week = 1"

Value

A date or datetime (POSIXct) vector the same length as index with the time values shifted +/- a period.

See Also

Other Time-Based vector functions:

  • between_time() - Range detection for date or date-time sequences.

Underlying function:

  • lubridate::period()

Examples



# ---- LOCATING A DATE N-PERIODS IN FUTURE / PAST ----

# Forward (Plus Time)
"2021" %+time% "1 hour 34 seconds"
"2021" %+time% "3 months"
"2021" %+time% "1 year 3 months 6 days"

# Backward (Minus Time)
"2021" %-time% "1 hour 34 seconds"
"2021" %-time% "3 months"
"2021" %-time% "1 year 3 months 6 days"

# ---- INDEX SHIFTING ----

index_daily <- tk_make_timeseries("2016", "2016-02-01")

# ADD TIME
# - Note `NA` values created where a daily dates aren't possible
#   (e.g. Feb 29 & 30, 2016 doesn't exist).
index_daily %+time% "1 month"

# Subtracting Time
index_daily %-time% "1 month"





timetk documentation built on Nov. 2, 2023, 6:18 p.m.