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

Break / exit from nested blocks in R without printing error messages

我一直在编写一个 R 脚本来模拟来自呼叫中心的出站 phone 呼叫以演示规则(如果呼叫计数超过 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

感谢任何帮助。

我建议使用带有布尔值的 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

希望对您有所帮助。