Skip to content

Instantly share code, notes, and snippets.

@mpettis
Last active January 12, 2023 16:50
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mpettis/c4a4e930e6e0d69b25249484378e9f5f to your computer and use it in GitHub Desktop.
Save mpettis/c4a4e930e6e0d69b25249484378e9f5f to your computer and use it in GitHub Desktop.
Parsing lag functions from strings
# See: https://gist.github.com/drsimonj/2038ff9f9c67063f384f10fac95de566
# See: https://adv-r.hadley.nz/meta-big-picture.html
# See: https://dplyr.tidyverse.org/reference/tidyeval.html
# See: https://dplyr.tidyverse.org/articles/programming.html
library(dplyr)
# Set up lags
lags <- c(1:30)
# Name the columns that will contain the lags, with appropriate index
lag_names_RealPower <- glue('lag_{str_pad(lags, nchar(max(lags)), pad = "0")}_RealPower')
# Create list of lag functions, as eval-ed/parse-d labmda functions
lag_functions_RealPower <-
map(lags, ~ eval(parse(text=glue("~ dplyr::lag(.x, {.x})")))) %>%
set_names(lag_names_RealPower)
# Compute the lag
tibble(RealPower=1:99) %>%
mutate_at(vars(RealPower), .funs=lag_functions_RealPower)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment