如何在Purr中修复“ eval(predvars,data,env)中的错误:数字'envir'arg长度不为1”

时间:2019-05-30 00:03:46

标签: r purrr glm broom

我正在引导知名的mtcars数据集,并使用glmpurrr::map应用逻辑回归。但是,我得到

Error in eval(predvars, data, env) : 
  numeric 'envir' arg not of length one

错误

我已经尝试将glm应用于单个引导数据,并且可以正常工作,但是当我应用map函数时,它将失败

library(tidyverse)
library(rsample)
library(broom)

sample10 <- 
    bootstraps(mtcars, times=10) %>%  
    rowwise() %>% 
    mutate(data_sample=list(analysis(splits))) %>%
    select(id, data_sample)

sample10

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

# A tibble: 10 x 2
   id          data_sample        
   <chr>       <list>             
 1 Bootstrap01 <df[,11] [32 × 11]>
 2 Bootstrap02 <df[,11] [32 × 11]>
 3 Bootstrap03 <df[,11] [32 × 11]>
 4 Bootstrap04 <df[,11] [32 × 11]>
 5 Bootstrap05 <df[,11] [32 × 11]>
 6 Bootstrap06 <df[,11] [32 × 11]>
 7 Bootstrap07 <df[,11] [32 × 11]>
 8 Bootstrap08 <df[,11] [32 × 11]>
 9 Bootstrap09 <df[,11] [32 × 11]>
10 Bootstrap10 <df[,11] [32 × 11]>

当我尝试为每个引导数据框拟合模型时:

sample10 %>% 
    mutate(model_fit = map(data_sample, 
                           ~ glm(formula= vs ~ wt + disp,                    
                                 data=., 
                                 family=binomial)))

Error in eval(predvars, data, env) : 
  numeric 'envir' arg not of length one

但是,当我尝试将glm装入单个Bootstrap数据帧时,一切都很好

glm(formula= vs ~ wt + disp, data=sample10$data_sample[[1]], family=binomial)


Call:  glm(formula = vs ~ wt + disp, family = binomial, data = sample10$data_sample[[1]])

Coefficients:
(Intercept)           wt         disp  
    5.54313     -1.19918     -0.01472  

Degrees of Freedom: 31 Total (i.e. Null);  29 Residual
Null Deviance:      41.18 
Residual Deviance: 16.97    AIC: 22.97

该错误消息没有帮助,我不确定自己在做什么错。我觉得它具有purrr::map函数,但不确定。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我认为的问题是,小标题仍按行分组。如果将ungroup()添加到链的最后一步,则代码将起作用。

sample10 <- bootstraps(mtcars, times=10) %>%  
  rowwise() %>% 
  mutate(data_sample=(list(analysis(splits)))) %>%
  select(id, data_sample) %>%
  ungroup()

sample10 %>% 
  mutate(model_fit = map(data_sample, 
                         ~ glm(formula= vs ~ wt + disp,                    
                               data=., 
                               family=binomial)))


# A tibble: 10 x 3
   id          data_sample            model_fit
   <chr>       <list>                 <list>   
 1 Bootstrap01 <data.frame [32 x 11]> <S3: glm>
 2 Bootstrap02 <data.frame [32 x 11]> <S3: glm>
 3 Bootstrap03 <data.frame [32 x 11]> <S3: glm>
 4 Bootstrap04 <data.frame [32 x 11]> <S3: glm>
 5 Bootstrap05 <data.frame [32 x 11]> <S3: glm>
 6 Bootstrap06 <data.frame [32 x 11]> <S3: glm>
 7 Bootstrap07 <data.frame [32 x 11]> <S3: glm>
 8 Bootstrap08 <data.frame [32 x 11]> <S3: glm>
 9 Bootstrap09 <data.frame [32 x 11]> <S3: glm>
10 Bootstrap10 <data.frame [32 x 11]> <S3: glm>