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

时间:2018-01-30 17:26:03

标签: r dplyr

我正在尝试使用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

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

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

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

1 个答案:

答案 0 :(得分: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)

所有回报都是一样的。

相关问题