[R] predict.lm, matrix in formula and newdata

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Tue Aug 17 14:34:48 CEST 2010


try it better this way:

XX <- matrix(runif(8), ncol = 2)
DF <- as.data.frame(XX)
DF$yy <- runif(4)

model <- lm(yy ~ ., DF)
XX.pred <- as.data.frame(matrix(runif(6), ncol = 2))
predict(model, XX.pred)


I hope it helps.

Best,
Dimitris


On 8/17/2010 2:24 PM, Stephan Kolassa wrote:
> Dear all,
>
> I am stumped at what should be a painfully easy task: predicting from an lm object. A toy example would be this:
>
> XX<- matrix(runif(8),ncol=2)
> yy<- runif(4)
> model<- lm(yy~XX)
> XX.pred<- data.frame(matrix(runif(6),ncol=2))
> colnames(XX.pred)<- c("XX1","XX2")
> predict(model,newdata=XX.pred)
>
> I would have expected the last line to give me the predictions from the model based on the new data given in XX.pred... but all I get are in-sample fits along with a warning "'newdata' had 3 rows but variable(s) found have 4 rows". Why would predict.lm worry about the number of rows in the model matrix?
>
> Unfortunately, ?predict.lm does not seem to be helpful, and neither RSiteSearch nor rseek.org have been useful. I'm sure that I am making an elementary error somewhere (am I misunderstanding the lm(yy~XX) part?) and would appreciate a gentle nudge in the right direction.
>
> Thank you,
> Stephan
>

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014



More information about the R-help mailing list