R While Loop ohjelmointiesimerkeillä
Silmukka R-ohjelmoinnissa
A While-silmukka R-ohjelmoinnissa on käsky, joka jatkuu, kunnes while-lauseen jälkeinen ehto täyttyy.
Vaikka silmukkasyntaksi R:ssä
Seuraava on While Loop in R -ohjelmoinnin syntaksi:
while (condition) {
Exp
}
R While Loop -vuokaavio

Huomautuksia: Muista kirjoittaa sulkemisehto jossain vaiheessa, muuten silmukka jatkuu loputtomiin.
While Loop in R ohjelmointiesimerkkejä
Esimerkki 1
Käydään läpi hyvin yksinkertainen R-ohjelmointi Esimerkki ymmärtääksesi while-silmukan käsitteen. Luot silmukan ja lisäät jokaisen ajon jälkeen 1 tallennettuun muuttujaan. Sinun on suljettava silmukka, joten kehotamme R:tä lopettamaan silmukan, kun muuttuja saavuttaa arvon 10.
Huomautuksia: Jos haluat nähdä nykyisen silmukan arvon, sinun on käärittävä muuttuja funktion print() sisään.
#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)
}
lähtö:
## 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
Esimerkki 2
Ostit osakkeen hintaan 50 dollaria. Jos hinta laskee alle 45, haluamme lyhentää sen. Muuten pidämme sen portfoliossamme. Hinta voi vaihdella -10 ja +10 välillä noin 50 jokaisen silmukan jälkeen. Voit kirjoittaa koodin seuraavasti:
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)
}
lähtö:
## [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)
lähtö:
## it took 7 loop before we short the price. The lowest price is 40
