tryCatch in R execute in case of error

陌路散爱 提交于 2021-02-07 19:41:54

问题


Is it possible to execute certain commands in case of error when using tryCatch in R ? I am using the code below but it does not execute X = alternative_value

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

回答1:


Assign your tryCatch directly to x

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

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

x
# [1] "world"


来源:https://stackoverflow.com/questions/43380908/trycatch-in-r-execute-in-case-of-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!