[R] predict.lm with new regressor names

Anirban Mukherjee anirban.mukherjee at gmail.com
Thu Dec 16 06:41:52 CET 2010


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



More information about the R-help mailing list