从R中的子项停止执行父函数

时间:2015-09-02 16:14:47

标签: r function break

我正在使用R中的stop函数来制定一些故障排除措施。例如,输入数据错误时抛出错误。我想要一个我可以调用来执行此检查的通用函数,然后我可以调用父代码的几个不同点。我可以抛出一个错误,但是,我注意到在抛出错误后父函数继续执行,只有我的“错误函数”,如果你将停止执行。当stop出现错误时,有没有办法让R停止全局执行?

谢谢。

我的问题的编码示例:

StopCode <- function() {

  try(if(TRUE) stop("This try/if statement should stop the code from executing."))

}

StopCode() # This function should stop the code!

print("I should not see this statement if the try/if statement stopped the code in the way I desired.")

控制台:

Error in try(if (TRUE) stop("This try/if statement should stop the code from executing.")) : 
  This try/if statement should stop the code from executing.
[1] "I should not see this statement if the try/if statement stopped the code in the way I desired."

期望的结果应该是StopCode函数完全停止代码而不是仅执行函数。当您获取此代码时,它会停止该功能,发出警告,然后继续运行打印功能。我希望这不会发生,并且在函数中停止全局终止执行。

2 个答案:

答案 0 :(得分:2)

默认情况下,stop完全按照您的要求执行:它会突破每个正在运行的函数,直到它处于顶层 - 并且,如果脚本以非交互方式运行,则会停止脚本。

但是,在您发布的代码中,通过try捕获错误,明确告诉R 停止执行调用函数。目前还不清楚你在这里使用try的原因,因为它的唯一目的是防止你似乎想要的行为。

解决方案只是从代码中删除try。或者,您可能想要捕获错误,处理它,然后重新抛出它:

result = try(‹some operation that may fail›)
if (inherits(result, 'try-error')) {
    ‹handle error›
    # Re-throw error:
    stop(attr(result, 'condition'))
}

答案 1 :(得分:0)

基本上,您希望将选项(error =)设置为您选择的某个功能。我会在这里粘贴文档吗?选项:

error:
either a function or an expression governing the handling of non-catastrophic
errors such as those generated by stop as well as by signals and internally
detected errors. If the option is a function, a call to that function, with
no arguments, is generated as the expression. The default value is NULL: see
stop for the behaviour in that case. The functions dump.frames and recover
provide alternatives that allow post-mortem debugging. Note that these need 
to specified as e.g. options(error = utils::recover) in startup files such
as ‘.Rprofile’.