Based on @ErnestA's answer, you can change your function to make sure subs. present in the environment of the formula form. :
myfun <- function(form., data., subs., ...){ assign("subs.", subs., envir=environment(form.)) lm(form., data., subs., ...) }
ETA, in order to avoid form contamination, you can create a new environment this way:
myfun <- function(form., data., subs., ...){ environment(form.) <- new.env(parent=environment(form.)) assign("subs.", subs., envir=environment(form.)) lm(form., data., subs., ...) }
ETA, perhaps the easiest way to fix the lm problem is to set up a form. environment form. to myfun value:
myfun <- function(form., data., subs., ...){ environment(form.) <- environment() lm(form., data., subs., ...) } myfun(mpg ~ cyl + hp, mtcars, TRUE)
Addressing the problem expand.model.frame , subs. not found, although it is used in an environment in which ?expand.model.frame is used. Is this a bug in expand.model.frame? or at least a conflict with the documentation?
myfun <- function(form., data., subs., ...){ environment(form.) <- environment() fit <- lm(form., data., subs., ...) print(ls(environment(formula(fit)))) expand.model.frame(fit, ~drat ) } myfun(mpg ~ cyl + hp, mtcars, TRUE) ## [1] "data." "fit" "form." "subs." ## Error in eval(expr, envir, enclos) : object 'subs.' not found
Room subs. to the parent environment seems to work.
myfun <- function(form., data., subs., ...){ environment(form.) <- environment() fit <- lm(form., data., subs., ...) assign("subs.", subs., envir = parent.env(environment(formula(fit)))) expand.model.frame(fit, ~drat) } myfun(mpg ~ cyl + hp, mtcars, TRUE)
But this has problems with pollution of the parent environment, in this case R_GlobalEnv . I could not get it to work using anything other than R_GlobalEnv as the parent.