Skip to content

Instantly share code, notes, and snippets.

@GuiMarthe
Created April 11, 2018 16:36
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 GuiMarthe/543481da81e25e06d79b5090596a9301 to your computer and use it in GitHub Desktop.
Save GuiMarthe/543481da81e25e06d79b5090596a9301 to your computer and use it in GitHub Desktop.
Little function I created in R for adding all lagged values up to n of a variable to a df. Can be improved for handling more than one variable.
add_lagged <- function(df, var, n = 1) {
var <- enquo(var)
names <- map(1:n, ~ paste0(quo_name(var), '_lag_' ,.))
lagged_cols <- map2(1:n, names, ~ df %>% transmute(!!.y := lag(!!var, n = .x))) %>%
bind_cols()
df %>% bind_cols(lagged_cols)
}
@GuiMarthe
Copy link
Author

An idea for multiple variables approach.

add_lagged <- function(df, n = 1, ...) {
  vars <- quos(...)
  new_vars <- map(vars, ~ add_lagged_var(df = df, var = !!., n = n)) %>% bind_cols()
  new_vars
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment