I’m using a choice modelling package (apollo) that has a function that needs to be specified as part of the model input parameters.
I want to dynamically specify a function such that in each iteration of a loop, part of the function is specified with a different subset of parameters. But there’s a couple of constraints. First, I can’t change the arguments the function accepts. Second, the function uses attach
.
I think there should be a hack but I’m not sure what it is! This is where I’ve got to so far:
for(var in c("Age", "Female") {
x <- parse(text = c("delta_a","gamma_Age_a*Age","gamma_Female_a*Female") %>%
str_subset(var, negate = TRUE) %>%
paste(collapse = "+"))
assign("dynamic_fun", function(args){
x
})
}
Here, in each iteration of the loop, the parsed expression should be as follows:
[1] expression(delta_a+gamma_Female_a*Female)
[2] expression(delta_a+gamma_Age_a*Age)
But it doesn’t work because x
in the function is just x
rather than an unevaluated expression. In the existing function, the expression is specified like so:
existing_fun <- function(args){
...
V=list()
V[["first"]] = delta_a + gamma_Age_a*Age + gamma_Female_a*Female
...
}
But I can’t see how it’s possible to recreate this structure while filtering the formula elements…