Skip to content

Instantly share code, notes, and snippets.

@christophergandrud
Created March 28, 2020 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christophergandrud/c69f9b4d8e834a235ac0f720a162d871 to your computer and use it in GitHub Desktop.
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")
# 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