[R] How to get function from lm object?

Marc Schwartz marc_schwartz at me.com
Fri Jul 10 01:58:15 CEST 2009


On Jul 9, 2009, at 6:18 PM, Alexander V Stolpovsky wrote:

> Dear experts,
>
> I am trying to obtain a function from a model, so that I could  
> further manipulate it, plot it, etc. I can get model estimates and   
> manually construct a function, but this gets tedious when trying out  
> different functions to fit the data. There must be a better way of  
> doing it, no?
>
> x <- c(1:10)
> y <- c(1:10)
>
> fit <- lm(y ~ x)
> f <- function(x){fit$coef[1] + fit$coef[2]*x}  # Manually  
> constructing function
>                                               # Would be nice to do  
> something like this:
>                                               # f<-getFunction(fit)
> plot(f, 0, 10)
>
> Thanks,
>  Alex Stolpovsky

If you want to get the model fitted y values, just use:

   fitted(fit)

As an aside, to get the model coefficients, there is also:

   coef(fit)

and

   coef(summary(fit))

which like fitted(), is one of several 'extractor' functions that can  
be used on model object to get specific components.

If you want to generate model predicted y values based upon 'new' x  
values, use:

   newdata <- data.frame(x = YourNewValues)
   predict(fit, newdata = newdata)

Note that the 'newdata' data frame must contain columns with the SAME  
names as the independent variables in your original model.

See ?predict.lm for more information, which can also generate various  
intervals, etc.

If you want to plot your original data in a scatterplot and then add  
the model fitted line, use:

   plot(x, y)
   abline(fit)

See ?abline for more information there.

BTW, much of this is covered in An Introduction to R, which is  
included in your R installation and on the main R web site under  
Manuals link.

HTH,

Marc Schwartz




More information about the R-help mailing list