Last active
January 12, 2023 16:50
-
-
Save RJHKnight/22dbe5a3ef1d2701afd48370a1f1742c to your computer and use it in GitHub Desktop.
Example of creating multiple lags with dplyr
This file contains hidden or 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
library(dplyr) | |
d <- data_frame(x = seq_len(100)) | |
lag_fn <- list() | |
lags <- 1:10 | |
for(i in lags) { | |
fixer <- function(x, i) { | |
force(i) | |
return( | |
function(x) { | |
return(dplyr::lag(x, i)) | |
} | |
)} | |
lag_fn[[i]] <- fixer(x, i) | |
} | |
d %>% | |
mutate(across("x", lag_fn, .names = "lag_{.fn}")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment