Loops in R (Examples) | How to Write, Run & Use a Loop in RStudio

 

Loops are among the most powerful tools of the R programming language (and programming in general).

In this tutorial I want to give a brief introduction to loops in R. This includes a theoretical discussion of the different types of loops as well as actionable R programming examples that you may use as basis for your own applications.

More precisely, this page will be structured as follows:

What are Loops? [Definition]

A loop is a programming instruction that repeats until a specific condition is reached.

The loop executes a code block again and again until no further action is required.

Each time the code block within the loop is executed is called an iteration.

 

Different Types of Loops

Depending on your specific programming situation, you may need different loop-structures that execute the code blocks within the loop on the basis of different conditions.

The R programming language generally provides three different types of loops: for-loops, while-loops, and repeat-loops. The following graphic is illustrating the workflow of each of the three loop-types:

 

flowchart of loops in r for while repeat

 

In the following, I’ll explain the different types of loops and illustrate the differences in R programming example codes. So keep on reading!

 

Writing for-Loops in R

for-loops specify a collection of objects (e.g. elements in a vector or list) to which a code block should be applied.

A for-loop consists of two parts: First, a header that specifies the collection of objects; Second, a body containing a code block that is executed once per object.

Let’s do this in R!

First, we have to specify a data object that we can use within the for-loop:

x_for <- 0                    # Preliminary specification of data object

Our exemplifying data object is simply containing the numeric value 0.

Let’s assume that we want to run a for-loop that iterates over a vector with ten elements (i.e. 1:10). In each iteration, we want to add +1 to our data object and we want to print this data object to the RStudio console. For this, we can use the following R code:

for(i in 1:10) {              # Head of for-loop
 
  x_for <- x_for + 1          # Body of for-loop
  print(x_for)
}
# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] 5
# [1] 6
# [1] 7
# [1] 8
# [1] 9
# [1] 10

The head of our for-loop defines the running index (i.e. i) and the collection of objects through which we want to iterate (i.e. 1:10). Note that our running index i is increased by 1 within each iteration. Also note that running indices can not be changed by the user within for-loops.

The body of our for-loop adds +1 to our data object (i.e. x_for + 1) and prints the updated data object to the RStudio console using the print function (i.e. print(x_for)). Note that we have to use the print function to visibly return values within a for-loop.

The RStudio console output is showing the final outputs of our for-loop (i.e. the values 1 to 10).

At this point, you basically know how to write and run a for-loop in the R programming language. Now, you could make the body of this for loop more complex to create more advanced outputs.

Click here to find more detailed explanations and advanced programming examples of for-loops in R.

 

Writing while-Loops in R

while-loops repeat a code block as long as a certain logical condition is TRUE.

This code is typically used when we don’t know the exact number of times our R code needs to be executed.

The following code illustrates how to write and use while-loops in R. Again, we have to create a data object first:

x_while <- 0                  # Preliminary specification of data object

Now, let’s assume that we want to repeat a code block, which adds +1 to our data object, as long as our data object is smaller than 10. We also want to print this data object at the beginning of each iteration to the RStudio console:

while(x_while < 10) {         # Head of while-loop
 
  x_while <- x_while + 1      # Body of while-loop
  print(x_while)
}
# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] 5
# [1] 6
# [1] 7
# [1] 8
# [1] 9
# [1] 10

The output is exactly the same as in the previous for-loop example. However, this time we used a while-loop to achieve our goal.

Click here to find more detailed explanations and advanced programming examples of while-loops in R.

 

Writing repeat-Loops in R

repeat-loops repeat a code block until a break condition is fulfilled. This break condition marks the end of the loop.

repeat-loops follow a similar logic as while-loops, since they can also be used when the user doesn’t know the exact number of times the R code should be repeated. However, repeat-loops are not as popular as while-loops.

In the next part, I want to show you how to use repeat-loops in R. Again, let’s create a data object containing the value 0:

x_repeat <- 0                 # Preliminary specification of data object

Now, we can apply a repeat-loop to get the same output as in the previous examples as shown below:

repeat{                       # Head of repeat-loop
 
  x_repeat <- x_repeat + 1    # Body of repeat-loop
  print(x_repeat)
 
  if(x_repeat >= 10) {        # Break condition of repeat-loop
 
    break
  }
}
# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] 5
# [1] 6
# [1] 7
# [1] 8
# [1] 9
# [1] 10

Within the repeat-loop, we specified a body adding +1 to our preliminarily created data object. Then, we printed this object to the RStudio console. As last step of the repeat-loop, we specified a logical condition that stopped the repeat-loop once our data object got equal to 10.

Click here to find more detailed explanations and advanced programming examples of repeat-loops in R.

 

Advanced Tutorials on Loops

You can find many advanced tutorials on the handling of different loop-types, statements, and user-defined functions below.

Please let me know in the comments section, in case you don’t find the instructions you are looking for. I’ll try my best to answer all remaining questions.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


8 Comments. Leave new

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.

Top