我正在尝试使用tryCatch
返回评估的表达式以及它生成的警告。我也想这样做,而无需两次评估表达式。
这是一个非常简单的示例:
x <- -1
info <- tryCatch(sqrt(x),
error = function(e) e
warning = function(w) w)
在这里
info
最终被捕获为警告,在这里我也想得到NaN
产生的sqrt(x)
。这个应用程序是我适合的模型,我想知道弹出的警告是什么,但我也只想评估一次模型。如果可以两次拟合,可以检查信息是否为警告,然后重新进行拟合,但是两次拟合模型是禁止的。
最佳答案
请参阅demo(error.catching)
,其中提供以下内容
##' Catch *and* save both errors and warnings, and in the case of
##' a warning, also keep the computed result.
##'
##' @title tryCatch both warnings (with value) and errors
##' @param expr an \R expression to evaluate
##' @return a list with 'value' and 'warning', where
##' 'value' may be an error caught.
##' @author Martin Maechler;
##' Copyright (C) 2010-2012 The R Core Team
tryCatch.W.E <- function(expr)
{
W <- NULL
w.handler <- function(w){ # warning handler
W <<- w
invokeRestart("muffleWarning")
}
list(value = withCallingHandlers(tryCatch(expr, error = function(e) e),
warning = w.handler),
warning = W)
}
在你的例子中
tryCatch.W.E(sqrt(-1))
#> $value
#> [1] NaN
#>
#> $warning
#> <simpleWarning in sqrt(-1): NaNs produced>
关于r - 使用tryCatch保存引发警告的对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32076454/