模型失败时的 r `dlply` 错误处理

r `dlply` error handling when model fails

我正在使用 dlply 按子组执行多个模型

library(dplyr)
library(geepack)

data("mtcars")

mtcars <- mtcars[,c("mpg", "cyl", "hp")]

models = plyr::dlply(mtcars, "cyl", function(df) lm(mpg ~ hp,data=df))
lapply(models, summary)

在某些情况下,某些模型不会收敛而导致失败。为了说明我的观点,我正在修改上面的代码,使其故意失败。

mtcars_test <- mtcars[,c("mpg", "cyl", "hp")]

mtcars_test <- mtcars_test %>% mutate(mpg = replace(mpg, which(cyl == 6 & mpg < 20), "9as34"))

models = plyr::dlply(mtcars_test, "cyl", function(df) geeglm(mpg ~ hp,data=df))
lapply(models, summary)

如何强制 dlply 存储消息“收敛失败”而不是中途崩溃?

期待这样的结果。

 > models
$`4`

Call:
lm(formula = mpg ~ hp, data = df)

Coefficients:
(Intercept)           hp  
    35.9830      -0.1128  


$`6`

"Failed to converge"


$`8`

Call:
lm(formula = mpg ~ hp, data = df)

Coefficients:
(Intercept)           hp  
   18.08007     -0.01424  

这里假设模型无法收敛到子集,cylinder = 6 谢谢?

我们可以使用tryCatch

models <- plyr::dlply(mtcars_test, "cyl", function(df) 
   tryCatch(geeglm(mpg ~ hp,data=df), error = function(e) "Failed to converge"))