中断正在运行的R脚本的什么函数?



我是r的初学者,我希望能够中断当前运行的脚本,如果条件为真。我发现最接近的是ps_kill函数,它会使Rstudio崩溃。

df <- data.frame(one = c(1,2,NA,4,NA), two = c(NA,NA,8,NA,10))
if (sum(is.na(df)) > 3)
{
ps_kill(p = ps_handle())
}

是否有一个功能,我可以用它来代替ps_kill,中断脚本而不崩溃Rstudio ?

如果您使用Rscript或source运行它,stop函数将抛出错误并有效地终止脚本。但请记住,这将以错误结束。例如:

# A function that will throw an error and quit
test <- function() {
print("This is printed")
stop()
print("this is not printed")
}
test()

请注意,您可以通过将错误抛出代码包装在try调用中来恢复错误抛出代码:

# This will not throw an error and will not print the second sentence
try(test(), silent = TRUE)

如果你真的想关闭R而不是完成你的脚本,另一个解决方案是使用q函数。这是不可恢复的(它将关闭R会话)。

我希望这能回答你的问题!

如果调用stop()函数将返回一个错误,因此您可以使用它。唯一的技巧是,如果你在交互模式下使用它,你需要把你想跳过的所有代码用大括号括起来,例如

df <- data.frame(one = c(1,2,NA,4,NA), two = c(NA,NA,8,NA,10))
{
if(sum(is.na(df)) > 3) stop("More than three NAs")
print("don't run this")
}
# Error: More than three NAs

注意大括号包括打印行,否则stop将只继续运行导致错误的行之后的代码,例如

if(sum(is.na(df)) > 3) stop("More than three NAs")
# Error: More than three NAs
print("don't run this")
# [1] "don't run this"

如果你有长时间运行的代码,你可以尝试在R studio控制台面板右上方的'Stop'按钮。

如下截图所示。https://prnt.sc/1txafh0

希望这是你正在寻找的!

如果你在交互模式下运行(就像你在评论中说的),stopApp应该终止进程而不会产生错误。

最新更新