2016-03-19 12 views
0

私はコールセンターからルールを示すために発信コールをシミュレートするRスクリプトを作成しています(コール数が5を超える場合、成功またはコールバック要求が設定されていれば、コードは終了するはずです)。 breakステートメントを使用すると、私はstop機能を使用している回避策として、望ましい結果を得られません。エラーを投げずにメッセージを印刷して関数の実行を停止する方法はありますか? これは私のコードです:R内のネストされたブロックからエラーメッセージを出力せずにブレーク/終了

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 

何か助けていただければ幸いです。

+2

'stop'はエラーを発生させ、' break'は 'for'、' while'、または 'repeat'ループから抜け出し、' return'は関数の実行を終了します。 – alistaire

+0

@alistaire 'stop'の代わりに' break'を使うと、それはifブロックから出てくるだけです。 'return'ステートメントを使用すると、関数はコールカウントが5に達するまで続きます。 –

答えて

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 

は、この情報がお役に立てば幸いです。

+0

これは素晴らしいです。@ cyrilb38に感謝します。私は 'if(callcount == 5){...}'部分も省略できると思います。 –

関連する問題