Skip to content

Instantly share code, notes, and snippets.

@drsimonj drsimonj/multiple_lags.R
Last active Jul 10, 2019

Embed
What would you like to do?
Example of creating multiple lags with dplyr
library(dplyr)
d <- data_frame(x = seq_len(100))
d
#> # A tibble: 100 x 1
#> x
#> <int>
#> 1 1
#> 2 2
#> 3 3
#> 4 4
#> 5 5
#> 6 6
#> 7 7
#> 8 8
#> 9 9
#> 10 10
#> # ... with 90 more rows
lags <- seq(10)
lag_names <- paste("lag", formatC(lags, width = nchar(max(lags)), flag = "0"),
sep = "_")
lag_functions <- setNames(paste("dplyr::lag(., ", lags, ")"), lag_names)
d %>% mutate_at(vars(x), funs_(lag_functions))
#> # 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 variables: 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.