db = tibble(a = rnorm(100), b = rnorm(100), c = rnorm(100))
如果我想要一個整潔的多元線性回歸,我可以去
lm(data = db, 0 a ~ b c) %>% tidy()
但是如果我想要多個單變數回歸,我會去
lm(data = db, a ~ 0 b) %>% tidy() %>%
add_row(lm(data = db, a ~ 0 c) %>% tidy())
現在,給定許多回歸量列,我想避免將每個單獨的回歸量編碼為新的add_row,我應該如何使代碼更加綜合?
這在這里有一個部分解決方案:
使用 purrr、broom 的許多單變數模型的整齊輸出
我認為代碼可以比示例中的更精簡?
uj5u.com熱心網友回復:
我們可以{}用來阻止多個運算式
library(magrittr)
library(broom)
lm(data = db, a ~ 0 b) %>%
tidy() %>%
{add_row(., lm(data = db, a ~ 0 c) %>%
tidy())}
-輸出
# A tibble: 2 × 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 b 0.0601 0.0907 0.663 0.509
2 c 0.0411 0.0899 0.457 0.649
或者可以在summarise和unnest
library(tidyr)
db %>%
summarise(out1 = list(bind_rows(lm(a ~ 0 b) %>% tidy,
lm(a~ 0 c) %>% tidy))) %>%
unnest(out1)
-輸出
# A tibble: 2 × 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 b 0.0601 0.0907 0.663 0.509
2 c 0.0411 0.0899 0.457 0.649
uj5u.com熱心網友回復:
我的答案
db %>%
select(-a) %>%
names() %>%
paste('a~0 ',.)%>%
map_df(~tidy(lm(as.formula(.x),
data= db,
)))
uj5u.com熱心網友回復:
您可以執行以下操作:取決于您的列:
library(broom)
vars <- names(db)[-1]
models <- list()
for (i in 1:2){
vc <- combn(vars,i)
for (j in 1:ncol(vc)){
model <- as.formula(paste0("a ~", paste0(vc[,j], collapse = " ")))
models <- c(models, model)
}
}
lapply(models, function(x) lm(x, data = db) %>% tidy())
[[1]]
# A tibble: 2 x 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 0.0155 0.0856 0.181 0.857
2 b -0.0502 0.0797 -0.630 0.530
[[2]]
# A tibble: 2 x 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 0.0113 0.0856 0.132 0.896
2 c 0.0553 0.0865 0.640 0.524
[[3]]
# A tibble: 3 x 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 0.0132 0.0860 0.153 0.878
2 b -0.0439 0.0807 -0.544 0.588
3 c 0.0486 0.0877 0.555 0.580
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/450187.html
下一篇:rmarkdown中的編號gt表
