2014-10-07 107 views
1

我一直在閱讀關於如何使用tryCatch的SO的答案。我真的不明白c變量來自哪裏。'e'或'c'來自R的tryCatch

例如(通過http://adv-r.had.co.nz/Exceptions-Debugging.html#condition-handling

show_condition <- function(code) { 
    tryCatch(code, 
    error = function(c) "error", 
    warning = function(c) "warning", 
    message = function(c) "message" 
) 
} 
show_condition(stop("!")) 
#> [1] "error" 
show_condition(warning("?!")) 
#> [1] "warning" 
show_condition(message("?")) 
#> [1] "message" 

# If no condition is captured, tryCatch returns the 
# value of the input 
show_condition(10) 
#> [1] 10 

c是一個系統變量? Elsewhere其他人似乎使用e在其位置?

+1

'C'是意義和時間花費打字之間的平衡。我使用'e'來處理錯誤,'w'使用警告。 – 2014-10-07 13:49:38

回答

3

在您的代碼中,function(c) "error"只是一個匿名函數,在tryCatch運行時,如果其參數code引發錯誤。

condition類的參數傳遞給該匿名函數,它可以讓你得到那個引發錯誤的call,和R.產生例如,message

R> tryCatch(print(foobar), error=function(c) print(c$message)) 
[1] "objet 'foobar' introuvable" 

因此,c這裏只是你給condition作爲參數傳遞的名字,你可以給它任何你想要的名字:c,e甚至deliciouspizza

例如:

R> tryCatch(print(foobar), error=function(rcatladies) print(rcatladies$call)) 
print(foobar) 
+0

謝謝。所以這一切都取決於最初的函數創建(或返回 - 我的術語可能是錯誤的)適當的類的論點。如果我使用我自己的函數(並且不夠聰明以返回這樣的參數),tryCatch方法會失敗嗎? – drstevok 2014-10-07 14:45:53

+0

@drstevok嗯不,不取決於你的初始功能。匿名函數在出現錯誤,警告,消息等情況下由'tryCatch'調用。它是'tryCatch',它創建'condition'參數並將其傳遞給您定義的匿名函數。不知道我在這裏真的很清楚...... – juba 2014-10-07 14:49:00

+0

不,這有幫助...我認爲這是我感到困惑的地方。我無法弄清楚「條件」論點來自哪裏。 – drstevok 2014-10-07 15:14:56