Skip to contents

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

Value

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

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"

See also

Other Time-Based vector functions:

Underlying function:

Examples



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

# Forward (Plus Time)
"2021" %+time% "1 hour 34 seconds"
#> [1] "2021-01-01 01:00:34 UTC"
"2021" %+time% "3 months"
#> [1] "2021-04-01"
"2021" %+time% "1 year 3 months 6 days"
#> [1] "2022-04-07"

# Backward (Minus Time)
"2021" %-time% "1 hour 34 seconds"
#> [1] "2020-12-31 22:59:26 UTC"
"2021" %-time% "3 months"
#> [1] "2020-10-01"
"2021" %-time% "1 year 3 months 6 days"
#> [1] "2019-09-25"

# ---- INDEX SHIFTING ----

index_daily <- tk_make_timeseries("2016", "2016-02-01")
#> Using by: day

# 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"
#> Warning: Missing values created during time addition. This can happen if dates do not exist.
#>  [1] "2016-02-01" "2016-02-02" "2016-02-03" "2016-02-04" "2016-02-05"
#>  [6] "2016-02-06" "2016-02-07" "2016-02-08" "2016-02-09" "2016-02-10"
#> [11] "2016-02-11" "2016-02-12" "2016-02-13" "2016-02-14" "2016-02-15"
#> [16] "2016-02-16" "2016-02-17" "2016-02-18" "2016-02-19" "2016-02-20"
#> [21] "2016-02-21" "2016-02-22" "2016-02-23" "2016-02-24" "2016-02-25"
#> [26] "2016-02-26" "2016-02-27" "2016-02-28" "2016-02-29" NA          
#> [31] NA           "2016-03-01"

# Subtracting Time
index_daily %-time% "1 month"
#>  [1] "2015-12-01" "2015-12-02" "2015-12-03" "2015-12-04" "2015-12-05"
#>  [6] "2015-12-06" "2015-12-07" "2015-12-08" "2015-12-09" "2015-12-10"
#> [11] "2015-12-11" "2015-12-12" "2015-12-13" "2015-12-14" "2015-12-15"
#> [16] "2015-12-16" "2015-12-17" "2015-12-18" "2015-12-19" "2015-12-20"
#> [21] "2015-12-21" "2015-12-22" "2015-12-23" "2015-12-24" "2015-12-25"
#> [26] "2015-12-26" "2015-12-27" "2015-12-28" "2015-12-29" "2015-12-30"
#> [31] "2015-12-31" "2016-01-01"