【问题标题】:Break / exit from nested blocks in R without printing error messages从 R 中的嵌套块中断/退出而不打印错误消息
【发布时间】:2016-03-19 09:12:49
【问题描述】:

我一直在编写一个 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

感谢任何帮助。

【问题讨论】:

  • stop 引发错误,break 跳出forwhilerepeat 循环,并且return 结束函数执行(并返回一些内容,如果你告诉它)。
  • @alistaire 如果我使用break 而不是stop,它只会出现在 if 块中。如果我使用return 语句,该函数将继续执行,直到调用计数达到 5

标签: r control-flow


【解决方案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

希望这会有所帮助。

【讨论】:

  • 这太棒了,谢谢@cyrilb38。我认为if(callcount==5){...}部分也可以省略。
猜你喜欢
  • 2013-10-03
  • 2019-04-03
  • 2021-07-20
  • 2011-06-01
  • 2022-12-21
  • 1970-01-01
  • 2021-11-03
  • 2022-01-18
  • 2021-03-12
相关资源
最近更新 更多