I'm trying to build a wrapper for lm()
with dots ...
, with partly success though. It works well just for the first two formula=
and data=
arguments. But for every argument that follows, it doesn't seem to work and throws an error.
What I'm doing with the result of lm()
in the function is not the cause of the issue. It only seems to be related to using dots. So I was able to isolate the problem in this MWE:
lm_fun <- function(...) {
lm(...)
# <some other stuff>
}
lm_fun(formula=mpg ~ hp, data=mtcars)
## works fine
mtcars$w <- runif(nrow(mtcars)) ## adding weights
lm_fun(formula=mpg ~ hp, data=mtcars, weights=w)
# Error in eval(substitute(subset), data, env) :
# ..3 used in an incorrect context, no ... to look in
lm_fun(formula=mpg ~ hp, data=mtcars, subset=am == 1)
# Error in eval(substitute(subset), data, env) :
# ..3 used in an incorrect context, no ... to look in
lm_fun(formula=mpg ~ hp, data=mtcars, subset=am == 1, weights=w)
# Error in eval(extras, data, env) :
# ..4 used in an incorrect context, no ... to look in
It seems to be a different issue than that question because I provide the complete set of arguments in the function call and don't add something in the function.
Am I missing something? What's the reason for this behavior, and how can I get this to work properly?
Edit
@user63230 offered a nice workaround below. However, it won't work in an lapply
, which would be important for my needs.
lm_fun2 <- function(...) eval(substitute(lm(...)))
fo <- c(mpg ~ hp, mpg ~ am)
lapply(fo, lm_fun, data=mtcars)
# works
lapply(fo, lm_fun2, data=mtcars)
# Error in stats::model.frame(formula = X[[i]], data = mtcars, drop.unused.levels = TRUE) :
# object 'X' not found