[R] predict.lm with new regressor names

Michael Bedward michael.bedward at gmail.com
Thu Dec 16 07:16:17 CET 2010


Hi Anirban,

You can do it like this...

lm.foobar <- lm(foo ~ bar)

some.data <- rnorm(200)

predict(lm.foobar, newdata=list(bar=some.data))

Hope that helps.
Michael

On 16 December 2010 17:05, Anirban Mukherjee <am253 at cornell.edu> wrote:
> Hi all,
>
> Suppose:
>
> y<-rnorm(100)
> x1<-rnorm(100)
> lm.yx<-lm(y~x1)
>
> To predict from a new data source, one can use:
>
> # works as expected
> dum<-data.frame(x1=rnorm(200))
> predict(lm.yx, newdata=dum)
>
> Suppose lm.yx has been run and we have the lm object. And we have a
> dataframe that has columns that don't correspond by name to the
> original regressors. I very! naively assumed that doing this (below)
> would work. It does not.
>
> # does not work
> lm.yx$coefficients<-c("Intercept", "n.x1")
> dum2<-data.frame(Int=rep(1,200), n.x1=rnorm(200))
> predict(lm.yx, newdata=dum2)
>
> I know that a simple alternative is to do:
>
> # because we messed around with the lm object above, re-building
> lm.yx<-lm(y~x1)
>
> # change names of dum2 to match names of coefficients of lm.yx
> names(dum2)<-names(coefficients(lm.yx))
> predict(lm.yx, newdata=dum2)
>
> Is there another way that involves changing the lm object rather than
> changing the prediction data.frame?
>
> Thanks,
> Anirban
>
> --
> Anirban Mukherjee | Assistant Professor, Marketing
> LKCSB, Singapore Management University
> 5056 School of Business, 50 Stamford Road
> Singapore 178899 | +65-6828-1932
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list