For loop in R

Filed Under: R Programming

Most of the time in programming, we need to perform the same operations upon all elements in a vector or perform the same set of actions multiple times. Loop statements in programming are designed for this purpose. R supports two kinds of loops namely the for loop and the while loop. This article elucidates the structure and usage of for loop for programming.

Structure of for loop in R

The general structure of for loop in R is as follows.

for(index in range or vector){
#Write the code to repeat here
}
  • The value index is the indicator of how many times we want the loop to run.
  • The range sets the upper bound on the number of times the loop runs. This number of times is known as iterations in computer science.
  • The actions that we need to carry out multiple times is placed between the braces. This can be anything we choose.

We now illustrate the running of a for-loop using simple print statements first.

Simple R for loop example

for(index in 1:5){
  print("Begin loop")
  print(index)
  print("End loop")
}
  • The variable index is a temporary variable that does not need to be defined or initialized outside the loop.
  • At its first occurrence, the index gets set to the starting value or the range, which is here set as 1 to 5. So index value is initially 1.
  • With each run of the loop, the value of index is incremented by 1, until it reaches the upper limit 5.
  • Let us now see how the output looks for this loop.

Output:

[1] "Begin loop"
[1] 1
[1] "End loop"
[1] "Begin loop"
[1] 2
[1] "End loop"
[1] "Begin loop"
[1] 3
[1] "End loop"
[1] "Begin loop"
[1] 4
[1] "End loop"
[1] "Begin loop"
[1] 5
[1] "End loop"
> 

Notice how the sentinel print statements we placed at the beginning and end of the loop run for each and every iteration, as long as the index value is less than or equal to 5.

Using for loop in R with vectors

For loop can also be used to loop over elements in a vector in R. Recall that a vector is defined by using c(element1,element2...) format.

Let us look at a for loop that reads and displays each element in a vector.

vec <- c(2,5,6,1,7,8,9)
 for(val in vec){
   print(val)
 }

Output:

[1] 2
[1] 5
[1] 6
[1] 1
[1] 7
[1] 8
[1] 9

The variable val gets the value of each element in the vector progressively with each iteration and displays it inside the loop’s body. This will prove an important feature when we handle larger data structures in future, which we will see as we go on.

Nested for loops in R

For a vector of one dimension like the one above, it is enough for one looping variable. However, when we are working with multidimensional vectors, say like matrices, we would need one variable for each dimension. Keeping one index constant, we can loop over all the subdimensions of the matrix/vector. This can be illustrated in the following example.

for(i in 1:4){
  for(j in 1:3){
    print(i*j)
  }
  cat("\n")
}

We are looping over two variables here. Firstly, for i value 1, the inner loop runs from j value 1 to j value 3. Each time, a product if i and j is printed. Next, i value gets incremented to 2 and j runs from 1 to 3 again. This continues until the i value is exhausted.

The line cat("\n") is to just place a new line between each cycle of the inner loop executions for our easy understanding.

Let us now look at the output of this loop.

Output:

[1] 1
[1] 2
[1] 3

[1] 2
[1] 4
[1] 6

[1] 3
[1] 6
[1] 9

[1] 4
[1] 8
[1] 12

Similar nesting of loops is used to handle matrix dimensions in R, which we will discuss in the matrices in R tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages