Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save moritzpschwarz/69c46e5be82617a07b60ab859b2e3b9a to your computer and use it in GitHub Desktop.
Save moritzpschwarz/69c46e5be82617a07b60ab859b2e3b9a to your computer and use it in GitHub Desktop.
# Multiple differences function
# dplyr package needed
multiple_differences <- function(data = .,
execute_on_variables = vars(everything()),
difference_vector = c(1)){
intermediate <- tibble(data)
for(i in difference_vector){
data %>%
mutate_at(.vars = execute_on_variables, .funs = list(differenced = ~ . - lag(x=.,n = i))) %>%
select(ends_with("_differenced")) %>%
# Just renaming the variables to D.variable
rename_at(.vars = vars(everything()), .funs = ~paste0("D",i,".",gsub("_differenced","",.))) %>%
bind_cols(intermediate,.) -> intermediate
}
return(intermediate)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment