2016-11-16 23 views
0

我正在學習R的基礎知識,我正在使用tryCatch繼續循環,即使遇到錯誤時也是如此。它基本上是這樣的:R - 將錯誤註冊爲新的變量/矢量/列

for (variableloop in (1:10000)){ 

    tryCatch({  

    My function/ formula goes here 

    },error=function(e){cat("ERROR :",conditionMessage(e), "\n")}) 
} 

我在想,如果有一個命令救了上來,其中環路提供了錯誤情況的列表。

非常感謝您的寶貴時間。

+0

你可以在捕捉部分內做一些註釋到列表中... – stats0007

+0

嗨stats0007,謝謝你的回答!我會看看。 – dena76

回答

0

你想要什麼是每次調用你的函數返回結果和錯誤,其中兩個是空的。像這樣的(使用基礎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 
+0

你好r2evans,非常感謝你! – dena76