# [R] Problem with predict.lm()

David L Carlson dcarlson at tamu.edu
Wed Apr 29 16:50:11 CEST 2015

```Since you passed a matrix to lm() and then a data.frame to predict(), predict can't match up what variables to use for the prediction so it falls back on the original data. This seems to work:

> set.seed(42)
> y <- rnorm(100)
> X <- matrix(rnorm(100*10), ncol=10)
> Xd <- data.frame(X)
> lm <- lm(y~., Xd)
> Xnew <- matrix(rnorm(100*20), ncol=10)
> Xnewd <- data.frame(Xnew)
> ynew <- predict(lm, newdata=Xnewd)
1           2           3           4           5           6
0.35404067  0.14073495 -0.45442499  0.31065562 -0.02091366  0.25358175
1           2           3           4           5           6
0.75474817  0.06024122 -0.27221466 -0.20344713  0.20218135 -0.24045859
>

-------------------------------------
David L Carlson
Department of Anthropology
Texas A&M University
College Station, TX 77840-4352

-----Original Message-----
From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Martin Spindler
Sent: Wednesday, April 29, 2015 9:21 AM
To: r-help at r-project.org
Subject: [R] Problem with predict.lm()

Dear all,

the following example somehow uses the "old data" (X) to make the predictions, but not the new data Xnew as intended.

y <- rnorm(100)
X <- matrix(rnorm(100*10), ncol=10)
lm <- lm(y~X)
Xnew <- matrix(rnorm(100*20), ncol=10)
ynew <- predict(lm, newdata=as.data.frame(Xnew)) #prediction in not made for Xnew

How can I foce predict.lm to use use the new data?

Best,

Martin

______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help