Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
multiple lags
``` r
library(purrr)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
jetlag <- function(data, x, n=10){
x <- enquo(x)
indices <- seq_len(n)
quosures <- map( indices, ~quo(lag(!!x, !!.x)) ) %>%
set_names(sprintf("lag_%02d", indices))
mutate( data, !!!quosures )
}
d <- data_frame(x = seq_len(100))
jetlag(d, x, n=10)
#> # A tibble: 100 x 11
#> x lag_01 lag_02 lag_03 lag_04 lag_05 lag_06 lag_07 lag_08 lag_09
#> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
#> 1 1 NA NA NA NA NA NA NA NA NA
#> 2 2 1 NA NA NA NA NA NA NA NA
#> 3 3 2 1 NA NA NA NA NA NA NA
#> 4 4 3 2 1 NA NA NA NA NA NA
#> 5 5 4 3 2 1 NA NA NA NA NA
#> 6 6 5 4 3 2 1 NA NA NA NA
#> 7 7 6 5 4 3 2 1 NA NA NA
#> 8 8 7 6 5 4 3 2 1 NA NA
#> 9 9 8 7 6 5 4 3 2 1 NA
#> 10 10 9 8 7 6 5 4 3 2 1
#> # ... with 90 more rows, and 1 more variable: lag_10 <int>
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.