如何提取线性模型的系数并存储在 R 中的变量中?

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

我有一个数据框,我做了一个线性模型。我想提取系数并使用 R 将每个系数存储到一个变量中。 这是我的数据框

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

这是我提取一个系数的方法

beta_0 = fit$coefficients[1]

我想对模型中的所有系数自动执行此操作。我尝试使用循环但不起作用。我知道这不是正确的代码,但那是我发现的

for (i in fit$coefficients(1:11)) {
  d["s{0}".format(x)] = variable1
}
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

在大多数情况下,as.numeric(coef(fit)[i])足以隔离系数:

fit <- lm(mpg~.,mtcars)
for(i in 1:length(coef(fit))){
  print(as.numeric(coef(fit)[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

如果您需要将系数放入数据框,此代码会将每个系数放入数据框 (vars) 内的单独变量(variable1、variable2、..):

fit <- lm(mpg~.,mtcars)
ce <- coef(fit)
vars <- data.frame(col = (NA))
for(i in 1:length(ce)) {                         
  new_col <- as.numeric(ce[i])                  
  vars[ 1, i] <- new_col                        
  colnames(vars)[i] <- paste0("variable", i)
}    
vars
# variable1  variable2  variable3   variable4 variable5 variable6 variable7 variable8 variable9 variable10 variable11
# 1  12.30337 -0.1114405 0.01333524 -0.02148212  0.787111 -3.715304 0.8210407 0.3177628  2.520227   0.655413 -0.1994193