Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order the coefficients in LM summary?

Tags:

r

Suppose I have a model like so:

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

How can I output summary(fit) but in order of the magnitude of the estimated coefficients?

like image 359
badmax Avatar asked Oct 16 '22 15:10

badmax


1 Answers

If you don't mind the overhead of loading an external package, broom makes this trivial:

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

Created on 2019-05-18 by the reprex package (v0.2.1)

Edit - adding stat significance annotations

You could add this after the fact:

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

Created on 2019-05-18 by the reprex package (v0.2.1)

like image 107
Chase Avatar answered Nov 15 '22 12:11

Chase