I am working on a custom function that includes a call to lm()
, but for some reason the function fails. I can't make any sense of why it fails.
Consider this example simplified to the bare-bones:
myfun <- function(form., data., subs., ...){
lm(form., data., subs., ...)
}
This will end up in an error:
myfun(mpg ~ cyl + hp, mtcars, TRUE)
## Error in eval(expr, envir, enclos) : object 'subs.' not found
However using lm()
directly will work just fine:
lm(mpg ~ cyl + hp, mtcars, TRUE)
##
## Call:
## lm(formula = mpg ~ cyl + hp, data = mtcars, subset = TRUE)
##
## Coefficients:
## (Intercept) cyl hp
## 36.90833 -2.26469 -0.01912
I tried debugging, but still can't get to the bottom of the problem. Why does the custom function fail? Clearly subs.
has been supplied to the function...
Edit:
While most of the solutions suggested below help in this simple case, the function will still fail if I add a simple twist. For instance expand.model.frame()
relies on the formula's environment, but fails if I use the normal evaluation solution:
myfun <- function(form., data., subs., ...){
fit <- lm(form., data.[ subs., ], ...)
expand.model.frame(fit, ~ drat)
}
myfun(mpg ~ cyl + hp, mtcars, TRUE)
## Error in eval(expr, envir, enclos) : object 'data.' not found
This is obviously related to the original issue, but I can't figure how. Is the environment of the model formula somehow corrupted?