【问题标题】:Stopping R code execution upon error when run as non-interactive Rscript作为非交互式 Rscript 运行时出现错误时停止 R 代码执行
【发布时间】:2018-10-22 15:04:27
【问题描述】:

如何让 R(版本 3.4.2,CentOS 6.9)脚本在出错时停止,而不是愉快地继续?我的档案:

$ cat tmp.R
a = 9
print(a)
print(b)
print(d)
print("Should never get here")

以非交互方式运行tmp.R

$ Rscript tmp.R
Looking for libraries in : ~/.R/3.4.2-lib
[1] 9
Error in print(b) : object 'b' not found
Error in print(d) : object 'd' not found
[1] "Should never get here"

问题:如何让 R 在遇到错误时停止执行?

我尝试过 options(error=stop)options(error=browser) 之类的方法,它们适用于交互式案例,但不适用于非交互式 Rscript 示例。

【问题讨论】:

  • 在 ubuntu 上使用 R 3.2.3,您的脚本会按预期终止。是否可以在 catch 块中使用 stop() 进行 try-catch?刚刚检查了 R 3.5.1:脚本在错误之后也终止了。
  • 我不知道错误会发生在哪里,我不想在我的代码的每一行都使用 try-catch。当发生错误并导致级联错误时,它只会让我发疯。真正的错误隐藏在一堆无用的输出后面。
  • 另外,我刚刚在 CentOS 6.9 上尝试使用 R 3.2.3,得到了与上面相同的输出。如果这种行为依赖于系统,那就太愚蠢了。

标签: r


【解决方案1】:

这是因为我在我的.Rprofile 中设置了options(error=traceback)。在我的.Rprofile 中将其注释掉会导致代码在第 3 行按预期终止。这引发了为什么会产生输出的问题。查看相关问题thisthis

【讨论】:

    猜你喜欢
    • 2015-10-10
    • 1970-01-01
    • 1970-01-01
    • 2015-08-02
    • 2019-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    相关资源
    最近更新 更多