R Loops Tutorial with Examples

Loops in R allow you to iterate over a sequence of elements, repeating a block of code multiple times.

This is especially useful for automating repetitive tasks, working with collections of data, and handling large datasets efficiently.

In this tutorial, we’ll explore the different types of loops in R, including:

Each of these looping constructs serves different purposes, and we’ll examine how they work with practical examples.

1. for Loop

The for loop in R is used to iterate over elements in a sequence, such as vectors, lists, or data frames. For each element in the sequence, the loop executes the specified block of code.

Syntax:

for (variable in sequence) {
  # Code to be executed
}

Example (Iterating Over a Vector):

# Define a vector
numbers <- c(1, 2, 3, 4, 5)

# For loop to iterate over the vector
for (num in numbers) {
  print(num)
}
  • In this example, the for loop iterates over each element in the numbers vector and prints the values:
    1, 2, 3, 4, 5

Example (Using for Loop for a Sequence of Numbers):

# For loop to iterate over a range from 1 to 5
for (i in 1:5) {
  print(i * 2)  # Outputs the value of i multiplied by 2
}
  • The loop prints double the value of each number in the sequence from 1 to 5, resulting in:
    2, 4, 6, 8, 10

Example (Nested for Loops):

# Nested for loop to print multiplication table
for (i in 1:3) {
  for (j in 1:3) {
    print(paste(i, "*", j, "=", i * j))
  }
}
  • This code generates a multiplication table for numbers from 1 to 3.

2. while Loop

The while loop repeatedly executes a block of code as long as a specified condition is TRUE. This type of loop is useful when the number of iterations is not known beforehand.

Syntax:

while (condition) {
  # Code to be executed as long as the condition is TRUE
}

Example (Simple while Loop):

# Initialize a variable
x <- 1

# While loop to print values from 1 to 5
while (x <= 5) {
  print(x)
  x <- x + 1
}
  • In this example, the while loop continues to execute as long as x is less than or equal to 5. It increments x by 1 during each iteration, and prints:
    1, 2, 3, 4, 5

Example (Sum of Numbers Using while Loop):

# Initialize variables
i <- 1
sum <- 0

# While loop to calculate the sum of numbers from 1 to 10
while (i <= 10) {
  sum <- sum + i
  i <- i + 1
}
print(sum)  # Outputs: 55
  • In this case, the loop calculates the sum of numbers from 1 to 10.

3. repeat Loop

The repeat loop in R is similar to while but without an explicit condition. It continues indefinitely until a break statement is encountered. This loop is less commonly used but can be helpful in situations where you want to repeat code without a predefined condition.

Syntax:

repeat {
  # Code to be executed
  if (condition) {
    break  # Exit the loop
  }
}

Example:

# Initialize a variable
x <- 1

# Repeat loop
repeat {
  print(x)
  x <- x + 1
  
  # Exit the loop when x reaches 5
  if (x > 5) {
    break
  }
}
  • The repeat loop continues until x > 5. The output will be:
    1, 2, 3, 4, 5

4. Loop Control Statements

4.1 break Statement

The break statement is used to exit a loop before it has completed all its iterations. It can be used with for, while, or repeat loops.

Example (Using break in a for Loop):

# For loop with break
for (i in 1:10) {
  if (i == 5) {
    break  # Exit the loop when i equals 5
  }
  print(i)
}
  • This loop exits when i == 5, so it prints:
    1, 2, 3, 4

4.2 next Statement

The next statement skips the current iteration of the loop and moves to the next iteration. This is useful when you want to ignore certain values.

Example (Using next in a for Loop):

# For loop with next
for (i in 1:5) {
  if (i == 3) {
    next  # Skip the iteration when i equals 3
  }
  print(i)
}
  • The next statement skips the iteration where i == 3, so the output is:
    1, 2, 4, 5

Practical Examples of Loops in R

1. Looping Through a List

You can loop through lists or vectors in R using the for loop.

# Define a list of names
names <- list("John", "Jane", "Doe")

# For loop to iterate through the list
for (name in names) {
  print(paste("Hello,", name))
}
  • The loop prints greetings for each name in the list.

2. Summing Elements of a Vector

# Define a vector
vec <- c(1, 2, 3, 4, 5)

# Initialize sum variable
sum <- 0

# For loop to sum the elements of the vector
for (num in vec) {
  sum <- sum + num
}
print(sum)  # Outputs: 15
  • This loop calculates the sum of the elements in the vec vector.

3. Finding Prime Numbers in a Range Using Loops

# Function to check if a number is prime
is_prime <- function(n) {
  if (n == 2) {
    return(TRUE)
  }
  if (n < 2 || n %% 2 == 0) {
    return(FALSE)
  }
  for (i in 3:sqrt(n)) {
    if (n %% i == 0) {
      return(FALSE)
    }
  }
  return(TRUE)
}

# Find prime numbers between 1 and 20
for (num in 1:20) {
  if (is_prime(num)) {
    print(paste(num, "is a prime number"))
  }
}
  • This example uses a loop and a custom function to identify prime numbers between 1 and 20.

Conclusion

Loops are an essential feature of programming in R and allow you to automate repetitive tasks and iterate over data structures like vectors, lists, and data frames.

Understanding how to use different types of loops (for, while, repeat) and control flow mechanisms (break, next) will help you write more efficient and powerful R scripts.

By mastering these constructs, you’ll be able to handle complex data manipulation and analysis tasks with ease.

Related posts

R Factors Tutorial with Examples

R Matrices Tutorial with Examples

R Vectors Tutorial with Examples