## Example 1: Regular time series
t <- 1:5
x <- c(10, 20, 30, 40, 50)
get_lag(x, t, k = 1)
# [1] NA 10 20 30 40
get_lag(x, t, k = -1)
# [1] 20 30 40 50 NA
## Example 2: Time series with a gap
t_gap <- c(1, 2, 4, 5)
x_gap <- c(10, 20, 40, 50)
get_lag(x_gap, t_gap, k = 1)
# [1] NA 10 NA 40
## Explanation:
## At t = 4, the requested time t-1 = 3 does not exist, so NA is returned.
## Example 3: Higher-order lags
get_lag(x_gap, t_gap, k = 2)
# [1] NA NA NA 20
Run the code above in your browser using DataLab