For loop in R with increments

Last Updated : 23 Jul, 2025

In R, a for loop allows for repeating a block of code for a specified number of iterations. The default behavior of a for loop is to iterate over a sequence, usually with an increment of 1. However, you may want to control the increment (or step size) during the loop execution. This article will demonstrate how to create a for loop in R Programming Language.

Basic Structure of a For Loop in R

The general syntax of a for loop in R is as follows:

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

where,

  • variable is the loop control variable.
  • sequence is the range or vector over which the loop will iterate.

Example of a Basic For Loop

A simple example of a for loop that iterates through numbers 1 to 5 and prints them:

R
for (i in 1:5) {
  print(i)
}

Output:

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

Implementing For Loop with Increments

By default, the for loop increments the loop variable by 1. To modify this behavior and introduce custom increments, you can use the seq() function to create a sequence with a specific step size.

1. Using seq() for Custom Increments

The seq() function is used to generate sequences in R. You can control the starting point, ending point, and step size (increment).

R
for (i in seq(1, 10, by = 2)) {
  print(i)
}

Output:

[1] 1
[1] 3
[1] 5
[1] 7
[1] 9

This loop starts at 1, increments by 2, and ends at 9 (since 10 is not part of the sequence with step size 2).

2. Increment by a Larger Value

You can specify any increment value with seq(). Here's an example where the loop increments by 5:

R
for (i in seq(0, 20, by = 5)) {
  print(i)
}

Output:

[1] 0
[1] 5
[1] 10
[1] 15
[1] 20

3. Decreasing Increments

You can also use negative increments to create a descending sequence:

R
for (i in seq(10, 1, by = -2)) {
  print(i)
}

Output:

[1] 10
[1] 8
[1] 6
[1] 4
[1] 2

Conclusion

In R, you can easily control the increment in a for loop by using the seq() function. This allows you to iterate over a sequence with custom step sizes, including positive or negative increments. This flexibility is useful in various situations where you need to control the iteration process based on specific requirements. The while loop provides another option for custom increments, though it's often simpler to use for loops in combination with seq() for this purpose.

Comment

Explore