Programlama Örnekleriyle R While Döngüsü

R Programlamada While Döngüsü

R programlamasındaki While döngüsü, while bloğundan sonraki bir koşul sağlanana kadar çalışmaya devam eden bir ifadedir.

R'de While Döngü Sözdizimi

R programlamada While Döngüsü için sözdizimi şöyledir:

while (condition) {
     Exp	
}

R While Döngüsü Akış Şeması

R While Döngüsü Akış Şeması
R While Döngüsü Akış Şeması

not: Bir noktada kapanış koşulunu yazmayı unutmayın, aksi takdirde döngü sonsuza kadar devam eder.

R Programlama Örneklerinde While Döngüsü

Örnek 1

Çok basit bir işlem yapalım R programlama while döngüsü kavramını anlamak için örnek. Bir döngü oluşturacaksınız ve her çalıştırmadan sonra saklanan değişkene 1 ekleyeceksiniz. Döngüyü kapatmanız gerekiyor, bu nedenle değişken 10'a ulaştığında R'ye açıkça döngüyü durdurmasını söylüyoruz.

not: Geçerli döngü değerini görmek istiyorsanız, değişkeni print() fonksiyonunun içine sarmanız gerekir.

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

Çıktı:

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

Örnek 2

50 dolarlık bir hisse senedi satın aldınız. Fiyat 45'in altına düşerse, onu kısa pozisyona almak istiyoruz. Aksi takdirde, portföyümüzde tutuyoruz. Fiyat her döngüden sonra 10 civarında -10 ile +50 arasında dalgalanabilir. Kodu aşağıdaki gibi yazabilirsiniz:

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

Çıktı:

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

Çıktı:

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