簡體   English   中英

如何在LM摘要中對系數進行排序?

[英]How to order the coefficients in LM summary?

假設我有這樣的模型:

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

如何按估計系數的大小順序輸出summary(fit)

如果你不介意加載外部軟件包的開銷,那么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包創建於2019-05-18(v0.2.1)

編輯 - 添加統計顯着性注釋

您可以在事后添加:

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包創建於2019-05-18(v0.2.1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM