I am trying to call an aggregate function in R "on the fly", by being able to create and pass strings as arguments to the aggregate() function. I have been able to do that for almost all parameters except for the subset parameter.
for example: I want to run the following piece of code: gg1 <- aggregate(metric ~ grouping_var1 + grouping_var2, data=data.set, FUN= "mean", subset=exclude.filter==0)
I can create string variables that I can pass to aggregate function:
current.metric <- "metric"
rhs <- c("grouping_var1","grouping_var2")
func1 <- "mean"
filter <- "exclude.filter == 0"
gg1 <- aggregate(as.formula(paste(current.metric, paste(rhs, collapse="+"), sep="~")), data=data.set, FUN= "mean", subset=exclude.filter==0)
The above piece of code works as long as subset=exclude.filter==0 is provided as the argument. I am unable to figure out how I can use something like subset = filter. I have tried expression(filter), substitute(filter), as.formula(filter) as the arguments in the subset parameter, but I am not parsing the expression in the right environment I think.
An alternative is to construct the whole string and pass it to eval(). However, I am wondering if it can be done within the aggregate function itself. Can somebody point me in the right direction to solve this please?
model.frame()
evaluated in theparent.frame()
going on here, which is what uses thesubset
argument. I think it's going to be hard to hack that. - Thomas