Sunday, November 11, 2018

How to use While loop in R Programming

While loop statement in R Programming
While Loop:
The While loop is a statement that keeps running until a condition is satisfied.

Syntax:
while (test_expression)
{
statement
}


Example 1:
We will create a loop and after each run add 1 to the stored variable. You need to close the loop, therefore we explicitly tells R to stop looping when the variable reached 10.
>x <- 1
while (x <= 10)
{
cat('The loop number is:',x,"\n")
x <- x+1
cat('The value of the variable x is:',x,"\n")
}


Output :
The loop number is: 1
The value of the variable x is: 2
The loop number is: 2
The value of the variable x is: 3
The loop number is: 3
The value of the variable x is: 4
The loop number is: 4
The value of the variable x is: 5
The loop number is: 5
The value of the variable x is: 6
The loop number is: 6
The value of the variable x is: 7
The loop number is: 7
The value of the variable x is: 8
The loop number is: 8
The value of the variable x is: 9
The loop number is: 9
The value of the variable x is: 10
The loop number is: 10
The value of the variable x is: 11


Example 2 :
Suppose we bought a stock at price of 50 dollars. If the price goes below 45, we want to short it. Otherwise, we keep it in our portfolio. The price can fluctuate between -10 to +10 around 50 after each loop. You can write the code as follow:

>set.seed(123)
>base_price <- 50
>cur_price <- 50

>x <- 1

>while (cur_price > 45)
{

# Create a random price between 40 and 60
cur_price <- base_price + sample(-10:10, 1)

# Print the Loop number 
cat("The number of the loop is:",x,"\n")

#Increment the variable by 1 
   x= x+1

# Print the current price of the stock
cat("The current price of the stock is:",cur_price,"\n")

}

Output :
The number of the loop is: 1
The current price of the stock is: 46
The number of the loop is: 2
The current price of the stock is: 56
The number of the loop is: 3
The current price of the stock is: 48
The number of the loop is: 4
The current price of the stock is: 58
The number of the loop is: 5
The current price of the stock is: 59
The number of the loop is: 6
The current price of the stock is: 40


Thanks, TAMATAM

No comments:

Post a Comment

Hi User, Thank You for visiting My Blog. Please post your genuine Feedback or comments only related to this Blog Posts. Please do not post any Spam comments or Advertising kind of comments which will be Ignored.

Featured Post from this Blog

How to compare Current Snapshot Data with Previous Snapshot in Power BI

How to Dynamically compare two Snapshots Data in Power BI Scenario: Suppose, we have a sample Sales data, which is stored with Monthly Snaps...

Popular Posts from this Blog