2011-11-21 64 views
67

我遇到問題: 我正在運行一個循環來處理多個文件。我的矩陣是巨大的,因此如果我不小心的話,我經常會記憶猶新。當「警告()」出現在R中時出現斷路

如果有任何警告被創建,有沒有辦法擺脫循環?它只是繼續運行循環,並報告說,它失敗了很多晚...煩人。任何想法哦智慧stackoverflow-ers?!

回答

104

您可以打開警告變爲錯誤有:

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 
+13

之後,使用'選項(警告= 1)'恢復默認設置。 –

+13

雖然默認值是0。所以要恢復_factory設置_使用'選項(「warn」= 0)'。 –

17

設置全局warn選項:

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

注意, 「警告」 不是一個 「錯誤」。循環不會因警告而終止(除非options(warn=2))。

31

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 
+0

+1 - 非常好。我曾經想過提及這個選項,但是不可能把這樣一個簡短但甜美的教程放在一起。 –

+0

有一個很好的'for'的演示會更好:) –