[R] Problem using stepAIC/addterm (MASS package)

BEER Michael michael.beer at unifr.ch
Fri Feb 25 11:03:30 CET 2005


Hello,

I'm currently dealing with a rather strange problem when using the
function "stepAIC" ("MASS" package).  The setting is the following: From
model learning data sets ("learndata"), I want to be able to build
prediction functions (in order to save them in a file for further use).
This is done by the function "pred.function" (see below). Therein, I'd
like to use "stepAIC" for model selection.

However, if I try to evaluate "pred.function" for a specific data set, R
sometimes stops with the message

---
Error in inherits(x, "data.frame") : Object "learndata" not found
---

Debugging "stepAIC" showed me that the problem occurs in the step where
"addterm" is called. "addterm" somehow doesn't seem to see the object
"learndata" which is present (?) in the function's environment.

Here is my code. The dataset "BostonHousing" is just an example for
which this problem can be observed. "my.MC" is inspired by the "Lexical
scoping" section in the R FAQ
(http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html#Lexical-scoping).

---
data(BostonHousing, package = "mlbench")
my.MC <- function (f, env) f  # make closure

pred.function <- function (learndata) {

    my.model <- lm(medv ~ ., learndata)

    if (!require("MASS"))
        stop("Package MASS not loadable.")

    my.model <- stepAIC(my.model, 
		scope = list(lower = medv ~ 1, 
			upper = medv ~ .))

    my.MC(function(newdata) {
        	predict(my.model, newdata)
    	    },
	    list(my.model = my.model)
    )
}

pf <- pred.function(BostonHousing)
---

How can I tell "addterm" (or "stepAIC") where to find "learndata"?

Thanks for your help.

Regards
Michael

-- 
Michael Beer, dipl. math., University of Freiburg/Fribourg Switzerland
Seminar of Statistics, Av. de Beauregard 13, CH-1700 Freiburg
Phone +41 26 300 8278, Fax +41 26 300 9781
E-mail: michael.beer at unifr.ch, Web: http://www.unifr.ch/stat/




More information about the R-help mailing list