Search code examples
rlinear-regression

How to extract the coefficients of a linear model and store in a variable?


I have a data frame and I did a linear model. I want to extract the coefficients and store each coefficient into a variable using R. This is my data frame

df <- mtcars
fit <- lm(mpg~., data = df)

This is how I extract one coefficient

beta_0 = fit$coefficients[1]

I want to do this automatically for all coefficients in my model. I tried to use a loop but is not working. I know is not the right code but that was what I found

for (i in fit$coefficients(1:11)) {
  d["s{0}".format(x)] = variable1
}

Solution

  • df <- mtcars
    fit <- lm(mpg~., data = df)
    
    beta_0 = fit$coefficients[1]
    
    #base R approach
    coef_base <- coef(fit)
    coef_base
    #> (Intercept)         cyl        disp          hp        drat          wt 
    #> 12.30337416 -0.11144048  0.01333524 -0.02148212  0.78711097 -3.71530393 
    #>        qsec          vs          am        gear        carb 
    #>  0.82104075  0.31776281  2.52022689  0.65541302 -0.19941925
    
    
    #tidyverse approach with the broom package
    coef_tidy <- broom::tidy(fit)
    coef_tidy
    #> # A tibble: 11 x 5
    #>    term        estimate std.error statistic p.value
    #>    <chr>          <dbl>     <dbl>     <dbl>   <dbl>
    #>  1 (Intercept)  12.3      18.7        0.657  0.518 
    #>  2 cyl          -0.111     1.05      -0.107  0.916 
    #>  3 disp          0.0133    0.0179     0.747  0.463 
    #>  4 hp           -0.0215    0.0218    -0.987  0.335 
    #>  5 drat          0.787     1.64       0.481  0.635 
    #>  6 wt           -3.72      1.89      -1.96   0.0633
    #>  7 qsec          0.821     0.731      1.12   0.274 
    #>  8 vs            0.318     2.10       0.151  0.881 
    #>  9 am            2.52      2.06       1.23   0.234 
    #> 10 gear          0.655     1.49       0.439  0.665 
    #> 11 carb         -0.199     0.829     -0.241  0.812
    
    for (i in coef_base) {
      #do work on i
      print(i)
    }
    #> [1] 12.30337
    #> [1] -0.1114405
    #> [1] 0.01333524
    #> [1] -0.02148212
    #> [1] 0.787111
    #> [1] -3.715304
    #> [1] 0.8210407
    #> [1] 0.3177628
    #> [1] 2.520227
    #> [1] 0.655413
    #> [1] -0.1994193