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

那年仲夏 提交于 2019-12-22 01:31:08

问题


I would like to run each variable in a dataset as a univariate glmer model using the lme4 package in R. I would like to prepare the data with the dplyr/tidyr packages, and organize the results from each model with the broom package (i.e. do(glance(glmer...). I would most appreciate help that stuck within that framework. I'm not that great in R, but was able to produce a dataset that throws an error and has the same structure as the data I'm using:

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)))

The last variable produces an error so there is no output. What I would like is it to produce NA values in the output if this occurs, or just skip that variable. I've tried using 'try' to blow past the trouble maker variable:

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

which it does, but still an output is not produced because it can't coerce a 'try-error' to a data.frame. Unfortunately there is no tryharder function. I've tried some if statements which make sense to me but not the computer. I'm sure I'm not doing it right, but if for example I use:

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

I get subscript out of bounds errors. Thanks very much for any input you can provide!


回答1:


Use tryCatch before the call to glance:

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)


来源:https://stackoverflow.com/questions/39044500/comparing-models-with-dplyr-and-broomglance-how-to-continue-if-error-is-produ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!