Created
March 28, 2020 17:05
-
-
Save christophergandrud/c69f9b4d8e834a235ac0f720a162d871 to your computer and use it in GitHub Desktop.
Create lag and difference variables for a grouped time series (grouped by a variable called "country")
This file contains 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
# Create lag and difference variables for a grouped time series (grouped by a variable called "country") | |
# | |
# @param df a data frame containing the variable to lag and lead | |
# @param x a column name in `df` to lag and lead | |
# @param lag integer period to lag and difference | |
# | |
# @importFrom tsibble difference | |
# @importFrom dplyr %>% lag | |
create_lags_diffs <- function(df, x, lag = 1) { | |
x_var <- enquo(x) | |
new_var_diff <- str_c(x_var, "_", "diff_", lag)[[2]] | |
new_var_lag <- str_c(x_var, "_", "lag_", lag)[[2]] | |
tmp <- df %>% group_by(country) %>% | |
mutate(!! new_var_diff := tsibble::difference(!! x_var, lag = lag)) %>% | |
mutate(!! new_var_lag := dplyr::lag(!! x_var, n = lag)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment