[R] More compact form of lm object that can be used for prediction?

Woolner, Keith kwoolner at indians.com
Mon Jul 14 17:58:38 CEST 2008


> From: Marc Schwartz [mailto:marc_schwartz at comcast.net]
> Sent: Friday, July 11, 2008 4:54 PM
> 
> on 07/11/2008 02:02 PM Woolner, Keith wrote:
> >> From: Marc Schwartz [mailto:marc_schwartz at comcast.net]
> >> Sent: Friday, July 11, 2008 12:14 PM
> >>
> >> on 07/11/2008 10:50 AM Woolner, Keith wrote:
> >>> Hi everyone,
> >>>
> >>> Is there a way to take an lm() model and strip it to a minimal
form (or
> >>> convert it to another type of object) that can still used to
predict the
> >>> dependent variable?
> >> <snip>
[...] 
> If the only thing that you need to do is to use the final models to
run
> predictions on new data, all you really need is the correct encoding,
> contrasts and any transforms of the IV's and the resultant
coefficients
> from the source models and code your program around those parameters.
> 
> If the models are not going to change 'too frequently' (a relative
term
> to be sure), I would not worry about spending a lot of time automating
> the processes. You can easily hard code the mechanics as they do
change
> once the basic framework is in place.
> 
> A possibility would be to create a design matrix from the new incoming
> data and then use matrix multiplication against the coefficients to
> generate the predictions.
> 
> For example, using the very simplistic model from ?predict.lm, we get:
> 
> x <- rnorm(15)
> y <- x + rnorm(15)
> 
> my.lm <- lm(y ~ x)
> 
> my.coef <- coef(my.lm)
> 
>  > my.coef
> (Intercept)           x
>    -0.232839    1.455494
> 
> # Create some new 'x' data for prediction
> new <- data.frame(x = seq(-3, 3, 0.5))
> 
> # Create a design matrix from the new data
> my.mm <- model.matrix(~ x, new)
> 
> # Now create the predicted 'y' values using the new 'x' data
>  > my.mm %*% my.coef

Thank you, once again, Marc!  This turns out to be exactly what I
needed.  I figured something like this should be possible, but I was
fumbling around for the right way to formulate it.  Your example was
perfect, and much appreciated.

Keith



More information about the R-help mailing list