Skip to content

Constructing a lm for predict() by hand

2 messages · Alexander Wise, Tony Plate

#
Hello, this probably seems like an odd question, but...

If I have the formula and the coefficients for a linear model that I 
would like to apply to some data using predict() -- is there a way I 
construct an object of type lm such that predict() will work with it? 
Or another way besides predict()?

Alexander Wise
Senior Software Engineer
http://laser.cs.umass.edu
#
One relatively easy way would be to construct some dummy data with the 
appropriate names and formula, use lm() to construct the model object, and 
then change the coefficients in the model object to be what you want (e.g., 
by fit$coefficients[2] <- 0.79).  This should then work with 
predict().  Don't make the mistake of thinking that output than output from 
anything other than predict(obj, newdata=data) will mean anything sensible 
-- summary(), predict(, se=T), ...

If your data is all numeric, then the easiest way might be just to use 
matrix computations:

pred <- cbind(1, data) %*% coef

where data is n x k matrix, coef is a vector of length k+1, and the 
intercept is the first element of coef.

hope this helps,

Tony Plate
At Tuesday 10:04 AM 1/6/2004 -0500, Alexander Wise wrote:
Tony Plate   tplate at acm.org