Home > OS >  How to index model object of regression to print specific coefficient
How to index model object of regression to print specific coefficient

Time:08-25

Ok. Here is my assignment:

Run a regression predicting calories from saturated fat, fiber, and sugar. Based on standardized regression coefficients, identify the strongest predictor.
Assign the unstandardized regression coefficient of the strongest predictor to Q4

Here is my code:

 suppressPackageStartupMessages(library(tidyverse))

 suppressPackageStartupMessages(library(lm.beta))

 suppressPackageStartupMessages(library(openintro))


 fastfood <- openintro::fastfood

 cal_model <- lm(calories ~ sat_fat   fiber   sugar, data = fastfood)
 cal_model_stancoeff <- lm.beta(cal_model)
 cal_model_coef_list <- cal_model[1]
 cal_model_coef_df <- do.call(rbind.data.frame, cal_model_coef_list)
 cal_model_coef_df1 <- rename(cal_model_coef_df, Intercept = X113.334379333345, sat_fat = 
 X30.8389266865679, fiber = X24.3961595673684, sugar = X8.88999973093656)
 Q4 <- cal_model_coef_df1[2]

Obviously, I am a beginner and this is an extremely tedious way of accessing the "unstandardized" coefficient of the strongest predictor for my regression model. How else could I do it? I have tried:

 which.max

but it doesn't work. My code has to be submitted to Codegrade and the output has to be:

 1.  sat_fat 
 2.  30.84

Using my code, my output is correct, but renaming column names isn't allowed in the Codegrade environment. This is the error I get:

 Error in `chr_as_locations()`:
 ! Can't rename columns that don't exist.
 ✖ Column `X113.334379333345` doesn't exist.
 Backtrace:
      etc.....

I have read a bunch and looked all over. What am I missing?

CodePudding user response:

I figured out some of it. Here is my updated code:

 cal_model <- lm(calories ~ sat_fat   fiber   sugar, data = fastfood)
 cal_model_stancoeff <- lm.beta(cal_model)
 Q4 <- round(cal_model[["coefficients"]][["sat_fat"]], 2)

Still can't get the

 1. sat_fat

to print.

CodePudding user response:

 summary.lm(cal_model)$coefficients[2]

also prints the coefficient value. However, I need both "sat_fat" and the value in this form:

 1. sat_fat
 2. 30.84
  • Related