There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially. The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and the following is the general form of a loop statement in most of the programming languages −
R programming language provides the following kinds of loop to handle looping requirements. Click the following links to check their detail.
Sr.No. | Loop Type & Description |
---|---|
1 | repeat loop
Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
|
2 | while loop
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
|
3 | for loop
Like a while statement, except that it tests the condition at the end of the loop body.
|
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
R supports the following control statements. Click the following links to check their detail.
Sr.No. | Control Statement & Description |
---|---|
1 | break statement
Terminates the loop statement and transfers execution to the statement immediately following the loop.
|
2 | Next statement
The next statement simulates the behavior of R switch.
|
For Loop in R with Examples for List and Matrix
For Loop Syntax and Examples
For (i in vector) { Exp }
Here,
R will loop over all the variables in vector and do the computation written inside the exp.
Let's see a few examples.
Example 1: We iterate over all the elements of a vector and print the current value.
# Create fruit vector fruit <- c('Apple', 'Orange', 'Passion fruit', 'Banana') # Create the for statement for ( i in fruit){ print(i) }
Output:
## [1] "Apple" ## [1] "Orange" ## [1] "Passion fruit" ## [1] "Banana"
Example 2: creates a non-linear function by using the polynomial of x between 1 and 4 and we store it in a list
# Create an empty list list <- c() # Create a for statement to populate the list for (i in seq(1, 4, by=1)) { list[[i]] <- i*i } print(list)
Output:
## [1] 1 4 9 16
The for loop is very valuable for machine learning tasks. After we have trained a model, we need to regularize the model to avoid over-fitting. Regularization is a very tedious task because we need to find the value that minimizes the loss function. To help us detect those values, we can make use of a for loop to iterate over a range of values and define the best candidate.
For Loop over a list
Looping over a list is just as easy and convenient as looping over a vector. Let's see an example
# Create a list with three vectors fruit <- list(Basket = c('Apple', 'Orange', 'Passion fruit', 'Banana'), Money = c(10, 12, 15), purchase = FALSE) for (p in fruit) { print(p) }
Output:
## [1] "Apple" "Orange" "Passion fruit" "Banana" ## [1] 10 12 15 ## [1] FALSE
For Loop over a matrix
A matrix has 2-dimension, rows and columns. To iterate over a matrix, we have to define two for loop, namely one for the rows and another for the column.
# Create a matrix mat <- matrix(data = seq(10, 20, by=1), nrow = 6, ncol =2) # Create the loop with r and c to iterate over the matrix for (r in 1:nrow(mat)) for (c in 1:ncol(mat)) print(paste("Row", r, "and column",c, "have values of", mat[r,c]))
Output:
## [1] "Row 1 and column 1 have values of 10" ## [1] "Row 1 and column 2 have values of 16" ## [1] "Row 2 and column 1 have values of 11" ## [1] "Row 2 and column 2 have values of 17" ## [1] "Row 3 and column 1 have values of 12" ## [1] "Row 3 and column 2 have values of 18" ## [1] "Row 4 and column 1 have values of 13" ## [1] "Row 4 and column 2 have values of 19" ## [1] "Row 5 and column 1 have values of 14" ## [1] "Row 5 and column 2 have values of 20" ## [1] "Row 6 and column 1 have values of 15" ## [1] "Row 6 and column 2 have values of 10"
While Loop in R with Example
A loop is a statement that keeps running until a condition is satisfied. The syntax for a while loop is the following:
while (condition) { Exp }
Note: Remember to write a closing condition at some point otherwise the loop will go on indefinitely.
Example 1:
Let's go through a very simple example to understand the concept of while loop. You will create a loop and after each run add 1 to the stored variable. You need to close the loop, therefore we explicitely tells R to stop looping when the variable reached 10.
Note: If you want to see current loop value, you need to wrap the variable inside the function 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) }
Output:
## 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
Example 2:
You 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) # 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) }
Output:
## [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)
Output:
## it took 7 loop before we short the price.The lowest price is 40
No comments:
Post a Comment