[R] variable '%s' was fitted with class... in predict.nls()

Jeff D. Hamann jeff.hamann at forestinformatics.com
Thu Mar 9 02:36:18 CET 2006

I've tried to predict the values from a new data.frame using the
nls.predict   function and keep getting the error message:

Error in if (sum(wrong) == 1) stop(gettextf("variable '%s' was fitted with
class \"%s\" but class \"%s\" was supplied",  :
	missing value where TRUE/FALSE needed

I first thought that it was becuase there may have been something goofy in
the formats of the objects/data.frames I was passing to the predict(), but
when I examined the code (online) I found the following:

I've trid to decipher the code, but most people are much better R
programmers that I, and I'm not sure what's going on here. DOes this mean
I have to use the same data frame I used to fit the model, in order to fit
"new" data?

.checkMFClasses <- function(cl, m, ordNotOK = FALSE)
    new <- sapply(m, .MFclass)
    if(length(new) == 0) return()
    old <- cl[names(new)]
    if(!ordNotOK) {
        old[old == "ordered"] <- "factor"
        new[new == "ordered"] <- "factor"
    ## ordered is OK as a substitute for factor, but not v.v.
    new[new == "ordered" && old == "factor"] <- "factor"
    if(!identical(old, new)) {
        wrong <- old != new
        if(sum(wrong) == 1)
    "variable '%s' was fitted with class \"%s\" but class \"%s\" was
                          names(old)[wrong], old[wrong], new[wrong]),
                 call. = FALSE, domain = NA)
    "variables %s were specified with different classes from the fit",
                 paste(sQuote(names(old)[wrong]), collapse=", ")),
                 call. = FALSE, domain = NA)

The docs for predict.nls state:

 newdata: A named list or data frame in which to look for variables
          with which to predict.  If 'newdata' is missing the fitted
          values at the original data points are returned.

I understand this to mean that the newdata data.frame simply need
*include* the variables that are in the model (extra's variables fine?)

When I used,

predict( fits.by.species.30[[1]], dbh=other.202$dbh, se.fit=TRUE )

I got results alright, but I would like to be able to simply pass a new
data.frame that contains the independent variables without having to build
a list of names. Is that possible?


Jeff D. Hamann
Forest Informatics, Inc.
PO Box 1421
Corvallis, Oregon 97339-1421
phone 541-754-1428

More information about the R-help mailing list