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

From: Woolner, Keith <kwoolner_at_indians.com>
Date: Mon, 14 Jul 2008 11:58:38 -0400

> 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



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. Received on Mon 14 Jul 2008 - 16:12:41 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 14 Jul 2008 - 16:31:58 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive