繁体   English   中英

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

[英]Using dplyr() to retrieve model object created via group_by() and do()

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

我无法找到一种方法来使用dplyr获取dat的实际模型对象。 当然,我可以使用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()调用的输出并从模型中检索系数,但这仍然不能给我模型对象本身:

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

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

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)

所有回报都是一样的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM