【发布时间】: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跳出for、while或repeat循环,并且return结束函数执行(并返回一些内容,如果你告诉它)。 -
@alistaire 如果我使用
break而不是stop,它只会出现在 if 块中。如果我使用return语句,该函数将继续执行,直到调用计数达到 5
标签: r control-flow