我正在运行模拟,想知道是否有办法使用broom,dplyr,modelr或purrr访问模型内部的“x”估计值。
这给了我我想要的内容,但我不想在最后一段代码中使用[[1]]
。
library(tidyverse)
library(purrr)
library(broom)
mod <- function(df) {
lm(y ~ x, data = df)
}
sim <- tibble(
model = "model1",
mu = 5, #this is unknown in practice
beta = 2.7, #this is unknown in practice
sigma = 0.15, #this is unknown in practice
mu_e = 0,
sigma_e = 1
)
sim_dat <- sim %>%
crossing(replication = 1:10000) %>%
mutate(e = rnorm(mu_e, mu_e),
x = sample(c(0,1),size=n(),replace = TRUE,prob=c(0.5, 0.5)),
y = mu+x*beta+e) %>%
group_by(model) %>%
nest() %>%
mutate(model_fit = map(data, mod))
broom::tidy(sim_dat$model_fit[[1]]) %>%
filter(term=="x") %>%
select(estimate)
答案 0 :(得分:1)
您可以使用purrr::map_df()
:
map_df(sim_dat$model_fit, broom::tidy) %>%
filter(term=="x") %>%
select(estimate)
您也可以将其放在mutate(model_fit = ...)
中,如下所示:
sim_dat <- sim %>%
crossing(replication = 1:10000) %>%
mutate(e = rnorm(mu_e, mu_e),
x = sample(c(0,1),size=n(),replace = TRUE,prob=c(0.5, 0.5)),
y = mu+x*beta+e) %>%
group_by(model) %>%
nest() %>%
mutate(model_fit = map(data, mod),
# you can pipe inside of mutate()
x_coef = map_dbl(model_fit, ~broom::tidy(.) %>%
filter(term =="x") %>%
select(estimate) %>%
unlist() ) )
根据您要为x_coef
返回的对象类别,您可以使用map_suffix()
并且可能删除unlist()
我认为dbl
有意义