我如何 stop/end/halt R 中的脚本?

How do I stop/end/halt a script in R?

我写了一个脚本,如果提供的数据不正确,它应该停止执行。然而,尽管 stop 产生错误消息,脚本仍然继续。一个最小的例子:

if (TRUE) {stop("End of script?")} #It should stop here
print("Script did NOT end!") # but it doesn't, because this line is printed!

控制台输出:

> if (TRUE) {stop("End of script?")}
Error: End of script?
> print("Script did NOT end!")
[1] "Script did NOT end!"
>

这其实并不奇怪,因为来自?stop

stops execution of the current expression and executes an error action.

所以它只结束当前表达式,而不是脚本。我发现 here 您可以将 {} 包裹在整个脚本中(或将其放入函数中),但这似乎是一种变通方法而不是解决方案。当然,捕获错误并自行处理它们是一种很好的编程习惯(例如,参见 mra68 评论中的 link),但我仍然想知道我是否可以在 R 中停止脚本。

我也试过returnbreak,但这只适用于函数或循环。我搜索了其他可能的关键字,如 "halt" 和 "end",但没有成功。我感觉有点傻,因为这似乎是一个很基础的问题。

那么,是否有一个命令可以使我的脚本 halt/stop/end 出现致命错误?

我是 运行 Windows 8 上的 R 3.2.3,但在 MAC-OSX 上遇到与 R 3.0.1 相同的问题。

> sessionInfo()
R version 3.2.3 (2015-12-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

locale:
[1] LC_COLLATE=Dutch_Netherlands.1252  LC_CTYPE=Dutch_Netherlands.1252    LC_MONETARY=Dutch_Netherlands.1252
[4] LC_NUMERIC=C                       LC_TIME=Dutch_Netherlands.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] tools_3.2.3

测试 MAC-OS,sessionInfo()

R version 3.0.1 (2013-05-16)
Platform: x86_64-apple-darwin10.8.0 (64-bit)

locale:
[1] nl_NL.UTF-8/nl_NL.UTF-8/nl_NL.UTF-8/C/nl_NL.UTF-8/nl_NL.UTF-8

据我所知,没有一个命令 真正在每个 platform/version 上停止脚本。有几种方法可以解决这个问题:

放在函数或大括号中:

{
if (TRUE) {stop("The value is TRUE, so the script must end here")}

print("Script did NOT end!")
}

或评估错误并像在 if else 构造中一样处理它:

if (TRUE) {stop("The value is TRUE, so the script must end here")    
  } else { #continue the script
print("Script did NOT end!")   
  }

或(编辑): 另一种可能性是从单独的 'main' R-scipt 和 source("MyScript.R") 调用脚本。然后脚本终止。然而,这会抑制所有输出到控制台的错误。

或者对于更复杂的操作,使用 tryCatch() 如图所示 here

也许有点晚了,但我最近遇到了同样的问题,发现对我来说最简单的解决方案是使用:

quit(save="ask")

?quit可以看出:

save must be one of "no", "yes", "ask" or "default". In the first case the workspace is not saved, in the second it is saved and in the third the user is prompted and can also decide not to quit. The default is to ask in interactive use but may be overridden by command-line arguments (which must be supplied in non-interactive use).

当消息框弹出时,您可以通过单击 "cancel" 来决定不退出 R。

希望对您有所帮助!

很简单:调用一个没有声明的函数:

condition <- TRUE
if (condition) {
  print('Reason for stopping')
  UNDECLARED()
}

脚本将停止并显示消息:

[1] "Reason for stopping"
Error in UNDECLARED() : could not find function "UNDECLARED"

请注意,在 RStudio 中

stop("Error message")

调用实际上是在打印错误信息后停止了脚本的执行。