使用 dplyr 和 broom::glance 比较模型:如果产生错误如何继续?

Comparing models with dplyr and broom::glance: How to continue if error is produced?

我想 运行 使用 R 中的 lme4 包将数据集中的每个变量作为单变量 glmer 模型。我想用 dplyr/tidyr 包准备数据,并组织来自带有扫帚包的每个模型的结果(即 do(glance(glmer...错误并且与我正在使用的数据具有相同的结构:

library(lme4)
library(dplyr)
library(tidyr)
library(broom)

Bird<-c(rep(c(0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0),10))
Stop<-c(rep(seq(1,10), 20))
Count<-c(rep(c(rep(c(1,2), each=10)), each=10))
Route<-c(rep(seq(1,10), each=20))
X1<-rnorm(200, 50, 10)
X2<-rnorm(200, 10, 1)
X3<-c(rep(c(0),200))#trouble maker variable

Data<-data.frame(cbind(Bird, Stop, Count, Route, X1, X2, X3))

Data%>%
  gather(Variable, Value, 5:7)%>%
  group_by(Variable)%>%
  do(glance(glmer(Bird~Value+Stop+(1+Stop|Route/Count), data=.,     family=binomial)))

最后一个变量产生错误,因此没有输出。如果发生这种情况,我想要的是在输出中生成 NA 值,或者只是跳过该变量。我试过使用 'try' 来解决麻烦制造者变量:

do(try(glance(glmer(Bird~Value+Stop+(1+Stop|Route/Count), data=.,       family=binomial))))

它确实如此,但仍然没有产生输出,因为它无法将 'try-error' 强制转换为 data.frame。不幸的是,没有 tryharder 函数。我已经尝试了一些对我有意义但对计算机没有意义的 if 语句。我确定我做的不对,但是如果我使用:

try(glance(glmer(Bird~Value+Stop+(1+Stop|Route/Count), data=., family=binomial)))->mod
if(is.data.frame(mod)){do(mod)}

我遇到下标越界错误。非常感谢您提供的任何输入!

在调用 glance 之前使用 tryCatch:

zz = Data %>%
  gather(Variable, Value, 5:7) %>%
  group_by(Variable) %>%
  do(aa = tryCatch(glmer(Bird~Value+Stop+(1+Stop|Route/Count), data=., 
                  family=binomial), error = function(e) data.frame(NA))) 


zz %>% 
  glance(aa)