R While Loop cu exemple de programare

While Loop รฎn programarea R

O buclฤƒ While din programarea R este o instrucศ›iune care continuฤƒ sฤƒ ruleze pรขnฤƒ cรขnd este รฎndeplinitฤƒ o condiศ›ie dupฤƒ blocul while.

Sintaxa While Loop รฎn R

Mai jos este sintaxa pentru While Loop รฎn programarea R:

while (condition) {
     Exp	
}

R While Loop diagramฤƒ de flux

R While Loop diagramฤƒ de flux
R While Loop diagramฤƒ de flux

notiศ›e: Nu uitaศ›i sฤƒ scrieศ›i o condiศ›ie de รฎnchidere la un moment dat, altfel bucla va continua la nesfรขrศ™it.

While Loop in R Exemple de programare

Exemplu 1

Sฤƒ trecem printr-un lucru foarte simplu R programare exemplu pentru a รฎnศ›elege conceptul de buclฤƒ while. Vei crea o buclฤƒ ศ™i dupฤƒ fiecare rulare vei adฤƒuga 1 la variabila stocatฤƒ. Trebuie sฤƒ รฎnchizi bucla, prin urmare รฎi spunem explicit lui R sฤƒ opreascฤƒ bucla.ping cรขnd variabila a ajuns la 10.

notiศ›e: Dacฤƒ doriศ›i sฤƒ vedeศ›i valoarea curentฤƒ a buclei, trebuie sฤƒ includeศ›i variabila รฎn funcศ›ia 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)
}

ieศ™ire:

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

Exemplu 2

Ai cumpฤƒrat un stoc la preศ›ul de 50 de dolari. Dacฤƒ preศ›ul scade sub 45, vrem sฤƒ-l scurtฤƒm. รŽn caz contrar, รฎl pฤƒstrฤƒm รฎn portofoliu. Preศ›ul poate varia รฎntre -10 ศ™i +10 รฎn jur de 50 dupฤƒ fiecare buclฤƒ. Puteศ›i scrie codul dupฤƒ cum urmeazฤƒ:

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

ieศ™ire:

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

ieศ™ire:

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

Rezumaศ›i aceastฤƒ postare cu: