如何在LM摘要中对系数进行排序?

时间:2019-05-18 21:57:43

标签: r

假设我有一个像这样的模型:

x1 <- rnorm(100)
x2 <- rnorm(100)
y <- x1 + 5 * x2 + rnorm(100)
fit <- lm(y ~ x1 + x2)

如何以估计系数的大小顺序输出summary(fit)

1 个答案:

答案 0 :(得分:2)

如果您不介意加载外部软件包的开销,那么broom会变得很简单:

x1 <- rnorm(100)
x2 <- rnorm(100)
y <- x1 + 5 * x2 + rnorm(100)
fit <- lm(y ~ x1 + x2)

library(broom)
coefs <- tidy(fit)
coefs[order(coefs$estimate, decreasing = TRUE),]
#> # A tibble: 3 x 5
#>   term        estimate std.error statistic  p.value
#>   <chr>          <dbl>     <dbl>     <dbl>    <dbl>
#> 1 x2            4.95      0.0883    56.1   1.04e-75
#> 2 x1            1.17      0.109     10.7   3.27e-18
#> 3 (Intercept)   0.0131    0.103      0.128 8.99e- 1

reprex package(v0.2.1)于2019-05-18创建

编辑-添加统计意义注释

您可以在事实之后添加它:

x1 <- rnorm(100)
x2 <- rnorm(100)
y <- x1 + 5 * x2 + rnorm(100)
fit <- lm(y ~ x1 + x2)

library(broom)
coefs <- tidy(fit)
coefs$p.value <- with(coefs, 
                      ifelse(abs(p.value) > .1, paste0(formatC(p.value, format = "e", digits = 2),""),
                             ifelse(abs(p.value) > .05, paste0(formatC(p.value, format = "e", digits = 2),"."),
                                    ifelse(abs(p.value) > .01, paste0(formatC(p.value, format = "e", digits = 2),"*"),
                                           ifelse(abs(p.value) > .001, paste0(formatC(p.value, format = "e", digits = 2),"**"),
                                           paste0(formatC(p.value, format = "e", digits = 2),"***"))))))
coefs[order(coefs$estimate, decreasing = TRUE),]
#> # A tibble: 3 x 5
#>   term        estimate std.error statistic p.value    
#>   <chr>          <dbl>     <dbl>     <dbl> <chr>      
#> 1 x2            4.91      0.0923    53.2   1.51e-73***
#> 2 x1            0.768     0.0890     8.64  1.17e-13***
#> 3 (Intercept)  -0.0327    0.0990    -0.330 7.42e-01

reprex package(v0.2.1)于2019-05-18创建