I am trying to generate multiple lags in my dataset to see if certain days correlate with each other. I am trying to use dplyr and setNames for this based on a post by Dr Simon Jackson on Github
My code is below and i am getting the following error based on looking for 6 lags
Error in setNames(paste("apply_lags(., ", lags, ")")) :
argument "nm" is missing, with no default
Does anyone know where i am going wrong?
# Here we create many lag functions using SetNames
apply_lags <- function(k, mydf) {
label = glue::glue("lag_{k}_day")
mydf %>%
mutate("lag_{{k}}_day" := lag(shps, n = k))
}
# Create a dataframe
x = seq(2,20,2) %>%
enframe()
# We set the number of lags we are interested in to 3
lags <- seq(1:3)
# ERROR HERE
lag_functions <- setNames(paste("apply_lags(., ", lags, ")"))
# Apply this to all the functions we have created
x %>%
mutate_at(vars(lags), funs_(lag_functions))
Why not use exactly Dr Jackson working code?
Your version introduces a mystery apply_lags function that we have no knowledge of....is there a reason you avoid dplyr::lag ?
I have managed to get it to work
The error basically needed me to name the results of each function call which was solved with nm = label in the call to lag_function
# Here we create many lag functions using SetNames
apply_lags <- function(mydf, k) {
lag(mydf, n = k)
}
# Create a dataframe
x = seq(2,20,2) %>%
enframe()
# We set the number of lags we are interested in to 4
lags <- seq(1:4)
label = glue::glue("lag_{lags}_day") %>%
as.character()
lag_functions <- setNames(paste("apply_lags(., ", lags, ")"), nm = label)
# Apply this to all the functions we have created
x %>%
mutate_at(vars(value), funs_(lag_functions))
[redacted : content above as john has already realised the things I wrote about before I hit post, so just leaving the rest]
Here I have made the code somewhat more generic, but I suppose further abstracting it has added an additional layer of complexity to understand, although it is perhaps more explicit ?
library(tidyverse)
library(glue)
d <- data_frame(x = seq_len(100))
d
gen_fun_maker <- function(func_as_string,
to_do,
gluestr)
{
to_do_vec <- seq_len(to_do)
gen_names <- glue('glue("{gluestr}")') %>%
str2expression %>% eval
setNames(glue("{func_as_string}(., {to_do_vec})"),
gen_names)
}
#using the above
myfuns <- gen_fun_maker("dplyr::lag",5,"lag_{to_do_vec}_day")
d %>% mutate_at(vars(x), funs_(myfuns))
myfuns_2 <- gen_fun_maker("dplyr::lead",5,"lead_{to_do_vec}_day")
d %>% mutate_at(vars(x), funs_(myfuns_2))