【问题标题】:Access the estimate inside a model object in R访问 R 中模型对象内的估计值
【发布时间】:2017-08-10 03:39:41
【问题描述】:

我正在运行一个模拟,想知道是否可以使用 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)

【问题讨论】:

    标签: r dplyr purrr broom modelr


    【解决方案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 有意义。

    【讨论】:

    • 有没有办法让上述管道的这一部分在mutate(model_fit = map(data, mod)) 之后开始?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 2016-04-07
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    相关资源
    最近更新 更多