[R] Problem with predict.lm()

Martin Spindler Martin.Spindler at gmx.de
Wed Apr 29 16:59:09 CEST 2015


Thank you! I think I now understand where the problem was.

Best,

Martin
 
 

Gesendet: Mittwoch, 29. April 2015 um 16:50 Uhr
Von: "David L Carlson" <dcarlson at tamu.edu>
An: "Martin Spindler" <Martin.Spindler at gmx.de>, "r-help at r-project.org" <r-help at r-project.org>
Betreff: RE: [R] Problem with predict.lm()
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)
> head(ynew)
1 2 3 4 5 6
0.35404067 0.14073495 -0.45442499 0.31065562 -0.02091366 0.25358175
> head(predict(lm))
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?
 
Thank you very much for your efforts in advance!
 
Best,
 
Martin

______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html[http://www.R-project.org/posting-guide.html]
and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list