I have the following code which throws an error (this is not a reprex, but I hope it is clear what is going on anyway since the question is more conceptual).
test_df <- test_reg %>%
mutate(
vars = map2(data, lm_obj, function(org_df, reg_obj) {
org_df %>%
mutate(
var_combinations = interaction(!!!syms(all.vars(reg_obj[["terms"]])[-1]), sep = "_", drop = TRUE)
)
})
)
Error in all.vars(reg_obj[["terms"]]) : object 'reg_obj' not found
despite the fact that reg_obj
is clearly defined in the function.
However, if I define a function with !!!
and call that, the code runs fine.
add_interaction_var <- function(df, vars) {
df %>%
mutate(
var_combinations = interaction(!!!vars, sep = "_", drop = TRUE)
)
}
test_df <- test_reg %>%
mutate(
vars = map2(data, lm_obj, function(org_df, reg_obj) {
xvars <- syms(all.vars(reg_obj[["terms"]])[-1])
add_interaction_var(org_df, xvars)
})
)
This seems a bit crazy, so I was wondering if there is a way to prevent !!!
from being evaluated until the code actually run or some other way to solve this that does not involve running a new function.
Edit: I should probably also mention that the function has to be defined outside, otherwise you end up with the same error.