Last active
January 12, 2023 16:50
-
-
Save mpettis/c4a4e930e6e0d69b25249484378e9f5f to your computer and use it in GitHub Desktop.
Parsing lag functions from strings
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
# 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