如何从 lm 系数中提取系数名称?

How do I extract the coefficient names from the lm coefficients?

我有以下代码显示了 lm

的一些系数
fit <-lm(Petal.Width ~ Petal.Length, data=iris) 
cf <-coef(summary(fit,complete = TRUE)) 
colnames(cf)[4] <- "pval"
cf<- data.frame(cf)
cf <-cf[cf$pval < 0.05,]
cf <-cf[order(-cf$pval), ]
head(cf)
cf[1,1]

我想提取左列中的名称,即(截距)和花瓣长度。 我以为我可以使用 cf[1,1] 但它显示了估计

这些是使用rownames提取的:

fit <-lm(Petal.Width ~ Petal.Length, data=iris) 
cf <-coef(summary(fit,complete = TRUE)) 
rownames(cf)
#[1] "(Intercept)"  "Petal.Length"

tidyverse 解决方案是使用 broom:

library(broom)
tidy_fit <- tidy(fit)

结果:

# A tibble: 2 x 5
  term         estimate std.error statistic  p.value
  <chr>           <dbl>     <dbl>     <dbl>    <dbl>
1 (Intercept)    -0.363   0.0398      -9.13 4.70e-16
2 Petal.Length    0.416   0.00958     43.4  4.68e-86

然后很容易提取你想要的组件,并且生成的代码更具可读性,例如tidy_fit$term 获取变量列表((Intercept)Petal.Length)。