Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
``` 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
library(rlang)
#>
#> Attaching package: 'rlang'
#> The following objects are masked from 'package:purrr':
#>
#> %@%, %||%, as_function, flatten, flatten_chr, flatten_dbl,
#> flatten_int, flatten_lgl, invoke, list_along, modify, prepend,
#> rep_along, splice
lags <- function(var, n=10){
var <- enquo(var)
indices <- seq_len(n)
map( indices, ~quo(lag(!!var, !!.x)) ) %>%
set_names(sprintf("lag_%s_%02d", quo_text(var), indices))
}
d <- data_frame(x = seq_len(100))
mutate( d, !!!lags(x, 10) )
#> # A tibble: 100 x 11
#> x lag_x_01 lag_x_02 lag_x_03 lag_x_04 lag_x_05 lag_x_06 lag_x_07
#> <int> <int> <int> <int> <int> <int> <int> <int>
#> 1 1 NA NA NA NA NA NA NA
#> 2 2 1 NA NA NA NA NA NA
#> 3 3 2 1 NA NA NA NA NA
#> 4 4 3 2 1 NA NA NA NA
#> 5 5 4 3 2 1 NA NA NA
#> 6 6 5 4 3 2 1 NA NA
#> 7 7 6 5 4 3 2 1 NA
#> 8 8 7 6 5 4 3 2 1
#> 9 9 8 7 6 5 4 3 2
#> 10 10 9 8 7 6 5 4 3
#> # ... with 90 more rows, and 3 more variables: lag_x_08 <int>,
#> # lag_x_09 <int>, lag_x_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.