R Tutorial



R LOOPS


Loops in R

Loops are used in programming to repeat a block of code multiple times. In R, the main types of loops are:

  • for loop: repeats code for each item in a sequence or vector.
  • while loop: repeats code while a condition is TRUE.
  • repeat loop: repeats code indefinitely until a break statement is encountered.

1. for Loop

The for loop iterates over elements of a vector or sequence.

# Print numbers 1 to 5
for(i in 1:5) {
  print(i)
}
  

Output: 1 2 3 4 5 (each printed on a new line)

You can also loop over vectors of characters or any other types:

fruits <- c("apple", "banana", "cherry")

for(fruit in fruits) {
  print(paste("I like", fruit))
}
  

2. while Loop

The while loop repeats as long as the condition remains TRUE.

count <- 1

while(count <= 5) {
  print(paste("Count is", count))
  count <- count + 1  # increment count
}
  

Output:

Count is 1
Count is 2
Count is 3
Count is 4
Count is 5
  

3. repeat Loop

The repeat loop runs infinitely until a break statement stops it.

count <- 1

repeat {
  print(paste("Count is", count))
  count <- count + 1
  if(count > 5) {
    break  # exit the loop when count is greater than 5
  }
}
  

Output: Same as above

Additional Tips

  • Use break to exit a loop early.
  • Use next to skip the current iteration and continue with the next.

Example: Using break and next

for(i in 1:10) {
  if(i == 3) {
    next  # skip when i is 3
  }
  if(i == 7) {
    break  # stop the loop when i is 7
  }
  print(i)
}
  

Output: 1 2 4 5 6

Summary

Loop Type When to Use Syntax
for loop When you want to repeat for each element in a sequence or vector. for(var in sequence) {
   statements
}
while loop When you want to repeat while a condition is true. while(condition) {
   statements
}
repeat loop When you want to repeat indefinitely until a break. repeat {
   statements
   if(condition) break
}

Practice Exercise

Write a for loop to print the squares of numbers from 1 to 10.


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review