Skip to content

Instantly share code, notes, and snippets.

@alexhallam
Last active June 30, 2018 22:44
Show Gist options
  • Save alexhallam/08953aa0757ba6c0aeebdf8ed57403d9 to your computer and use it in GitHub Desktop.
Save alexhallam/08953aa0757ba6c0aeebdf8ed57403d9 to your computer and use it in GitHub Desktop.
Make many lag columns
#https://purrple.cat/blog/2018/03/02/multiple-lags-with-tidy-evaluation/
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 = 1:10, y = letters[1:10])
d %>%
mutate( !!!lags(x, 3), !!!lags(y,3) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment