Get coefficients "a" and "b" from the Linear Regression Model in R

2

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

    
asked by anonymous 12.07.2017 / 15:47

2 answers

3

It is also worth mentioning here the broom package that makes it much easier to get the data of a regression (estimates, standard error, t-statistic, p-value etc).

For example, to get the basic data of the coefficients of a regression, use the tidy() function. 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 data.frame with the estimate, standard error, t-statistic 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
    
13.07.2017 / 06:00
6

Using part of a response posted 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 coef command on 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 the R:

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

To obtain more complete information, such as the hypothesis tests associated with the regression coefficients, R ^ 2 and other statistics, use the 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

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

12.07.2017 / 17:02