我目前有以下R代码,它可以跨不同的子集运行具有不同预测变量的多个回归模型,并使用该broom包返回整理的输出。
library(dplyr)
library(purrr)
library(broom)
cars <- mtcars
preds<-c("disp", "drat", "wt")
model_fits <- map_df(preds, function(pred) {
model_formula <- sprintf("mpg ~ %s", pred)
cars %>%
group_by(cyl) %>%
do(tidy(lm(model_formula, data = .), conf.int = T)) %>%
filter(term == pred) %>%
mutate(outcome = "mpg") %>%
select(outcome, cyl:estimate, starts_with("conf."))
})
Run Code Online (Sandbox Code Playgroud)
这会产生以下数据框:
> model_fits
Source: local data frame [9 x 6]
Groups: cyl [3]
outcome cyl term estimate conf.low conf.high
<chr> <dbl> <chr> <dbl> <dbl> <dbl>
1 mpg 4 disp -0.135141815 -0.21018121 …Run Code Online (Sandbox Code Playgroud)