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

bad*_*max 5 r

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

x1 <- rnorm(100)
x2 <- rnorm(100)
y <- x1 + 5 * x2 + rnorm(100)
fit <- lm(y ~ x1 + x2)
Run Code Online (Sandbox Code Playgroud)

我如何输出summary(fit)但按估计系数的大小排序?

Cha*_*ase 3

如果您不介意加载外部包的开销,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
Run Code Online (Sandbox Code Playgroud)

由reprex 包(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
Run Code Online (Sandbox Code Playgroud)

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