R While Loop koos programmeerimisnäidetega

Kuigi silmus R programmeerimisel

A While tsükkel R-programmeerimises on lause, mis töötab seni, kuni on täidetud tingimus pärast while-plokki.

Kuigi tsükli süntaks R

Järgmine on While Loop in R programmeerimise süntaks:

while (condition) {
     Exp	
}

R Silmuse vooskeem

R Silmuse vooskeem
R Silmuse vooskeem

märkused: Ärge unustage mingil hetkel kirjutada sulgemistingimust, vastasel juhul jätkub tsükkel lõputult.

Kuigi Loop in R programmeerimisnäited

Näiteks 1

Käime läbi väga lihtsa R programmeerimine näide, et mõista while-tsükli mõistet. Loote tsükli ja lisate pärast iga käitamist salvestatud muutujale 1. Peate tsükli sulgema, seetõttu käsime R-il selgesõnaliselt katkestada silmus, kui muutuja jõuab 10-ni.

märkused: Kui soovite näha praegust tsükli väärtust, peate muutuja mähkima funktsiooni print() sees.

#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)
}

Väljund:

## 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

Näiteks 2

Ostsite aktsia hinnaga 50 dollarit. Kui hind langeb alla 45, tahame selle lühikeseks teha. Vastasel juhul hoiame seda oma portfellis. Hind võib pärast iga tsüklit kõikuda -10 kuni +10 50 ringis. Koodi saate kirjutada järgmiselt:

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)
}

Väljund:

## [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)

Väljund:

## it took 7 loop before we short the price. The lowest price is 40