Skip to content

Instantly share code, notes, and snippets.

@moritzpschwarz
Last active May 28, 2020 15:04
Show Gist options
  • Save moritzpschwarz/811e272945249afd0a00a18d260fcb0e to your computer and use it in GitHub Desktop.
Save moritzpschwarz/811e272945249afd0a00a18d260fcb0e to your computer and use it in GitHub Desktop.
Creates multiple lags using dplyr.
multiple_lags <- function(data = .,
execute_on_variables = vars(everything()),
lag_vector = c(1)){
intermediate <- tibble(data)
for(i in lag_vector){
data %>%
# Lags - note we don't include the dependent variable because we want to regulate this using the ARX object
mutate_at(.vars = execute_on_variables, .funs = list(lagged = ~lag(x=.,n = i))) %>%
ungroup() %>%
select(ends_with("_lagged")) %>%
# Just renaming the variables to Li.variable
rename_at(.vars = vars(everything()), .funs = ~paste0("L",i,".",gsub("_lagged","",.))) %>%
bind_cols(intermediate,.) -> intermediate
}
return(intermediate)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment