在 RStudio 中执行代码块时,执行实际上不会在发生错误时停止。例如,如果我在打开的编辑器中有以下代码:
x <- 'test'
stopifnot(is.numeric(x))
print('hello world')
然后运行它(使用 command-return 或单击“运行”按钮),它会打印错误,然后继续执行打印语句。
有没有办法将 RStudio 配置为不继续处理错误?即让它停在上面的第 2 行而不继续打印语句?
编辑:刚刚意识到,如果我使用 command-R 在标准 R GUI 中发送代码块,也会发生这种情况。
最佳答案
解决此问题的一种方法是配置 R 'error'
选项以在遇到错误时运行自定义函数。
错误处理函数示例可以使用 Sys.sleep
暂停 R 的执行并等待用户输入(例如,通过按 ctrl-C 或 R 中的 Escape 中断正在运行的函数-我的 Mac 上的工作室)。
通常,R 会继续执行任何后续命令。但是,我们可以通过定义一个函数来防止这种情况发生,该函数将“吃掉”所有这些,这样它们就不会运行。为了让这个更流畅,我们可以在每个“吃掉”行之后输出一个“光标向上”字符序列,这会在下一个输出时删除它们中的每一个,这样未运行的行就不会弄乱终端/控制台。
示例代码:
# Define our error-handling pause function:
pause=function(){
on.exit(eat_input())
cat("Paused: press ctrl-C (or Escape key in Rstudio) to continue\n")
cat("(any subsequent code will be ignored)\n")
Sys.sleep(Inf)
}
# Define our 'eat_input' function to prevent output of subsequent, not-run input:
eat_input=function(){
cat("\033[1A")
while((x=readline())!='')cat("\033[1A")
}
# Set the 'error' option to execute our pause function:
options(error=pause)
尝试一下:
print("Before the error")
# an error: we want to stop after this
xxx
# some more input: we don't want this to be run or to appear in the console
print("After the error")
要关闭此行为,只需将错误选项重新设置为 NULL
:
options(error=NULL)
关于r - 在 RStudio/Interactive R session 中出错时停止执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42256291/