首页 文章

使用dplyr()检索通过group_by()和do()创建的模型对象

提问于
浏览
1

我正在尝试使用 dplyr 和管道运算符( %>% )来检索存储在数据帧中的模型对象 .

使用示例数据

library(dplyr)

set.seed(256)
dat <- 
  data.frame(x = rnorm(100), 
           y = rnorm(100, 10), 
           spec = sample(c("1", "2"), 100, TRUE)) %>%
  group_by(spec) %>%
  do(lm = lm(y ~ x, data = .))

我可以分组和检索实际的模型对象

> dat$lm[dat$spec == "1"][[1]]

Call:
lm(formula = y ~ x, data = .)

Coefficients:
(Intercept)            x  
     9.8171      -0.2292  

> dat$lm[dat$spec == "1"][[1]] %>% class()
[1] "lm

但我认为这是检索其中包含的 lm() 模型对象的一种不优雅的方式,特别是考虑到我的其余代码的结构是“ dplyr ” . 我想使用 dplyr ,但我无法弄清楚如何 . 例如,使用

dat %>% filter(spec == "1") %>% select(lm)

因为它返回不起作用

Source: local data frame [1 x 1]
Groups: <by row>

# A tibble: 1 x 1
  lm      
  <list>  
1 <S3: lm>

dat %>% filter(spec == "1") %>% .$lm

只让我到列表中的第一个对象,例如,

> dat %>% filter(spec == "1") %>% .$lm
[[1]]

Call:
lm(formula = y ~ x, data = .)

Coefficients:
(Intercept)            x  
   10.01495     -0.07438

我无法找到一种方法来获取 dat 中的实际模型对象 dplyr . 当然,我可以使用 broomtidy() 来浓缩一切

library(broom)
tidy(dat, lm)

但是这仍然不会返回实际的模型对象:

> tidy(dat, lm)
# A tibble: 4 x 6
# Groups: spec [2]
  spec  term        estimate std.error statistic                        p.value
  <fct> <chr>          <dbl>     <dbl>     <dbl>                          <dbl>
1 1     (Intercept)  10.0        0.120    83.3                         1.91e-54
2 1     x           - 0.0744     0.111   - 0.671                       5.05e- 1
3 2     (Intercept)   9.86       0.131    75.0                         1.42e-50
4 2     x           - 0.0793     0.148   - 0.535                       5.95e- 1

我甚至可以使用 dplyr 来调用 do() 调用的输出并从模型中检索系数,但这仍然不能给我模型对象本身:

dat %>% 
  select(spec) %>%
  bind_cols(dat %>%
              summarize(lm_i = coefficients(lm)[[1]], 
                        lm_s = coefficients(lm)[[2]]))

是否有 dplyr 方法从使用 do() 创建的模型中检索实际模型对象?

1 回答

  • 3

    do 返回列表列,因此要提取其各个元素,您需要使用列表子集 . 有多种方法可以做到这一点,但在tidyverse中, purrr::pluck 是提取单个[可能深度嵌套]元素的不错选项:

    library(tidyverse)
    
    dat %>% pluck('lm', 1)
    #> 
    #> Call:
    #> lm(formula = y ~ x, data = .)
    #> 
    #> Coefficients:
    #> (Intercept)            x  
    #>    10.01495     -0.07438
    

    它大部分相当于 [[ 子集,即

    dat[['lm']][[1]]
    

    为了获得你必须工作的东西,你需要保持子集,因为 .$lm 返回列表列,在这种情况下是列表的模型 . .[[1]] (类似于上面的 1 )从列表中提取模型:

    dat %>% filter(spec == "1") %>% .$lm %>% .[[1]]
    

    或者是混合方法,如果你喜欢:

    dat %>% filter(spec == "1") %>% pluck('lm', 1)
    

    或者使用 pull 来提取具有NSE语义的列:

    dat %>% filter(spec == "1") %>% pull(lm) %>% pluck(1)
    

    所有回报都是一样的 .

相关问题