使用R执行备用cmds

时间:2014-01-02 12:44:32

标签: r cmd

在R中是否可以执行以下操作:

execute cmd1
if cmd1 generates error, proceed to:
execute cmd2

由于

3 个答案:

答案 0 :(得分:2)

try和/或tryCatch可能对您有用。考虑下面的超简单玩具示例:

#  Our function just returns it's input as long as input is not negative otherwise an error is generated
f <- function(n) {
if( n < 0 ) 
  stop("need positive integer") 
return(n)
}

# Our alternative function to run if we get an error from the first function
f2 <- function(n) return( cat( paste( "You have  a negative number which is" , n ) ) )

#  Now we try to run it with `try`:
if( class( try( f(-1) , silent = TRUE ) ) == "try-error" )
  f2(-1)
#You have  a negative number which is -1

#  And using the sophisticated `tryCatch()`  
tryCatch( f(-1) , finally = f2(-1) )
#Error in f(-1) : need positive integer
#You have  a negative number which is -1

try()的返回值是表达式的值,如果它的计算结果没有错误,否则是class "try-error"的对象。在第一个示例中,我们只是检查是否使用比较try的返回值的类生成了错误,并在生成错误时执行f2()

请注意,有很多方法可以解决这个问题,我当然不会提倡这些方法中的最佳方法,但它们应该是您了解错误处理的有用起点。

答案 1 :(得分:1)

试试这个,错误是try块中的错误信息。

tryCatch(stop(),
    error=function(err){
      print(1)
      print(err)
      })

答案 2 :(得分:1)

根据您的使用情况,即使简单的布尔运算符短路也可能就足够了。即,如果您的函数可以返回TRUE以指示无错误而FALSE指示错误,那么您可以使用||仅评估RHS操作数(如果LHS操作数)的事实评估为FALSE

> doAwesomeStuff <- function() {cat("OMG, I'm awesome! <falls flat on face>\n"); FALSE}
> okDoNormalStuff <- function() {cat("OMG, I'm OK! :-)\n"); TRUE}
> doAwesomeStuff() || okDoNormalStuff()
OMG, I'm awesome! <falls flat on face>
OMG, I'm OK! :-)
[1] TRUE

但是如果doAwesomeStuff()有效,

> doAwesomeStuff <- function() {cat("OMG, I'm awesome!\n"); TRUE}
> doAwesomeStuff() || okDoNormalStuff()
OMG, I'm awesome!
[1] TRUE
相关问题