在Rstudio中使用什么而不是停止?

时间:2017-05-02 02:31:30

标签: r function rstudio

我想知道当用户输入' bad'参数,我的函数可以在一个图中发送文本(参见我下面的R代码),停止进一步处理(即 除了消息之外没有生成输出 ),但不会崩溃(stop的行为方式)?

例如,当b不大于a时,是否有一种方法,只绘制一条消息并停止进一步处理而不使用导致页面崩溃的stop

这是我的R代码:

 GGG = function(a, b){

 if(b > a) { c = b - a    ## Necessary condition to be met ! 

  } else {

  plot(1, axes = F, ty = 'n', ann = F)  ## Text Message to be plotted 

  text(1, 1, "Unable to process this setting", cex = 2, col = 'red4', font = 2) 

  stop("b must be larger than a" )      ## This just crashes the R studio  

     }

 d =  c / 100     ## this should NOT run in this example because b < a in my example

 return(d)

}

GGG (a = 3, b = 2)  ## b < a, thus function should just plot message  

1 个答案:

答案 0 :(得分:0)

您可以使用return()返回&#34;没有&#34; (即NULL)来自该函数,并使用warning()代替stop(),因此它不会崩溃&#39;功能

GGG = function(a, b){

    if(b > a) { 
        c = b - a    ## Necessary condition to be met ! 
    } else {

        plot(1, axes = F, ty = 'n', ann = F)  ## Text Message to be plotted 
        text(1, 1, "Unable to process this setting", cex = 2, col = 'red4', font = 2) 
        # warning("b must be larger than a" ) 
        # return()
        return(message("b must be larger than a" ))
    }

    d =  c / 100 

    return(d)
}