从R中的嵌套块中断/退出而不打印错误消息

时间:2016-03-19 09:12:50

标签: r control-flow

我一直在编写一个R脚本来模拟来自呼叫中心的出站电话以演示规则(如果呼叫计数超过5或者如果呼叫成功或者设置了回叫请求,那么代码应退出)。如果我使用break语句,我没有得到所需的结果,作为我使用stop函数的解决方法。有没有办法打印消息并停止执行函数而不抛出错误? 这是我的代码:

dial <- function(callcount = 1)
{
  maxcalls <- 5
  # Possible Outcomes
  outcomes <- c("RPCON","WPCON","CBLTR")
  # Probaility Vector for results:
  pvector <- c(1,1,1)

  repeat{
    if(callcount == 5){
      stop("5 attempts reached, closing record for the day")
      }
    res <- sample(outcomes, 1, prob=pvector, rep = TRUE)
    print(paste0("Attempt ",callcount))
  if(res == "RPCON" & callcount <= 5){
    print("Call Successful")
    stop(simpleError("Ended"))
  }else if(res == "WPCON" & callcount <= 5){
    print("Wrong Party!, Trying alternate number...")
    callcount <- callcount + 1
    dial(callcount)
  }else if(res == "CBLTR" & callcount <= 5){
    print("Call back request set by agent")
    stop("Ended")
  }
}# End of REPEAT loop

}# End of function

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我建议使用带有布尔值的While循环来检查是否要继续循环:

dial <- function(callcount = 1)
{
  maxcalls <- 5
  # Possible Outcomes
  outcomes <- c("RPCON","WPCON","CBLTR")
  # Probaility Vector for results:
  pvector <- c(1,1,1)

  endLoop <- FALSE
  while(callcount <=5 & endLoop == FALSE ){
    if(callcount == 5){
      stop("5 attempts reached, closing record for the day")
    }
    res <- sample(outcomes, 1, prob=pvector, rep = TRUE)
    print(paste0("Attempt ",callcount))
    if(res == "RPCON" & callcount <= 5){
      print("Call Successful")
      endLoop <- TRUE
    }else if(res == "WPCON" & callcount <= 5){
      print("Wrong Party!, Trying alternate number...")
      callcount <- callcount + 1
      dial(callcount)
    }else if(res == "CBLTR" & callcount <= 5){
      print("Call back request set by agent")
      endLoop <- TRUE
    }
  }# End of REPEAT loop

}# End of function

希望这有帮助。