A loop statement allows us to execute a statement or group of statements multiple times.
There are three types of loops in R programming:
For Loop
While Loop
Repeat Loop
for loop in R
A for loop is used to iterate over a list, vector, or any other object of elements.
for (value in sequence) {
# block of code
}
Here, sequence is an object of elements and value takes in each of those elements. In each iteration, the block of code is executed.
numbers = c(1,2,3,4,5)
# for loop to print all elements in numbers
for (x in numbers){
print(x)
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Code Breakdown:
In this program, we have used a for loop to iterate through a sequence of numbers called numbers. In each iteration, the variable x stores the element from the sequence and the block of code is executed.
Count the Number of Even Numbers:
Let's use a for loop to count the number of even numbers stored inside a vector of numbers.
# Vector of numbers
num = c(2,3,12,14,5,19,23,64)
# variable to store the count of even numbers
count = 0
# for loop to count even numbers
for (i in num){
# check if i is even
if (i %% 2 == 0){
count = count + 1
}
}
print(count)
Output:
[1] 4
Code Breakdown:
In this program, we have used a for loop to count the number of even numbers in the num vector. Here is how this program works:
We first initialized the count variable to 0. We use this variable to store the count of even numbers in the num vector.
We then use a for loop to iterate through the num vector using the variable i.
Inside the for loop, we check if each element is divisible by 2 or not. If yes, then we increment the count by 1.
forLoop With break Statement:
We can use the break statement to exit from the for loop in any iteration.
For example:
# vector of numbers
numbers = c(2, 3, 12, 14, 5, 19, 23, 64)
# for loop with break
for (i in numbers) {
# break the loop if the number is 5
if(i == 5){
break
}
print(i)
}
Output:
[1] 2
[1] 3
[1] 12
[1] 14
Code Breakdown:
Here, we have used an if statement inside the for loop. If the current element is equal to 5, we break the loop using the break statement. After this, no iteration will be executed.
forLoop With the next Statement
Instead of terminating the loop, you can skip an iteration using the next statement.
For example:
# vector of numbers
numbers = c(2, 3, 12, 14, 5, 19, 23, 64)
# for loop with next
for (i in numbers) {
# use next to skip odd numbers
if(i %% 2 != 0){
next
}
print(i)
}
Output:
[1] 2
[1] 12
[1] 14
[1] 64
Code Breakdown:
Here, we have used an if statement inside the for loop to check for odd numbers. If the number is odd, we skip the iteration using the next statement and print only even numbers.
while loop in R
A while loop in R is a type of loop that executes a block of code repeatedly while a certain condition is met.
The basic structure of a while loop in R is as follows:
while (condition) {
# Code to be executed
}
In this structure, the condition is evaluated at the beginning of each iteration of the loop. If the condition is TRUE, the code inside the loop is executed, and the process is repeated. If the condition is FALSE, the loop terminates and control is returned to the rest of the program.
Here is a simple example of how you can use a while loop in R to count the number of positive integers less than a specified value:
# Input the upper limit
limit <- 45
# Initialize the counter
count <- 0
# Start the loop
while (count < limit) {
count <- count + 1
print(count)
}
In this example, the value for the upper limit will be stored in the limit variable. The count variable is initialized to 0, and the while loop is started. The loop increments the count variable by 1 on each iteration and prints the current value of count. The loop continues to execute as long as count is less than limit. When count becomes equal to or greater than limit, the loop terminates.
Note that it's important to include a way to update the condition inside the loop, otherwise, the loop will never end and will run indefinitely, which is called an infinite loop. In this example, the condition is updated on each iteration by incrementing the count variable.
While loops can be very useful in R, but it's important to be careful with their usage to avoid infinite loops and slow performance. Whenever possible, it's recommended to use a for loop or a repeat loop instead of a while loop, as they provide a more concise and straightforward way to handle looping in R.
while loop with break Statement in R
A break statement can be used in a while loop to prematurely terminate the loop and exit the rest of the program.
The basic structure of a while loop in R with a break statement is as follows:
while (condition) {
# Code to be executed
if (exit_condition) {
break
}
}
In this structure, the condition is evaluated at the beginning of each iteration of the loop. If the condition is TRUE, the code inside the loop is executed. If the exit_condition is TRUE, the break statement is executed, and the loop terminates. If the exit_condition is FALSE, the loop continues.
Here is a simple example of how you can use a while loop in R with a break statement to find the first positive integer that is divisible by 3 and 5:
# Initialize the counter
count <- 0
# Start the loop
while (TRUE) {
count <- count + 1
if (count %% 3 == 0 && count %% 5 == 0) {
print(sprintf("The first positive integer divisible by 3 and 5 is %d", count))
break
}
}
In this example, the count variable is initialized to 0, and the while loop is started with a condition of TRUE. This means that the loop will execute indefinitely until the break statement is executed. The loop increments the count variable by 1 on each iteration, and checks if count is divisible by both 3 and 5 using the %% operator. If count is divisible by both 3 and 5, the break statement is executed, and the loop terminates. The value of count is then printed as the first positive integer that is divisible by 3 and 5.
Here, sprintf is used to create a string with the message "The first positive integer divisible by 3 and 5 is %d". The %d placeholder is used to represent a decimal number, which is the value of the count variable. The sprintf function returns the formatted string, which is then passed as an argument to the print function to be displayed on the console.
while loop with next Statement in R
Here's an example of a while loop in R that uses the next statement:
# Initialize a counter
i <- 1
# Start the while loop
while (i <= 10) {
# Check if the current value of i is odd
if (i %% 2 != 0) {
# If i is odd, go to the next iteration of the loop
i <- i + 1
next
}
# If i is even, print its value
print(i)
# Increment the counter
i <- i + 1
}
In this example, the while loop will run as long as i is less than or equal to 10. At each iteration of the loop, the current value of i is checked to see if it is odd. If i is odd, the next statement is executed, which causes the loop to go to the next iteration without executing the rest of the loop body. If i is even, its value is printed to the console. The counter i is incremented at the end of each iteration, which eventually causes the loop to terminate when i becomes greater than 10.
Output:
[1] 2
[1] 4
[1] 6
[1] 8
[1] 10
repeat loop in R
We use the R repeat loop to execute a code block multiple times.
However, the repeat loop doesn't have any condition to terminate the loop.
You need to put an exit condition implicitly with a break statement inside the loop.
Here, we have used the repeat keyword to create a repeat loop. It is different from the for and while loop because it does not use a predefined condition to exit from the loop.
Let's see an example that will print numbers using a repeat loop and will execute until the break statement is executed.
x = 5
# Repeat loop
repeat {
print(x)
# Break statement to terminate if x > 40
if (x > 40) {
break
}
# Increment x by 10
x = x + 10
}
Output:
[1] 5
[1] 15
[1] 25
[1] 35
[1] 45
Here, we have used a repeat loop to print numbers from 5 to 45. We have used an if statement to provide a breaking condition that breaks the loop if the value of x is greater than 40.
Infinite repeat Loop
If you fail to put a break statement inside a repeat loop, it will lead to an infinite loop. For example:
x = 1
sum = 0
# Repeat loop
repeat {
# Calculate sum
sum = sum + x
# Print sum
print(sum)
# Increment x by 1
x = x + 1
}
Output:
[1] 1
[1] 3
[1] 6
[1] 10
.
.
.
In the above program, sincewe have not included any break statement with an exit condition, the program prints the sum of numbers infinitely.
repeat Loop with next Statement
You can also use a next statement inside a repeat loop to skip an iteration.
For example:
x = 1
repeat {
# Break if x = 5
if (x == 5) {
break
}
# Skip if x == 2
if (x == 2) {
# Increment x by 1 and skip
x = x + 1
next
}
# Print x and increment x by 1
print(x)
x = x + 1
}
Output:
[1] 1
[1] 3
[1] 4
Here, we have a repeat loop where we break the loop if x is equal to 5. We skip the iteration where x becomes equal to 2.