遇到错误或警告时如何使RStudio停止

编程入门 行业动态 更新时间:2024-10-27 22:32:37
本文介绍了遇到错误或警告时如何使RStudio停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当我在 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停止

本文发布于:2023-10-16 00:44:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1495975.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   RStudio

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!