此问题类似于Using tryCatch() to catch a bootstrap loop,但是我无法使用tidyverse引导方法将建议应用于我的案例。我试图从复杂的混合效应模型中获取系数的置信区间估计,但是某些模型在引导过程中失败,从而终止了整个引导过程。我想忽略这些失败的运行(但还要计数并存储它们以了解它们是什么),然后继续执行引导程序。我也乐于接受将引导包与tryCatch一起使用的建议。使用钻石数据集的示例:
diamonds <- diamonds
diamonds$clarity <- factor(diamonds$clarity, ordered=FALSE)
diamonds$cut <- factor(diamonds$cut, ordered=FALSE)
diamonds$color <- factor(diamonds$color, ordered=FALSE)
diamonds <- diamonds[diamonds$price <= 500,] # truncate the data set for faster processing
无意义的随机模型,但运行没有错误:
my_mod <- glmmTMB(carat ~
cut*x*poly(depth,3) + table + price +
(1|color) + (1|clarity),
REML=TRUE,
data = diamonds)
summary(my_mod)
我想在“明确”级别(即按簇而不是观察值)进行替换抽样。
set.seed(30)
my_boot <- diamonds %>%
modelr::bootstrap(n = 20, id = 'clarity') %>%
group_by(clarity) %>%
mutate(fit = map(strap,
~glmmTMB(carat ~
cut*x*poly(depth,3) +
table + price +
(1|color) + (1|clarity),
REML=T,
data = data.frame(.))))
Warning message:
In fitTMB(TMBStruc) :
Model convergence problem; false convergence (8). See vignette('troubleshooting')
只需将tryCatch
包装在对glmmTMB
的调用周围。并编写一个error
函数。类型>>的错误消息
定时停在:0.484 0.071 0.556时间停止于:0.919 0.052 0.972计时停止于:0.542 0.04 0.583
仍会显示,但
my_boot$fit
会出现错误。
set.seed(30)
my_boot <- diamonds %>%
modelr::bootstrap(n = 20, id = 'clarity') %>%
group_by(clarity) %>%
mutate(fit = map(strap,
~tryCatch(glmmTMB(carat ~
cut*x*poly(depth,3) +
table + price +
(1|color) + (1|clarity),
REML=T,
data = data.frame(.)),
error = function(e) e)))