[R] scoping problem when calling step inside a function

Scott Gilpin sgilpin at gmail.com
Mon Oct 11 21:10:46 CEST 2004


Hi everyone -

I'm trying to do a forward stepwise regression (I've tried both step
and stepAIC) inside of a function.  I can do it outside the function
with no problems (first example in code below).  I can also do a
backward stepwise regression inside a function (second example), but
forward stepwise regression ( third example ) fails with the error:

"Error in model.frame.default(formula = y ~ X1 + X2 + X3 + X4 + X5 + X6 +  : 
        Object "lsdata" not found"

I looked through the help archives and found several threads where the
problem appears to be the environment which is used in eval.  When I
looked at the source for step, it appears OK, as it's using
eval.parent.  I also read section 7.12 of the FAQ about enclosing and
parent environments, but this leads me to belive that step is doing
the right thing.  I've tried this code with R version 1.9.0, 1.9.1 and
2.0.0 on Windows XP.  The error message is slightly different for
2.0.0, but it seems to be the same problem.

Thanks in advance,
Scott Gilpin


## Example code
rm(list=ls())

## Forward stepwise regression - works fine
set.seed(2863)
x<-matrix(runif(1000),ncol=10)
colnames(x)<-1:10
beta<-matrix(c(1,2,3,4,5,0,0,0,0,0),ncol=1)
y<-drop(x %*% beta + rnorm(100))

lsdata<-data.frame(cbind(x=x,y=y))

xnam <- names(lsdata)[names(lsdata) != "y"]
(fmla <- as.formula(paste("y ~ ", paste(xnam, collapse= "+"))))
fit<-lm(y ~ 1,data=lsdata)
step.fit<-step(fit,scope = fmla, direction="forward",data=lsdata)

## start from scratch
rm(list=ls())
set.seed(2863)
x<-matrix(runif(1000),ncol=10)
colnames(x)<-1:10
beta<-matrix(c(1,2,3,4,5,0,0,0,0,0),ncol=1)
y<-drop(x %*% beta + rnorm(100))

## backward stepwise in a function - works fine
backward.step<-function(x,y,...) {

   lsdata<-data.frame(cbind(x=x,y=y))

   xnam <- names(lsdata)[names(lsdata) != "y"]
   (fmla <- as.formula(paste("y ~ ", paste(xnam, collapse= "+"))))
   fit<-lm(fmla,data=lsdata)
   step.fit<-step(fit, direction="backward",data=lsdata)
   step.fit

}

backward.fit<-backward.step(x,y)

## forward stepwise in a function - error

forward.step<-function(x,y,...) {

   lsdata<-data.frame(cbind(x=x,y=y))

   xnam <- names(lsdata)[names(lsdata) != "y"]
   (fmla <- as.formula(paste("y ~ ", paste(xnam, collapse= "+"))))
   fit<-lm(y ~ 1,data=lsdata)
   step.fit<-step(fit,scope = fmla, direction="forward",data=lsdata)
   step.fit

}

forward.fit<-forward.step(x,y)




More information about the R-help mailing list