[R] Problem storing lm() model in a list

Harold Pimentel haroldpimentel at gmail.com
Sat Dec 4 08:30:55 CET 2010


Hi all,

I recently wrote some code to store a number of polynomial models in a list and return this list. The model is returned fine, but when I make a subsequent call to predict(), I have an error. The code for polyModel selection is listed at the end of the email. Here is an example of the error:

> poly.fit <- polyModelSelection(x,y,10,F)
> for (d in 1:4) {
+     lm.model <- poly.fit$models[[d]]
+     curve(predict(lm.model,data.frame(x)),add=T,lty=d+1)
+ }
Error: variable 'poly(x, d, raw = T)' was fitted with type "nmatrix.1" but type "nmatrix.10" was supplied

Does anyone have any ideas? 



Thanks,

Harold


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

polyModelSelection <- function(x,y,maxd,add.dim=F) {
    dim.mult <- 0
    if (add.dim) {
        dim.mult = 1
    }
    bestD <- 1
    bestError <- 1
    loss <- 1
    lm.models <- vector("list",maxd)
    for (d in 1:maxd) {
        lm.mod <- lm(y ~ 0 + poly(x,d,raw=T))
        lm.models[[d]] <- lm.mod
        loss[d] <- modelError(lm.mod,data.frame(x),y)+d*dim.mult
        if (d == 1){
            bestError <- loss[d]
        }
        if (loss[d] < bestError) {
            bestError <- loss[d]
            bestD <- d
        }
        # print(loss[d])
    }
    list(loss=loss,models=lm.models,best=c(bestD))
}

modelError <- function(model,x,y) {
    sum((y-predict(model,x))^2)
}


More information about the R-help mailing list