Skip to content

Instantly share code, notes, and snippets.

@denrou
Last active May 2, 2018 14:47
Show Gist options
  • Select an option

  • Save denrou/09cd976cd8e3e1738815a327ac05f85f to your computer and use it in GitHub Desktop.

Select an option

Save denrou/09cd976cd8e3e1738815a327ac05f85f to your computer and use it in GitHub Desktop.
Add lags to multiple column in a dataframe
shift <- function(x, ..., shifts = 1, suffix = "lag") {
vars <- unname(tidyselect::vars_select(names(x), !!!rlang::quos(...)))
combinations <- expand.grid(var = vars, shift = shifts, stringsAsFactors = FALSE)
shift_cols <- purrr::pmap_dfc(combinations, function(var, shift) {
new_var <- glue::glue("lag_{var}_{shift}")
tibble::tibble(!!new_var := dplyr::lag(x[[var]], shift))
})
dplyr::bind_cols(x, shift_cols)
}
# Example
shift(mtcars, mpg:hp, shifts = c(1, 2, 3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment