gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:06:53 28 4
gpt4 key购买 nike

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

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
创建于 2019-05-18 由 reprex package (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
创建于 2019-05-18 由 reprex package (v0.2.1)

关于r - 如何对LM摘要中的系数进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56203147/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com