Skip to content
Prev 359149 / 398502 Next

Lexical scoping for step and add1 functions

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).

################################

test.FN <- function( dfr, scope, k = 2 ) {
   scp <- list( lower = as.formula( scope$lower )
 	     , upper = as.formula( scope$upper )
 	     )
   temp.lm <- lm( scp$lower
                , data = dfr
                )
   step( temp.lm
       , scope = scp
       , k=k
       )
}

# Begin by setting the rng seed.
set.seed( 523 )

# Generate a design matrix and response.
X.des <- matrix( abs( rnorm( 50 * 20, sd = 4 ) ), nrow = 50 )
Y <- 20 + X.des[, 1:3 ] %*% matrix( c( 3, -4, 2 ), nrow = 3 ) + rnorm( 50 )
X.des <- cbind( as.data.frame( X.des ), Y )

# Create the lower and upper formula components of a list.
test.scope <- list( lower = "Y ~ 1"
 		  , upper = paste( "Y ~"
 				 , paste( names( X.des )[ 1:20 ]
 					, collapse = " + "
 					)
 				 , sep=""
 				 )
 		  )
# Run 'test.FN'.
test.FN( dfr = X.des
        , scope = test.scope
        )
On Mon, 7 Mar 2016, Louisell, Paul T PW wrote:

            
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                       Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k