Answers:
您可以使用以下方法将警告变为错误:
options(warn=2)
与警告不同,错误会中断循环。很好,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
options("warn"=0)
。
op=options(warn=2)
,2)执行您的事情然后3)用重置来最好地处理,在这种情况下options(op)
,您可以返回warn=0
。
R允许您定义条件处理程序
x <- tryCatch({
warning("oops")
}, warning=function(w) {
## do something about the warning, maybe return 'NA'
message("handling warning: ", conditionMessage(w))
NA
})
导致
handling warning: oops
> x
[1] NA
在tryCatch之后执行继续;您可以通过将警告转换为错误来决定结束
x <- tryCatch({
warning("oops")
}, warning=function(w) {
stop("converted from warning: ", conditionMessage(w))
})
或优雅地处理条件(警告呼叫后继续评估)
withCallingHandlers({
warning("oops")
1
}, warning=function(w) {
message("handled warning: ", conditionMessage(w))
invokeRestart("muffleWarning")
})
哪个打印
handled warning: oops
[1] 1
for
甚至会更好:)
设置全局warn
选项:
options(warn=1) # print warnings as they occur
options(warn=2) # treat warnings as errors
请注意,“警告”不是“错误”。循环不会因警告而终止(除非options(warn=2)
)。
options(warn=1)
来恢复默认设置。