当我在 R 脚本中选择几行代码并运行它时,RStudio 会顺利"运行所有代码,即使中间部分有一些警告和错误.因此,我必须仔细检查控制台"窗口,并查看是否有任何红线.这真的很耗时,我可能会错过错误.当出现错误或警告时,有什么方法可以使运行停止?
When I select several lines of codes in a R script, and run it, RStudio will "smoothly" run all of the codes, even though there are some warnings and errors in the middle part. As a result, I have to carefully check the "Console" window, and to see whether there is any red lines. This is really time consuming and I may miss the errors. Are there some ways to make the running stop, when error or warning occurs?
推荐答案RStudio 当前的工作方式是将所选文本粘贴到控制台中.它不在乎其中是否有错误.更好的方法是获取文本并获取它的来源.
RStudio currently works by pasting the selected text into the console. It doesn't care if there are errors in it. A better approach would be to get the text and source it.
您可以使用
selected <- rstudioapi::getSourceEditorContext()$selection[[1]]$text如果您获取此文本而不是粘贴它,它将在第一个错误处停止.这样做使用
If you source this text instead of pasting it, it will stop at the first error. Do that using
source(exprs = parse(text = selected), echo = TRUE)另一种方法是将文本复制到剪贴板,然后从那里获取.我认为 RStudio 目前没有办法做到这一点,但您可以添加一个.
Another way to go would be to copy the text into the clipboard, then sourcing it from there. I don't think RStudio currently has a way to do that, but you can add one.
此函数在 Windows 和 MacOS 上从剪贴板读取;我不确定 pbpaste 在 Linux 上是否普遍可用,但那里应该有一些等价物:
This function reads from the clipboard on Windows and MacOS; I'm not sure if pbpaste is generally available on Linux, but there should be some equivalent there:
readClipboard <- function() { if (.Platform$OS.type == "windows") lines <- readLines("clipboard") else lines <- system("pbpaste", intern=TRUE) lines }此代码从剪贴板中获取文本:
This code sources the text from the clipboard:
source(exprs = parse(text = readClipboard()), echo = TRUE)您可以将这些操作中的任何一个作为加载项放在 RStudio 中的热键上.说明如下:rstudio.github.io/rstudioaddins/.
You could put either of these actions on a hot key in RStudio as an add-in. Instructions are here: rstudio.github.io/rstudioaddins/.
上述建议仅在出现错误时停止.如果您还想停止警告,请使用 options(warn = 2) 正如@FransRodenburg 所说.
The advice above only stops on errors. If you want to also stop on warnings, use options(warn = 2) as @FransRodenburg said.
更多推荐
遇到错误或警告时如何使RStudio停止
发布评论