[R] Lexical scoping for step and add1 functions

Jeff Newmiller jdnewmil at dcn.davis.ca.us
Wed Mar 9 17:46:06 CET 2016

So in both my solution and your second option, lm prints that it evaluated the regression in a function context (using dfr) which the user of the function might prefer to be unaware of (they know what X.des is). Your first solution  avoids that but hardcodes access to the global variable so if the user wants to use a different data frame then a different function has to be defined. I am OK with that, but thought that there might be a way to indirectly tell lm to use the global environment via the parameter dfr. 
Sent from my phone. Please excuse my brevity.

On March 9, 2016 3:05:28 AM PST, S Ellison <S.Ellison at LGCGroup.com> wrote:
>> 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
>> 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
>> 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
>> summaries refer to the X.des data frame instead of dfr (but someone
>> 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
>      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 
>		print(temp.lm)
>		 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.FN(scope=scope)
>test.step(X.des, Y)
>S Ellison
>This email and any attachments are confidential. Any
>R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>PLEASE do read the posting guide
>and provide commented, minimal, self-contained, reproducible code.

	[[alternative HTML version deleted]]

More information about the R-help mailing list