Controlling Code Flow - Looping Constructs in R
In R, looping constructs allow you to repeat a set of instructions until a specific condition is met. These are powerful tools for automating repetitive tasks and iterating over data structures like vectors, matrices, lists, and data frames.
R provides several looping constructs for controlling the flow of code, namely:
for loop
while loop
repeat loop
break and next statements (for controlling the flow within loops)
Let’s explore each of these constructs in detail.
The for loop in R allows you to iterate over a sequence of numbers or elements (like vectors, lists, or data frames). You define the loop variable, and for each iteration, the loop will execute a block of code.
Syntax:
R
for (variable in sequence) {
# Code to execute in each iteration
}
variable: The loop variable that takes the value of each element in the sequence during each iteration.
sequence: A vector or list over which the loop iterates.
Example 1: for Loop with a Vector
R
# Iterate over a vector of numbers and print each value
numbers <- c(1, 2, 3, 4, 5)
for (i in numbers) {
print(i)
}
Output:
1
2
3
4
5
In this example, the loop iterates over each element in the numbers vector and prints it.
Example 2: for Loop with Indexing
You can also iterate using the index of a vector or list.
R
# Iterate using the indices of the vector
for (i in 1:length(numbers)) {
print(paste("Element", i, ":", numbers[i]))
}
Output:
csharp
[1] "Element 1 : 1"
[1] "Element 2 : 2"
[1] "Element 3 : 3"
[1] "Element 4 : 4"
[1] "Element 5 : 5"
In this example, the loop iterates through the indices of the vector numbers and accesses each element using numbers[i].
The while loop in R repeatedly executes a block of code as long as a condition is TRUE. The condition is evaluated before each iteration.
Syntax:
R
while (condition) {
# Code to execute while condition is TRUE
}
condition: A logical expression that is checked before each iteration.
Example 3: while Loop
R
# Print numbers from 1 to 5 using a while loop
i <- 1
while (i <= 5) {
print(i)
i <- i + 1 # Increment the value of i
}
Output:
csharp
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
In this example, the loop continues as long as i is less than or equal to 5. Each iteration increments i by 1.
Example 4: while Loop with Condition Check
R
# Find the smallest integer greater than 100 that is divisible by 7
x <- 101
while (x %% 7 != 0) {
x <- x + 1
}
print(x) # Output: 105
In this example, the loop runs until the condition x %% 7 == 0 is met, i.e., until x is divisible by 7.
The repeat loop in R is an infinite loop that continues until a break statement is encountered. Unlike the while loop, it does not evaluate the condition at the beginning; you must explicitly include a break statement inside the loop to stop it.
Syntax:
R
repeat {
# Code to execute repeatedly
if (condition) {
break # Exit the loop when the condition is met
}
}
The loop will continue indefinitely unless the break statement is executed.
Example 5: repeat Loop
R
# Repeat until a number divisible by 7 is found
x <- 101
repeat {
if (x %% 7 == 0) {
print(x)
break # Exit the loop when the number is divisible by 7
}
x <- x + 1 # Increment x
}
Output:
csharp
[1] 105
In this example, the repeat loop continues until x is divisible by 7, and the break statement exits the loop when that condition is met.
The break statement is used inside loops (for, while, or repeat) to exit the loop prematurely when a certain condition is met. It immediately terminates the current loop and moves the execution to the code that follows the loop.
Example 6: Using break in a for Loop
R
# Print numbers from 1 to 10, but break when the number is 5
for (i in 1:10) {
if (i == 5) {
break # Exit the loop when i is 5
}
print(i)
}
Output:
csharp
[1] 1
[1] 2
[1] 3
[1] 4
In this example, the loop stops executing when i reaches 5, due to the break statement.
The next statement is used to skip the current iteration of the loop and move on to the next one. It allows you to bypass specific code inside a loop without terminating it completely.
Example 7: Using next in a for Loop
R
# Print numbers from 1 to 10, but skip even numbers
for (i in 1:10) {
if (i %% 2 == 0) {
next # Skip even numbers
}
print(i)
}
Output:
csharp
[1] 1
[1] 3
[1] 5
[1] 7
[1] 9
In this example, the next statement skips the even numbers, and the loop continues with the next iteration.
You can also have loops inside other loops, which are called nested loops. Nested loops are useful when you need to perform operations on multi-dimensional data structures like matrices or data frames.
Example 8: Nested for Loop
R
Copy code
# Create a multiplication table using nested loops
for (i in 1:5) {
for (j in 1:5) {
print(paste(i, "*", j, "=", i * j))
}
}
Output:
csharp
[1] "1 * 1 = 1"
[1] "1 * 2 = 2"
[1] "1 * 3 = 3"
[1] "1 * 4 = 4"
[1] "1 * 5 = 5"
...
In this example, the outer loop controls the first factor (i), and the inner loop controls the second factor (j), creating a multiplication table.
for Loop: Iterates over a sequence of numbers or elements, executing code for each item in the sequence.
while Loop: Repeats code as long as a specified condition is TRUE.
repeat Loop: Repeats code indefinitely until a break condition is met.
break Statement: Exits the loop immediately when a condition is met.
next Statement: Skips the current iteration of the loop and moves to the next one.
Nested Loops: Loops inside other loops are useful for working with multi-dimensional data.