In this article, we will learn how to repeat the execution of certain parts of R code using loops. In some cases, there is a need to execute a section of code for a number of times. Loops can help you achieve this effectively. Generally, loops execute the statements according to the order they have been written.
R supports different types of loop statements. Let us discuss them.
With this loop, a piece of code will be executed again and again until it finds a stop condition. The repeat loop does not have a condition to check so as to exit the loop. We have to explicitly add the condition inside the loop body and use the break statement so as to exit the loop. If we don’t do so, we will have created an infinite loop.
The repeat loop in R takes the following syntax,
- repeat {
- commands
- if(condition) {
- break
- }
- }
Consider the example given below which shows how this loop can be used,
- > msg <- c("Hello","World!")
- > count <- 2
- > repeat {
- + print(msg)
- + count <- count+1
- + if(count > 5) {
- + break
- + }
- + }
Write the script in an r script file and execute it from the terminal of your OS. it will return the following output,
- [1] "Hello" "World!"
- [1] "Hello" "World!"
- [1] "Hello" "World!"
- [1] "Hello" "World!"
We have created two variables, msg, and count. The first one has a list of strings while the second variable holds the integer 2. Inside the body of the repeat loop, we are trying to print the value of msg variable. The counting will begin at number 2 because the value of variable count was initialized to 2. We have used the if statement to create a condition.
The condition will ensure that the value of variable count does not go beyond 5. The loop will iterate from 2 to 5, meaning that the value of msg variable will be printed for only 4 times. That is how we got the above output! If it were not for the condition inside the if statement, the loop would run forever.
Here is another example,
- > y <- 1
- > repeat {
- + print(y)
- + y = y+1
- + if (y == 5){
- + break
- + }
- + }
The script will return the following upon execution,
We initialized the value of variable y to 1. In the if condition, we are checking for when the value of this variable is 5, at which the loop should stop. That is why the loop printed values only between 1 and 4, with 4 included.
While Loop
This type of loop will execute code again and again until it meets a particular condition. The loop takes the syntax given below,
- while (test_expression) {
- statement
- }
The test_expression will be evaluated first before getting into the loop body. If the test_expression is true, the loop body will be executed. After execution of the loop body, execution will return to the test_expression. If true, the loop body will be executed again. With such a syntax, the loop might end up not running. If the test_expression is found to be false for the first time, the loop will have to be skipped, and then the statement that occurs immediately after the loop body will be executed.
Consider the example given below,
- > msg <- c("Hello","this is a while loop")
- > count <- 2
- > while (count < 6) {
- + print(msg)
- + count = count + 1
- + }
The script should return the following result,
- [1] "Hello" "this is a while loop"
- [1] "Hello" "this is a while loop"
- [1] "Hello" "this is a while loop"
- [1] "Hello" "this is a while loop"
Here is another example that demonstrates the use of the while loop,
- > y <- 1
- > while (y < 6) {
- + print(y)
- + y = y+1
- + }
The script will return the following output upon execution,
- [1] 1
- [1] 2
- [1] 3
- [1] 4
- [1] 5
The code returns numbers from 1 to 5.
For Loop
This is a repetition control structure that helps R programmers to write a loop that executes a particular section of code for a specific number of times.
The statement takes the basic syntax given below,
- for (value in vector) {
- statements
- }
The for loop is very flexible since it is not limited to numbers or integers as the input. We can pass logical vectors, character vectors, and expressions or lists to it.
Consider the example given below,
- > l <- LETTERS[1:5]
- > for ( j in l) {
- + print(j)
- + }
Execution of the above program will return the following output,
- [1] "A"
- [1] "B"
- [1] "C"
- [1] "D"
- [1] "E"
We have created a variable l. The LETTERS is an R keyword which represents all letters of the alphabet from A to Z, uppercase. The variable l will store the first 5 letters, that is, from A to E. We have then used a for loop to iterate through these. We have lastly printed them on the terminal.
Here is another example,
- > y <- c(3,5,2,9,7,11,4)
- > count <- 0
- > for (val in y) {
- + if(val %% 2 == 0)
- + count = count+1
- + }
- > print(count)
The script will return the following output upon execution,
We have created a vector y with a number of integers. The variable count has been initialized to 0. Inside the for loop, we have created the variable val to help us iterate the elements of the vector. We have used the if statement to check whether there are even numbers inside vector y. An integer is an even number if it gives a remainder of 0 after division by 2. The count variable helps us count the number of even numbers found inside the vector. From the output, only 2 even numbers were found.
Summary
In this article, I demonstrated how to repeat the execution of certain parts of R code using loops statements. I explained each and every loop statements such as for and while loop statements in detail. Proper coding snippets as well as outputs are also provided.