我使用lapply
在大量項目上運行一個複雜的函數,並且我想將每個項目的輸出(如果有)與任何生成的警告/錯誤一起保存,以便我可以告訴哪個項目項目產生了哪個警告/錯誤。如何將警告和錯誤保存爲函數的輸出?
我發現了一種使用withCallingHandlers
來捕獲警告的方法(這裏描述:https://stackoverflow.com/questions/4947528)。不過,我也需要發現錯誤。我可以通過將它包裝在tryCatch
(如下面的代碼中)來做到,但是有沒有更好的方法來做到這一點?這個功能的
catchToList <- function(expr) {
val <- NULL
myWarnings <- NULL
wHandler <- function(w) {
myWarnings <<- c(myWarnings, w$message)
invokeRestart("muffleWarning")
}
myError <- NULL
eHandler <- function(e) {
myError <<- e$message
NULL
}
val <- tryCatch(withCallingHandlers(expr, warning = wHandler), error = eHandler)
list(value = val, warnings = myWarnings, error=myError)
}
示例輸出:
> catchToList({warning("warning 1");warning("warning 2");1})
$value
[1] 1
$warnings
[1] "warning 1" "warning 2"
$error
NULL
> catchToList({warning("my warning");stop("my error")})
$value
NULL
$warnings
[1] "my warning"
$error
[1] "my error"
這裏有幾個問題上,以便討論tryCatch
和錯誤處理,但沒有我發現地址這一具體問題。最相關的參見How can I check whether a function call results in a warning?,warnings() does not work within a function? How can one work around this?和How to tell lapply to ignore an error and process the next thing in the list?。
是的,相同的想法,但更好!你有沒有考慮把它包裝成一個包?從我在這裏看到的其他問題來看,其他人也會覺得這很有用。 – Aaron 2011-02-10 05:35:30
我有一個函數將其調用存儲在輸出中。調用`工廠'後,該呼叫被改變,例如, `fun(公式= .1,data =。2,method =「genetic」,ratio = .4, print.level = 0)`,其中`formula`應該是我的原始輸入公式,但會被覆蓋。有小費嗎? – 2012-02-25 13:15:51