프로그래밍 예제가 포함된 R While 루프

R 프로그래밍의 While 루프

R 프로그래밍의 While 루프는 while 블록 이후의 조건이 만족될 때까지 계속 실행되는 명령문입니다.

R의 while 루프 구문

R 프로그래밍에서 While 루프의 구문은 다음과 같습니다.

while (condition) {
     Exp	
}

R While 루프 흐름도

R While 루프 흐름도
R While 루프 흐름도

주의 사항: 루프가 무한정 계속되지 않도록 어느 시점에 종료 조건을 작성해야 합니다.

R 프로그래밍 예제의 While 루프

예제 1

아주 간단한 문제를 살펴보겠습니다. R 프로그래밍 while 루프의 개념을 이해하기 위한 예제입니다. 루프를 생성하고 각 실행 후에 저장된 변수에 1을 추가합니다. 루프를 닫아야 하므로 변수가 10에 도달하면 루프를 중지하도록 R에 명시적으로 지시합니다.

주의 사항: 현재 루프 값을 보려면 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)
}

출력:

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

당신은 50달러에 주식을 샀습니다. 만약 가격이 45달러 아래로 떨어지면, 우리는 그것을 숏하고 싶습니다. 그렇지 않으면, 우리는 그것을 포트폴리오에 보관합니다. 가격은 각 루프 후 10을 중심으로 -10에서 +50 사이에서 변동할 수 있습니다. 다음과 같이 코드를 작성할 수 있습니다.

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

출력:

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

출력:

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