R在错误情况下执行tryCatch

Kin*_*ist 2 error-handling r try-catch

在R中使用tryCatch时是否有可能在出错的情况下执行某些命令?我正在使用下面的代码,但它不执行X = Alternative_value

tryCatch(
{
  X = certain_function_that_sometimes_returns_error      
},
error=function(e) {
  X = alternative_value
})
Run Code Online (Sandbox Code Playgroud)

Sym*_*xAU 7

tryCatch直接将您分配给x

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

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

x
# [1] "world"
Run Code Online (Sandbox Code Playgroud)