如何在 R 中退出(0)?
How to exit(0) in R?
我在 RStudio 工作,当函数满足特定条件时,我需要从函数内部退出我的代码(但不是 RStudio 会话),例如一个按键。在 C/c++ 中,我们使用 exit(0)
函数来做到这一点。在 R 中,如果我调用 quit()
,它会尝试为我关闭整个 R 会话,但我只需要停止从我的函数内部执行当前编码。
即我正在寻找如下所示的功能,当用户输入 'q'.
时,它会导致程序退出
f <- function() {
if (readline("Press 'q' to exit the code: ") == 'q')
#I want to terminate the execution of program here
else
#continue the execution of other set of commands
}
帮我实现这个
这是自定义的退出函数,看看是否有帮助
exit <- function() {
.Internal(.invokeRestart(list(NULL, NULL), NULL))
}
f <- function() {
if (readline("Press 'q' to exit the code: ") == 'q')
exit()
return (1)
}
或者还有另一种方法可以简单地停止执行,
f <- function() {
if (readline("Press 'q' to exit the code: ") == 'q')
stop("Stopping")
return (1)
}
还有一个菜鸟停止执行的方法,(不可取)
f <- function() {
if (readline("Press 'q' to exit the code: ") == 'q')
try{x=0/0}catch{}
return (1)
}
我在 RStudio 工作,当函数满足特定条件时,我需要从函数内部退出我的代码(但不是 RStudio 会话),例如一个按键。在 C/c++ 中,我们使用 exit(0)
函数来做到这一点。在 R 中,如果我调用 quit()
,它会尝试为我关闭整个 R 会话,但我只需要停止从我的函数内部执行当前编码。
即我正在寻找如下所示的功能,当用户输入 'q'.
时,它会导致程序退出 f <- function() {
if (readline("Press 'q' to exit the code: ") == 'q')
#I want to terminate the execution of program here
else
#continue the execution of other set of commands
}
帮我实现这个
这是自定义的退出函数,看看是否有帮助
exit <- function() {
.Internal(.invokeRestart(list(NULL, NULL), NULL))
}
f <- function() {
if (readline("Press 'q' to exit the code: ") == 'q')
exit()
return (1)
}
或者还有另一种方法可以简单地停止执行,
f <- function() {
if (readline("Press 'q' to exit the code: ") == 'q')
stop("Stopping")
return (1)
}
还有一个菜鸟停止执行的方法,(不可取)
f <- function() {
if (readline("Press 'q' to exit the code: ") == 'q')
try{x=0/0}catch{}
return (1)
}