首页 > 解决方案 > 如何显示来自 lm 输出的参考电平?

问题描述

我想为线性回归输出 lm() 的最终输出添加一个参考电平。例如:

levels(iris$Species)
"setosa"     "versicolor" "virginica" 

summary(lm(Sepal.Length ~ Petal.Width + Species, iris))

Coefficients:
                  Estimate Std. Error t value Pr(>|t|)    
(Intercept)        4.78044    0.08308  57.543  < 2e-16 ***
Petal.Width        0.91690    0.19386   4.730 5.25e-06 ***
Speciesversicolor -0.06025    0.23041  -0.262    0.794    
Speciesvirginica  -0.05009    0.35823  -0.140    0.889    

我想拥有它:

Coefficients:
                  Estimate Std. Error t value Pr(>|t|)    
(Intercept)        4.78044    0.08308  57.543  < 2e-16 ***
Petal.Width        0.91690    0.19386   4.730 5.25e-06 ***
Speciessetosa      
Speciesversicolor -0.06025    0.23041  -0.262    0.794    
Speciesvirginica  -0.05009    0.35823  -0.140    0.889    

我一直在寻找它已经有一段时间了,但还没有任何线索。任何帮助将不胜感激。

@编辑

进一步扩展的数据:

iris$Petal.Width <- as.factor(ifelse(iris$Petal.Width >1, "Big", "Small"))

levels(iris$Petal.Width)
"Big"   "Small"

标签: rlinear-regression

解决方案


这是您可以使用的基本工作流程,用于使用dplyr并将broom您的级别与系数表连接起来。现在它需要你知道哪些变量是因子。如果您愿意,可以更改为NA""它还按字母顺序组织输出,这并不总是将参考组放在首位。如果您对此缩放有任何问题,请告诉我:

library(broom)
library(dplyr)

iris <- datasets::iris

iris$Petal.Width <- factor(ifelse(iris$Petal.Width > 1, "Big", "Small"), levels = c("Small", "Big"))

reg_obj <- lm(Sepal.Length ~ Petal.Width + Species, iris)

factor_levels <- tibble(term = c(paste0("Species", levels(iris$Species)),
                                 paste0("Petal.Width", levels(iris$Petal.Width))))

full_join(tidy(reg_obj), factor_levels, by = "term") %>%
  arrange(term)

# A tibble: 6 x 5
  term              estimate std.error statistic    p.value
  <chr>                <dbl>     <dbl>     <dbl>      <dbl>
1 (Intercept)          5.01     0.0709     70.6   1.03e-114
2 Petal.WidthBig       0.607    0.204       2.97  3.51e-  3
3 Petal.WidthSmall    NA       NA          NA    NA        
4 Speciessetosa       NA       NA          NA    NA  
5 Speciesversicolor    0.408    0.202       2.02  4.55e-  2
6 Speciesvirginica     0.975    0.228       4.28  3.33e-  5

推荐阅读