[R] Lexical scoping for step and add1 functions

S Ellison S.Ellison at LGCGroup.com
Wed Mar 9 12:05:28 CET 2016

> In a nutshell, formulas carry the environment in which they are defined along
> with the variable names, and your dfr was defined in the test.FN environment,
> but the formulas were defined in the global environment. I got this to work by
> defining the formula character strings in the global environment, and then
> converting those strings to formulas in the function. I don't think you can trick
> lm into referring to the global environment from within test.FN so that
> summaries refer to the X.des data frame instead of dfr (but someone could
> prove me wrong).

If you want a function to refer to something in the global environment, just refer to the global object in the function. If the object name isn't used in the function's scope, it is sought in the parent environment. So the original code works if 
test.FN <-  function(scope, k=2){
      temp.lm=lm(scope$lower, data=X.des)  ## X.des is sought in parent environment
      step(temp.lm, scope=scope$upper, k=k)

Admittedly, I'd not regard that kind of thing as a good idea; fragile and inflexible. But if you are clear about scope it does work.

Another way to proceed, somewhat more safely, is to wrap the whole thing in a function, passing X.des as dfr, then defining test.FN inside the outer function so that you know where it's going to get dfr from. Something along the lines of

test.step <- function(dfr, Y) {
	test.FN <-  function(scope, k=2){
      		temp.lm=lm(scope$lower, data=dfr)  ## X.des 
		 step(temp.lm, scope=as.formula(scope$upper), k=k)
	scope <- list( lower= as.formula('Y~1'), 
		upper=as.formula(paste('Y~', paste(names(dfr[1:20]), collapse="+"))) 

test.step(X.des, Y)

S Ellison

This email and any attachments are confidential. Any use...{{dropped:8}}

More information about the R-help mailing list