我在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
}
Run Code Online (Sandbox Code Playgroud)
帮助我实现这一目标
小智 6
这是定制的退出功能,看看这是否有帮助
exit <- function() {
.Internal(.invokeRestart(list(NULL, NULL), NULL))
}
f <- function() {
if (readline("Press 'q' to exit the code: ") == 'q')
exit()
return (1)
}
Run Code Online (Sandbox Code Playgroud)
或者还有另一种方法,你可以简单地停止执行,
f <- function() {
if (readline("Press 'q' to exit the code: ") == 'q')
stop("Stopping")
return (1)
}
Run Code Online (Sandbox Code Playgroud)
以及一种停止执行的新手方式,(不可取)
f <- function() {
if (readline("Press 'q' to exit the code: ") == 'q')
try{x=0/0}catch{}
return (1)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2685 次 |
| 最近记录: |