lag_vec() applies a Lag Transformation.
Details
Benefits:
This function is NA padded by default so it works well with dplyr::mutate() operations.
The function allows both lags and leads (negative lags).
Lag Calculation
A lag is an offset of lag periods. NA values are returned for the number of lag periods.
Lead Calculation
A negative lag is considered a lead. The only difference between lead_vec() and lag_vec() is
that the lead_vec() function contains a starting negative value.
See also
Modeling and Advanced Lagging:
- recipes::step_lag()- Recipe for adding lags in- tidymodelsmodeling
- tk_augment_lags()- Add many lags group-wise to a data.frame (tibble)
Vectorized Transformations:
- Box Cox Transformation: - box_cox_vec()
- Lag Transformation: - lag_vec()
- Differencing Transformation: - diff_vec()
- Rolling Window Transformation: - slidify_vec()
- Loess Smoothing Transformation: - smooth_vec()
- Fourier Series: - fourier_vec()
- Missing Value Imputation for Time Series: - ts_impute_vec(),- ts_clean_vec()
Examples
library(dplyr)
# --- VECTOR ----
# Lag
1:10 %>% lag_vec(lag = 1)
#>  [1] NA  1  2  3  4  5  6  7  8  9
# Lead
1:10 %>% lag_vec(lag = -1)
#>  [1]  2  3  4  5  6  7  8  9 10 NA
# --- MUTATE ----
m4_daily %>%
    group_by(id) %>%
    mutate(lag_1 = lag_vec(value, lag = 1))
#> # A tibble: 9,743 × 4
#> # Groups:   id [4]
#>    id    date       value lag_1
#>    <fct> <date>     <dbl> <dbl>
#>  1 D10   2014-07-03 2076.   NA 
#>  2 D10   2014-07-04 2073. 2076.
#>  3 D10   2014-07-05 2049. 2073.
#>  4 D10   2014-07-06 2049. 2049.
#>  5 D10   2014-07-07 2006. 2049.
#>  6 D10   2014-07-08 2018. 2006.
#>  7 D10   2014-07-09 2019. 2018.
#>  8 D10   2014-07-10 2007. 2019.
#>  9 D10   2014-07-11 2010  2007.
#> 10 D10   2014-07-12 2002. 2010 
#> # ℹ 9,733 more rows
