Created
February 3, 2018 15:09
-
-
Save romainfrancois/6a2203faacfa8ae849f29f83b56e01da to your computer and use it in GitHub Desktop.
multiple lags
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
``` 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