[R] How to get the intercept from lm?

Barry Rowlingson B.Rowlingson at lancaster.ac.uk
Fri Mar 10 11:51:27 CET 2006


Rainer M Krug wrote:

> I want to use lm() to get the slope and intercept for several daatasets 
> and store them in a database. So far so good - but how do I extract the 
> slope and the intercept from the result from lm()?

  Read the help for lm - it talks about coefficients rather than slope 
and intercept, because a linear model can have more (or less) than a 
slope and an intercept.

  But basically you want the coef() or coefficients() function on the model:

  > x=1:10;y=x*1.4+2.5;m=lm(y~x)
  > m

  Call:
  lm(formula = y ~ x)

  Coefficients:
  (Intercept)            x
          2.5          1.4

  > coef(m)
  (Intercept)           x
          2.5         1.4
  > coef(m)[1]
  (Intercept)
          2.5
  > coef(m)[2]
    x
  1.4

In general the help for any function should tell you what you can do 
with its returned object in the 'VALUE' section of the help, but there 
may also be functions like 'coef()' that give back useful info. For lm() 
objects there's coef(), residuals(), fitted() etc.

Barry




More information about the R-help mailing list