Created
April 11, 2018 16:36
-
-
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.
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
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An idea for multiple variables approach.