R: cannot predict specific value

sujinge9 picture sujinge9 · Dec 13, 2011 · Viewed 11.9k times · Source
> age <- c(23,19,25,10,9,12,11,8)
> steroid <- c(27.1,22.1,21.9,10.7,7.4,18.8,14.7,5.7)
> sample <- data.frame(age,steroid)
> fit2 <- lm(sample$steroid~poly(sample$age,2,raw=TRUE))
> fit2

Call:
lm(formula = sample$steroid ~ poly(sample$age, 2, raw = TRUE))

Coefficients:
(Intercept)                        -27.7225     
 poly(sample$age, 2, raw = TRUE)1    5.1819  
 poly(sample$age, 2, raw = TRUE)2   -0.1265  


> (newdata=data.frame(age=15))
 age
1  15

> predict(fit2,newdata,interval="predict")
    fit       lwr      upr
1 24.558395 17.841337 31.27545
2 25.077825 17.945550 32.21010
3 22.781034 15.235782 30.32628
4 11.449490  5.130638 17.76834
5  8.670526  2.152853 15.18820
6 16.248596  9.708411 22.78878
7 13.975514  7.616779 20.33425
8  5.638620 -1.398279 12.67552
Warning message:
'newdata' had 1 rows but variable(s) found have 8 rows 

Why does the predict function unable to predict for age=15?

Answer

Hong Ooi picture Hong Ooi · Dec 14, 2011

Instead of lm(data$y ~ data$x), use the form lm(y ~ x, data). That should solve your problem.

EDIT: the problem is not only with the call to lm, but also the use of poly(*, raw=TRUE). If you remove the raw=TRUE bit, it should then work. Not sure why raw=TRUE breaks here.