【问题标题】:Warnings in R - making noteR中的警告 - 做笔记
【发布时间】:2015-07-03 17:06:11
【问题描述】:

我正在尝试在 R 中运行一个函数 (glm) 1000 次(每次输入略有不同)。有时我会收到警告(因为发生了分离) - 我要做的就是计算这种情况发生了多少次(所以在 1000 次迭代中有多少次我收到警告“glm.fit:拟合概率为 0 或 1 发生")。

所以我的代码大致如下:

warningCount <- 0
for(i in 1:1000) {
  [generate data]
  glm(y ~ ., family="binomial", data=generated_data)
  if( I got the warning ) warningCount <- warningCount + 1
}

我只是想知道如果(我收到警告)正确地写这行。

谢谢

【问题讨论】:

    标签: r warnings


    【解决方案1】:

    您可以使用tryCatch 正确获取警告:

    lapply(1:1000, function(u){
        [generate some data]
        tryCatch(glm(y ~ ., family="binomial", data=generated_data),
                 warning = function(w) list(glm(y ~ ., family="binomial", data=generated_data), w)
    })
    

    在这里它会同时捕获警告和结果,但您只能在需要时捕获警告。

    【讨论】:

      【解决方案2】:

      我会使用tryCatch() 来捕捉、检查并根据警告采取行动。

      ## A function that randomly emits one of two warnings
      f <- function() if(runif(1) > .7) warning("Ouch") else warning("Hmmm")
      
      ## A function to catch and process warnings, adding to a global counter
      ## when one of them includes the string "Ouch"
      saidOuch <- function(w) {
          if(grepl("Ouch", as.character(w))) {ww <<- ww+1}
      }
      
      ## Run your analyses, each wrapped in a tryCatch()
      ww <- 0
      for(i in 1:100) tryCatch(f(), warning = saidOuch)
      ww
      ## [1] 32
      

      对于您的具体情况,如果您决定不处理 some other way 中的完美分离问题,您可以使用如下函数捕获和计算警告:

      perfectSeparation <- function(w) {
          if(grepl("fitted probabilities numerically 0 or 1 occurred",
                   as.character(w))) {ww <<- ww+1}
      }
      
      ## Test it with a function that will fit glm's that often emit the warning of interest
      fitglm <- function() {
          dat <- data.frame(x=rnorm(3), y=sample(0:1, 3, replace=TRUE))
          glm(y~x, data=dat, family="binomial")
      }
      ww <- 0
      for(i in 1:100) tryCatch(fitglm(), warning = perfectSeparation)
      ww
      # [1] 45
      

      【讨论】:

      • 如果运行 glm(或在您的示例中为 f)会给出两个警告,例如:“警告消息:1:[另一个警告] 2:[我正在寻找的那个]”然后 ww不会增加一 - 我试图修改它以使其确实有效,但没有任何成功。只是想知道你是否知道如何修改它,所以它仍然可以 ww
      • 也许,为了调试,在saidOuch() 的主体中调用browser(),这样你就可以直接检查警告对象w,然后玩弄你的grepl() 调用直到正确匹配?如果没有看到您的实际代码,我将无法提供更多帮助......
      • @hodgenovice -- 在仔细查看了您问题中提到的具体警告后,我修改了答案以更直接地解决它。
      猜你喜欢
      • 1970-01-01
      • 2017-02-27
      • 2019-04-26
      • 2017-09-22
      • 2016-10-16
      • 1970-01-01
      • 2022-08-20
      • 1970-01-01
      • 2022-08-24
      相关资源
      最近更新 更多