当R中出现“警告()”时打破循环

我有一个问题:我正在运行一个循环来处理多个文件。 我的matrix是巨大的,所以如果我不小心的话,我经常会记忆犹新。

如果有任何警告被创build,有没有办法摆脱循环? 它只是继续运行循环,并报告说,它失败了很多晚…烦人。 任何想法哦智慧stackoverflow-ers?

您可以将警告转化为以下错误:

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 

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 

设置全局warn选项:

 options(warn=1) # print warnings as they occur options(warn=2) # treat warnings as errors 

请注意,“警告”不是“错误”。 循环不会终止警告(除非options(warn=2) )。