R While ループとプログラミング例
R プログラミングでの While ループ
R プログラミングの While ループは、while ブロックの後の条件が満たされるまで実行を続けるステートメントです。
R の While ループ構文
以下は、R プログラミングにおける While ループの構文です。
while (condition) {
Exp
}
R While ループのフローチャート

お願い: どこかの時点で終了条件を必ず記述してください。そうしないと、ループが無限に続きます。
R プログラミング例の While ループ
例
非常に簡単な手順を見てみましょう Rプログラミング whileループの概念を理解するための例です。ループを作成し、実行ごとに格納変数に1を加算します。ループを閉じる必要があるため、Rに明示的にループを停止するように指示します。ping 変数が10に達したとき。
お願い: 現在のループ値を確認したい場合は、関数 print() 内で変数をラップする必要があります。
#Create a variable with value 1
begin <- 1
#Create the loop
while (begin <= 10){
#See which we are
cat('This is loop number',begin)
#add 1 to the variable begin after each loop
begin <- begin+1
print(begin)
}
出力:
## This is loop number 1[1] 2 ## This is loop number 2[1] 3 ## This is loop number 3[1] 4 ## This is loop number 4[1] 5 ## This is loop number 5[1] 6 ## This is loop number 6[1] 7 ## This is loop number 7[1] 8 ## This is loop number 8[1] 9 ## This is loop number 9[1] 10 ## This is loop number 10[1] 11
例
50 ドルで株を購入しました。価格が 45 ドルを下回ったら、空売りします。それ以外の場合は、ポートフォリオに保持します。価格は、ループごとに 10 ドルを中心として -10 ドルから +50 ドルの間で変動します。コードは次のように記述できます。
set.seed(123)
# Set variable stock and price
stock <- 50
price <- 50
# Loop variable counts the number of loops
loop <- 1
# Set the while statement
while (price > 45){
# Create a random price between 40 and 60
price <- stock + sample(-10:10, 1)
# Count the number of loop
loop = loop +1
# Print the number of loop
print(loop)
}
出力:
## [1] 2 ## [1] 3 ## [1] 4 ## [1] 5 ## [1] 6 ## [1] 7
cat('it took',loop,'loop before we short the price. The lowest price is',price)
出力:
## it took 7 loop before we short the price. The lowest price is 40
