发生错误时在R中执行tryCatch [英] tryCatch in R execute in case of error

查看:62
本文介绍了发生错误时在R中执行tryCatch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
})

推荐答案

直接将您的 tryCatch 分配给 x

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

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

x
# [1] "world"

这篇关于发生错误时在R中执行tryCatch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆