3 回答

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超8個(gè)贊
也許這與你的解決方案相同,但我寫了一個(gè)factory
將普通舊函數(shù)轉(zhuǎn)換為捕獲它們的值,錯(cuò)誤和警告的函數(shù),所以我可以
test <- function(i) switch(i, "1"=stop("oops"), "2"={ warning("hmm"); i }, i)res <- lapply(1:3, factory(test))
結(jié)果的每個(gè)元素都包含值,錯(cuò)誤和/或警告。這適用于用戶功能,系統(tǒng)功能或匿名功能(factory(function(i) ...)
)。這是工廠
factory <- function(fun) function(...) { warn <- err <- NULL res <- withCallingHandlers( tryCatch(fun(...), error=function(e) { err <<- conditionMessage(e) NULL }), warning=function(w) { warn <<- append(warn, conditionMessage(w)) invokeRestart("muffleWarning") }) list(res, warn=warn, err=err) }
和一些幫助處理結(jié)果列表
.has <- function(x, what) !sapply(lapply(x, "[[", what), is.null)hasWarning <- function(x) .has(x, "warn")hasError <- function(x) .has(x, "err")isClean <- function(x) !(hasError(x) | hasWarning(x))value <- function(x) sapply(x, "[[", 1)cleanv <- function(x) sapply(x[isClean(x)], "[[", 1)

TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超8個(gè)贊
試試評估包。
library(evaluate)test <- function(i) switch(i, "1"=stop("oops"), "2"={ warning("hmm"); i }, i)t1 <- evaluate("test(1)")t2 <- evaluate("test(2)")t3 <- evaluate("test(3)")
它目前缺乏評估表達(dá)式的好方法 - 這主要是因?yàn)樗哪繕?biāo)是在控制臺(tái)上準(zhǔn)確再現(xiàn)R輸出的給定文本輸入。
replay(t1)replay(t2)replay(t3)
它還捕獲消息,輸出到控制臺(tái),并確保所有內(nèi)容按照發(fā)生的順序正確交錯(cuò)。

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超8個(gè)贊
主要思想是同時(shí)保留警告/錯(cuò)誤消息以及觸發(fā)此問題的命令。
myTryCatch <- function(expr) { warn <- err <- NULL value <- withCallingHandlers( tryCatch(expr, error=function(e) { err <<- e NULL }), warning=function(w) { warn <<- w invokeRestart("muffleWarning") }) list(value=value, warning=warn, error=err)}
例子:
myTryCatch(log(1))myTryCatch(log(-1))myTryCatch(log("a"))
輸出:
> myTryCatch(log(1))
$ value [1] 0 $ warning NULL $ error NULL
> myTryCatch(log(-1))
$ value [1] NaN $警告$ error NULL
> myTryCatch(log(“a”))
$ value NULL $ warning NULL $ error
- 3 回答
- 0 關(guān)注
- 715 瀏覽
添加回答
舉報(bào)