Skip to content
Prev 304654 / 398506 Next

predict.lm(...,type="terms") question

Hello,

John is right, there seems to be an error in predict.lm. It can be made 
to work but if the model is fitted with lm(...,data) then it messes 
things up. Apparently predict.lm disregards the data argument and uses 
whatever it finds in the global environment. In the examples below, 
after running David's x <- rnorm(15) example (case 1 is a simplified 
version of it), case 3 shows the bug, there are 15 predictions for 4 new 
values. Then we must backtrack to case 2 and also consider it a bug.

Examples:

# ------------------- 1
# David's example simplified, only one regressor.
# And with set.seed()

set.seed(4409)
x <- rnorm(15)
y <- x + rnorm(15)

fit <- lm(y ~ x)
new <- data.frame(y = seq(-3.5, 3.5, 0.5))
predict(fit, newdata = new, type = "terms")
# no error is thrown.

# ------------------- 2
# Original post, 'area' and 'concn' are now 'y' and 'x'
# Remove 'x' and 'y' from the global environment.
rm(x, y)
dat <- data.frame(
     y = c(4875, 8172, 18065, 34555),
     x = c(25, 50, 125, 250))
new <- data.frame(y = c(8172, 10220, 11570, 24150))

model <- lm(y ~ x, data = dat)
predict(model, newdata = new, type = "terms")
# Error in eval(expr, envir, enclos) : object 'x' not found

# ------------------- 3
# Original post.
# Do NOT remove 'x' and 'y' from the global environment.
set.seed(4409)
x <- rnorm(15)
y <- x + rnorm(15)

dat <- data.frame(
     y = c(4875, 8172, 18065, 34555),
     x = c(25, 50, 125, 250))
new <- data.frame(y = c(8172, 10220, 11570, 24150))

model <- lm(y ~ x, data = dat)
predict(model, newdata = new, type = "terms")
# Warning message:
# 'newdata' had 4 rows but variable(s) found have 15 rows

#------------------- 4
# Original post, no data argument to lm.

y <- c(4875, 8172, 18065, 34555)
x <- c(25, 50, 125, 250)
new <- data.frame(y = c(8172, 10220, 11570, 24150))

model <- lm(y ~ x)
predict(model, newdata = new, type = "terms")
# no warning or error is thrown, predictions seem allright

I haven't looked at the code for predict.lm, and really don't know where 
the error is.
Bug report?

Rui Barradas

Em 01-09-2012 06:40, David Winsemius escreveu: