Skip to content

Instantly share code, notes, and snippets.

@RJHKnight
Last active January 12, 2023 16:50
Show Gist options
  • Save RJHKnight/22dbe5a3ef1d2701afd48370a1f1742c to your computer and use it in GitHub Desktop.
Save RJHKnight/22dbe5a3ef1d2701afd48370a1f1742c to your computer and use it in GitHub Desktop.
Example of creating multiple lags with dplyr
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