2017-04-12 126 views
1

在R中使用tryCatch時,是否可以執行某些命令以防出錯?我使用下面的代碼,但它不執行X = alternative_valueR中tryCatch在出錯時執行

tryCatch(
{ 
    X = certain_function_that_sometimes_returns_error  
}, 
error=function(e) { 
    X = alternative_value 
}) 

回答

2

將您的tryCatch直接x

foo <- function() stop("hello") 
bar <- function() 'world' 

x <- tryCatch(
    { 
     foo() 
    }, 
    error = function(e){ 
     bar() 
    } 
) 

x 
# [1] "world"