【问题标题】:How to use tryCatch() during bootstrapping with modelr/tidyverse?如何在使用 modelr/tidyverse 引导期间使用 tryCatch()?
【发布时间】:2020-05-29 17:02:00
【问题描述】:

这个问题类似于Using tryCatch() to catch a bootstrap loop,但我在使用 tidyverse 引导方法将建议应用到我的案例时遇到了麻烦。我正在尝试从复杂的混合效应模型中获取系数的置信区间估计值,但是某些模型在引导过程中失败,从而停止了整个引导过程。我想忽略这些失败的运行(但也计算并存储它们以知道它们是什么)并继续引导。我也愿意接受使用带有 tryCatch 的引导包的建议。使用 diamonds 数据集的示例:

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

【问题讨论】:

    标签: r tidyverse hierarchical-clustering statistics-bootstrap


    【解决方案1】:

    只需将tryCatch 包裹在对glmmTMB 的调用周围。并编写error 和warning 函数。类型的错误信息

    时间停止在: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,
                                warning = function(w) w)))
    

    然后您可以使用

    检查结果
    err <- sapply(my_boot$fit, inherits, "error")
    warn <- sapply(my_boot$fit, inherits, "warning")
    ok <- !(err | warn)
    

    并使用这些向量对列表my_boot 进行子集化。例如:

    my_boot[ok]
    

    err 和 warn 也是如此。

    【讨论】:

      猜你喜欢
      • 2013-04-02
      • 1970-01-01
      • 2017-07-02
      • 2014-09-08
      • 2017-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-06
      相关资源
      最近更新 更多