-4

I have linear model I would like to run weekly with updated data, and then extract and print the Estimate coefficients along with the titles. For example:

data <- mtcars
fit <- lm(mpg ~ cyl + disp + hp, data = data)
summary(fit)

Call:
lm(formula = mpg ~ cyl + disp + hp, data = data)

Residuals:
   Min         1Q     Median         3Q        Max 
-4.0888899 -2.0845357 -0.7744705  1.3971991  6.9183052 

Coefficients:
           Estimate  Std. Error  t value            Pr(>|t|)    
(Intercept) 34.18491917  2.59077758 13.19485 0.00000000000015372 ***
cyl         -1.22741994  0.79727631 -1.53952            0.134904    
disp        -0.01883809  0.01040369 -1.81071            0.080929 .  
hp          -0.01467933  0.01465087 -1.00194            0.324952    

Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 3.055261 on 28 degrees of freedom
Multiple R-squared:  0.7678877, Adjusted R-squared:  0.7430186 
F-statistic:  30.8771 on 3 and 28 DF,  p-value: 0.000000005053802

My ultimate goal would be to output something like below to a csv (or similar) file.

(Intercept) 34.18491917  
cyl         -1.22741994    
disp        -0.01883809
hp          -0.01467933

Is there any easy way to access the data in the fit, or would it have to be done manually?

ajamess
  • 141
  • 2
  • 12

2 Answers2

5

You can use either fit$coefficients or coef(fit).

Anthony S.
  • 361
  • 1
  • 11
  • 2
    The advantage of `coef()` is that it will be immune to any alterations to the underlying model object structure. – joran Jun 21 '16 at 20:44
0

To access the coefficients:

fit$coefficients
thepule
  • 1,721
  • 1
  • 12
  • 22