Shift time stamps in ts-boxable time series, either by a number of periods or by a fixed amount of time.

ts_lag(x, by = 1)

Arguments

x

ts-boxable time series, an object of class ts, xts, zoo, data.frame, data.table, tbl, tbl_ts, tbl_time, tis, irts or timeSeries.

by

integer or character, either the number of shifting periods (integer), or an absolute amount of time (character). See details.

Value

a ts-boxable time series, with the same class as the input. If time stamp shifting causes the object to be irregular, a data frame is returned.

Details

The lag order, by, is defined the opposite way as in R base. Thus, -1 is a lead and +1 a lag.

If by is integer, the time stamp is shifted by the number of periods. This requires the series to be regular.

If by is character, the time stamp is shifted by a specific amount of time. This can be one of one of "sec", "min", "hour", "day", "week", "month", "quarter" or "year", optionally preceded by a (positive or negative) integer and a space, or followed by plural "s". This is passed to base::seq.Date(). This does not require the series to be regular.

Examples

ts_plot(AirPassengers, ts_lag(AirPassengers), title = "Illustrating the need for glasses")
head(ts_lag(fdeaths, "1 month"))
#> Feb Mar Apr May Jun Jul #> 1974 901 689 827 677 522 406
head(ts_lag(fdeaths, "1 year"))
#> Jan Feb Mar Apr May Jun #> 1975 901 689 827 677 522 406
head(ts_lag(ts_df(fdeaths), "2 day"))
#> time value #> 1 1974-01-03 901 #> 2 1974-02-03 689 #> 3 1974-03-03 827 #> 4 1974-04-03 677 #> 5 1974-05-03 522 #> 6 1974-06-03 406
head(ts_lag(ts_df(fdeaths), "2 min"))
#> time value #> 1 1974-01-01 01:02:00 901 #> 2 1974-02-01 01:02:00 689 #> 3 1974-03-01 01:02:00 827 #> 4 1974-04-01 01:02:00 677 #> 5 1974-05-01 01:02:00 522 #> 6 1974-06-01 01:02:00 406
head(ts_lag(ts_df(fdeaths), "-1 day"))
#> time value #> 1 1973-12-31 901 #> 2 1974-01-31 689 #> 3 1974-02-28 827 #> 4 1974-03-31 677 #> 5 1974-04-30 522 #> 6 1974-05-31 406