[R] predict.lm(...,type="terms") question

David Winsemius dwinsemius at comcast.net
Sat Sep 1 07:07:41 CEST 2012


On Aug 31, 2012, at 5:27 PM, jjthaden wrote:

> The error is generated in the last line of code shown here from  
> predict.lm

The code you offered had an extra comma in the 'area' vector. Removing  
allowed the fitting and prediction to proceed without error, I do not  
see why you are producing code from predict.lm.


>
>> predict.lm
> function (object, newdata, se.fit = FALSE, scale = NULL, df = Inf,
>    interval = c("none", "confidence", "prediction"), level = 0.95,
>    type = c("response", "terms"), terms = NULL, na.action = na.pass,
>    pred.var = res.var/weights, weights = 1, ...)
> {
>    tt <- terms(object)
>    if (!inherits(object, "lm"))
>        warning("calling predict.lm(<fake-lm-object>) ...")
>    if (missing(newdata) || is.null(newdata)) {
>        mm <- X <- model.matrix(object)
>        mmDone <- TRUE
>        offset <- object$offset
>    }
>    else {
>        Terms <- delete.response(tt)
>        m <- model.frame(Terms, newdata, na.action = na.action,
>            xlev = object$xlevels)
> #MORE LINES DELETED HERE...
>
> As written, if newdata is specified but it doesn't contain every  
> term  in
> the original data frame, then an error is thrown.

That statement is also not reproducible. To gain further attention you  
should offer code that demonstrates what errors you are seeing.

x <- rnorm(15); x2=rnorm(15)
  y <- x + x2 +rnorm(15)
  fit <- lm(y ~ x+x2)
  new <- data.frame(x = seq(-3.5, 3.5, 0.5)  )
  predict(fit, newdate=new)
# no error is thrown.

Given the fact that your earlier effort had an obvious syntax error  
that had absolutely nothing to do with predict.lm argument, I would  
ask that you conduct better testing of code that you offer for review.  
You now show no evidence for your assertion about the source of the  
error. Where is the error message and the results of traceback()?  
Where is the data. Where is the code?

(And please include context. (It is not difficult to do so with Nabble.)

> But for predict.lm to
> predict values for a term, i.e., type = "term", those terms cannot  
> be in the
> newdata vector.
> -John
>


-- 

David Winsemius, MD
Alameda, CA, USA




More information about the R-help mailing list