【问题标题】:How to exit(0) in R? [closed]如何在 R 中退出(0)? [关闭]
【发布时间】:2017-06-24 01:42:37
【问题描述】:

我在 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
 }

帮我实现这个目标

【问题讨论】:

标签: r exit


【解决方案1】:

这是自定义退出功能,看看有没有帮助

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 会话。
  • 如果可行,请为答案投票。干杯
  • exit 函数在使用 R3.5.1 时为我生成一个非零退出
猜你喜欢
  • 1970-01-01
  • 2015-02-26
  • 2016-02-17
  • 1970-01-01
  • 1970-01-01
  • 2014-07-18
  • 2013-11-21
  • 2020-05-06
  • 2020-10-13
相关资源
最近更新 更多