[R] Error in calling stepAIC() from within a function
Prof Brian Ripley
ripley at stats.ox.ac.uk
Mon Aug 4 10:03:20 CEST 2003
Your example works for me in R-devel, and in R 1.7.1 using step()
rather than stepAIC().
On Sun, 3 Aug 2003, Siew Leng TENG wrote:
> Hi,
>
> I am experiencing a baffling behaviour of stepAIC(),
> and I hope to get any advice/help on what went wrong
> or I'd missed. I greatly appreciate any advice given.
>
> I am using stepAIC() to, say, select a model via
> stepwise selection method.
>
> R Version : 1.7.1
> Windows ME
>
> Many thanks and best regards,
> Siew-Leng
>
>
> ***Issue :
>
> When stepAIC() is placed within a function, it seems
> that stepAIC() cannot detect the data matrix, and
> the
> program is halted as a result. However, when the
> same
> codes are copied, paste and run in R workspace,
> stepAIC can execute and R is able to produce the
> desired output.
>
> ***Actions taken :
> I had tried to look into and manipulate environments
> and formals(f), but with not much luck.
>
>
> ***Code snippets (an example):
>
> library(MASS)
> library(nls)
>
> Data<-data.frame(matrix(rnorm(120),ncol=6))
> colnames(Data)<-c("Y",paste("X",1:5,sep=""))
>
> f<-function(A)
> {
> a <-glm(Y~X1+X2+X3, data=A)
> b
>
> <-stepAIC(a,scope=list(upper=~X1+X2+X3+X4+X5,lower=~1),direction="both",trace=FALSE)
> b
> }
>
>
> f(Data)
>
>
> R gives the following error :
>
> > f(Data)
> Error in model.frame.default(formula = Y ~ X1 + X3,
> data = A, drop.unused.levels = TRUE) :
> Object "A" not found
>
>
> However, when the same codes are copied, paste and
> run
> in the workspace, stepAIC() can run, and R is able
> to
> produce the desired output :
>
> A <- Data
> a <-glm(Y~X1+X2+X3, data=A)
> b
>
> <-stepAIC(a,scope=list(upper=~X1+X2+X3+X4+X5,lower=~1),direction="both",trace=FALSE)
> b
>
> > b
>
> > Call: glm(formula = Y ~ X4, data = A)
> >
> > Coefficients:
> > (Intercept) X4
> > 0.1942 -0.3314
> >
> > Degrees of Freedom: 19 Total (i.e. Null); 18
> > Residual
> > Null Deviance: 20.51
> > Residual Deviance: 17.95 AIC: 60.6
> > >
>
>
> __________________________________
>
> Yahoo! SiteBuilder - Free, easy-to-use web site design software
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>
--
Brian D. Ripley, ripley at stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272866 (PA)
Oxford OX1 3TG, UK Fax: +44 1865 272595
More information about the R-help
mailing list