Nors kilpa R su pavyzdžiu

Turinys

Ciklas yra sakinys, kuris tęsiasi, kol įvykdoma sąlyga. Kurio ciklo sintaksė yra tokia:

while (condition) {Exp}

Nors ciklo schema

Pastaba : Nepamirškite tam tikru metu parašyti uždarymo sąlygos, kitaip ciklas tęsis neribotą laiką.

1 pavyzdys:

Peržiūrėkime labai paprastą pavyzdį, kad suprastume „while loop“ sąvoką. Sukursite ciklą ir po kiekvieno paleidimo pridėsite 1 prie saugomo kintamojo. Jums reikia uždaryti kilpą, todėl mes aiškiai pasakome R, kad nustotų kilpą, kai kintamasis pasieks 10.

Pastaba : jei norite pamatyti dabartinę kilpos vertę, kintamąjį turite apvynioti funkcijos print () viduje.

#Create a variable with value 1begin <- 1#Create the loopwhile (begin <= 10){#See which we arecat('This is loop number',begin)#add 1 to the variable begin after each loopbegin <- begin+1print(begin)}

Išvestis:

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

2 pavyzdys:

Jūs nusipirkote akcijų už 50 dolerių kainą. Jei kaina nesiekia 45, norime ją sutrumpinti. Priešingu atveju mes jį laikome savo portfelyje. Po kiekvienos kilpos kaina gali svyruoti nuo -10 iki +10 apie 50. Galite parašyti kodą taip:

set.seed(123)# Set variable stock and pricestock <- 50price <- 50# Loop variable counts the number of loopsloop <- 1# Set the while statementwhile (price > 45){# Create a random price between 40 and 60price <- stock + sample(-10:10, 1)# Count the number of looploop = loop +1# Print the number of loopprint(loop)}

Išvestis:

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

Išvestis:

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

Įdomios straipsniai...