你想要什麼是每次調用你的函數返回結果和錯誤,其中兩個是空的。像這樣的(使用基礎R)一句:
# bigger loop than this ...
input <- 1:5
myfunc <- function(ign) if ((x <- runif(1)) < 0.2) stop(paste0("some error: ", x)) else x
set.seed(2)
ret <- lapply(input, function(i) {
tryCatch(list(result = myfunc(i), error = NA),
error = function(e) list(result = NA, error = e))
})
str(ret)
# List of 5
# $ :List of 2
# ..$ result: logi NA
# ..$ error :List of 2
# .. ..$ message: chr "some error: 0.18488225992769"
# .. ..$ call : language myfunc(i)
# .. ..- attr(*, "class")= chr [1:3] "simpleError" "error" "condition"
# $ :List of 2
# ..$ result: num 0.702
# ..$ error : logi NA
# $ :List of 2
# ..$ result: num 0.573
# ..$ error : logi NA
# $ :List of 2
# ..$ result: logi NA
# ..$ error :List of 2
# .. ..$ message: chr "some error: 0.168051920365542"
# .. ..$ call : language myfunc(i)
# .. ..- attr(*, "class")= chr [1:3] "simpleError" "error" "condition"
# $ :List of 2
# ..$ result: num 0.944
# ..$ error : logi NA
您可以存取(可能爲空),用錯誤:
str(lapply(ret, `[[`, "error"))
# List of 5
# $ :List of 2
# ..$ message: chr "some error: 0.18488225992769"
# ..$ call : language myfunc(i)
# ..- attr(*, "class")= chr [1:3] "simpleError" "error" "condition"
# $ : logi NA
# $ : logi NA
# $ :List of 2
# ..$ message: chr "some error: 0.168051920365542"
# ..$ call : language myfunc(i)
# ..- attr(*, "class")= chr [1:3] "simpleError" "error" "condition"
# $ : logi NA
您還可以使用purrr
包:
set.seed(2)
ret <- lapply(input, function(i) {
purrr::safely(myfunc)(i)
})
str(lapply(ret, `[[`, "error"))
# List of 5
# $ :List of 2
# ..$ message: chr "some error: 0.18488225992769"
# ..$ call : language .f(...)
# ..- attr(*, "class")= chr [1:3] "simpleError" "error" "condition"
# $ : NULL
# $ : NULL
# $ :List of 2
# ..$ message: chr "some error: 0.168051920365542"
# ..$ call : language .f(...)
# ..- attr(*, "class")= chr [1:3] "simpleError" "error" "condition"
# $ : NULL
你可以在捕捉部分內做一些註釋到列表中... – stats0007
嗨stats0007,謝謝你的回答!我會看看。 – dena76