Jos*_*ien 142
您可以通过以下方式将警告变为错误:
options(warn=2)
Run Code Online (Sandbox Code Playgroud)
与警告不同,错误会中断循环.很好,R还会向您报告这些特定错误是从警告转换而来的.
j <- function() {
for (i in 1:3) {
cat(i, "\n")
as.numeric(c("1", "NA"))
}}
# warn = 0 (default) -- warnings as warnings!
j()
# 1
# 2
# 3
# Warning messages:
# 1: NAs introduced by coercion
# 2: NAs introduced by coercion
# 3: NAs introduced by coercion
# warn = 2 -- warnings as errors
options(warn=2)
j()
# 1
# Error: (converted from warning) NAs introduced by coercion
Run Code Online (Sandbox Code Playgroud)
Mar*_*gan 41
R允许您定义条件处理程序
x <- tryCatch({
warning("oops")
}, warning=function(w) {
## do something about the warning, maybe return 'NA'
message("handling warning: ", conditionMessage(w))
NA
})
Run Code Online (Sandbox Code Playgroud)
结果
handling warning: oops
> x
[1] NA
Run Code Online (Sandbox Code Playgroud)
tryCatch后继续执行; 您可以决定通过将警告转换为错误来结束
x <- tryCatch({
warning("oops")
}, warning=function(w) {
stop("converted from warning: ", conditionMessage(w))
})
Run Code Online (Sandbox Code Playgroud)
或优雅地处理条件(警告电话后继续评估)
withCallingHandlers({
warning("oops")
1
}, warning=function(w) {
message("handled warning: ", conditionMessage(w))
invokeRestart("muffleWarning")
})
Run Code Online (Sandbox Code Playgroud)
打印
handled warning: oops
[1] 1
Run Code Online (Sandbox Code Playgroud)
Jos*_*ich 25
设置全局warn
选项:
options(warn=1) # print warnings as they occur
options(warn=2) # treat warnings as errors
Run Code Online (Sandbox Code Playgroud)
请注意,"警告"不是"错误".循环不会因警告而终止(除非options(warn=2)
).