Obtain coefficients "a" and "b" of the Linear Regression Model in R

Asked

Viewed 658 times

2

In a Simple Linear Regression model - y = a + bx - we have the angular coefficient "b" and the intercept "a". I wonder how I do to get these coefficients in R?

2 answers

7

Using part of a reply published here in the OS a few days ago:

regressao <- lm(mpg ~ cyl, data = mtcars)
coef(regressao)
(Intercept)         cyl 
   37.88458    -2.87579 

That is, just use the command coef the object created with the regression results. If you want to use these values in other calculations, you can save them to other objects within your session in R:

a <- coef(regressao)[1] 
b <- coef(regressao)[2]

To obtain more complete information, such as hypothesis tests associated with regression coefficients, R 2 and other statistics, use the command summary:

summary(regressao)

Call:
lm(formula = mpg ~ cyl, data = mtcars)

Residuals:
    Min      1Q  Median      3Q     Max 
-4.9814 -2.1185  0.2217  1.0717  7.5186 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  37.8846     2.0738   18.27  < 2e-16 ***
cyl          -2.8758     0.3224   -8.92 6.11e-10 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 3.206 on 30 degrees of freedom
Multiple R-squared:  0.7262,    Adjusted R-squared:  0.7171 
F-statistic: 79.56 on 1 and 30 DF,  p-value: 6.113e-10

Realize that the summary informs, inside the column Estimate, the values of the linear coefficients ((Intercept)) and angular (cyl) of the adjusted regression model.

  • Take the opportunity to include the data of the coefficients for use. a <- coef(regressao)[1] b <- coef(regressao)[2]

  • Thank you for your knowledge Marcus!

  • Thanks for the tip Daniel!

3


It is worth mentioning here also the package Broom which makes it easier to obtain data from a regression (estimates, standard error, statistics t, p-value etc).

For example, to take the basic data of the coefficients of a regression, use the function tidy(). Returning to the example of the model with the base mtcars:

library(broom) # carrega pacote
regressao <- lm(mpg ~ cyl, data = mtcars) # roda regressão
info_coeficientes <- tidy(regressao) # pega informações dos coeficientes

The object info_coeficientes is a data.frame with the estimate, standard error, statistics t and p-value for each of the coefficients, including the constant:

info_coeficientes
         term estimate std.error statistic      p.value
1 (Intercept) 37.88458 2.0738436 18.267808 8.369155e-18
2         cyl -2.87579 0.3224089 -8.919699 6.112687e-10
  • I like this job! Although it presents a little less information than the Summary() function, the information it presents seems to be a little clearer. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.