R Loops

Programming languages typically have constructs that allow iterative evaluation of expressions, that bring support for repetitious computing routines, and R is no exception. In this article, we will examine some of these tools and some of their best use cases.

Before proceeding, we need to state that, as a functional programming language, R presents us with facilities for applying a function to data structures. These data structures are principally arrays (a term we use both strictly and loosely). This programming paradigm enables iterative evaluation of the elements of a data structure e.g. vectors, data frames, etc. We are not , however, going to delve into it in this write-up. Our focus today is loops.

The general syntax for a loop looks like this

keyword-construct { body-expression }

Types of loops

There are three keywords available in R for writing different kinds of loops. They are:

  1. repeat
  2. while
  3. for


The repeat loop is one that runs indefinitely until interrupted. Its syntax is as follows:

repeat {
  # expression line 1
  # expression line 2
  # ...

This loop is analogous to the indefinite while loop found in C-like languages and which is constructed like this

// C/C++
    // statement 1
    // statement 2
    // ...

The only to way to terminate repeat is via the break statement or via an interrupt e.g. when an error is signalled,

x <- 1
repeat {
  x <- x + 1
  if (x == 10)
## [1] 10


The while loop is one that runs as long as a condition, cond, holds true:

while (cond) {
  # expression line 1
  # expression line 2
  # ...

Once cond evaluates to FALSE, the loop is terminated. This presupposes that the expression within the body of the loop is going to flip cond from TRUE to FALSE.

x <- 1
while (x < 10) {
  x <- x + 1
## [1] 10


This loop iterates of the entire length of a vector whilst extracting the value, var, of each of element for that vector during each turn. This value is optionally useful for computations within the body of the loop. Its syntax is as follows:

for (var in vector) {
  # expression line 1
  # expression line 2
  # ...

The variable var in the body of the loop is the actual element of the sequence. This is in contrast to similar constructs in languages like C/C++ or JavaScript, where this variable exclusively represents the index of the sequence. (C++ offers access to the actual elements of an object via iterators).

Using a similar example to the previous ones

x <- 0L
for (i in 1:10) {
  x <- x + 1
## [1] 10

Notice the difference: In the for loop, we have to set x to zero to get a similar result, because the loop turns 10 times while the preceding 2 turn 9 times. This is because the length of the vector 1:10 is 10. But to maximise the use of a for loop, it is better to actually use the elements of the sequence

# Make a small data frame first and view output
(some.cars <- head(cars))
##   speed dist
## 1     4    2
## 2     4   10
## 3     7    4
## 4     7   22
## 5     8   16
## 6     9   10

We will now write a loop to multiply the content of each row by 2

for (row in seq_len(nrow(some.cars))) {
  some.cars[row, ] <- some.cars[row, ] * 2

##   speed dist
## 1     8    4
## 2     8   20
## 3    14    8
## 4    14   44
## 5    16   32
## 6    18   20

To further demonstrate the use of a sequence of variables for expressions, let’s use a character vector

rm(list = ls())   

nums <- c('one', 'two', 'three', 'four', 'five', 'six')

for (n in nums)
  assign(x = paste0("var_", n), value = n)

## [1] "n"         "nums"      "var_five"  "var_four"  "var_one"   "var_six"  
## [7] "var_three" "var_two"

We can see that several objects were created by this loop using the character vector as a suffix.

When to use loops

Loops by John Flinchbaugh

As mentioned earlier, R has other facilities that enable the element-by-element traversal of data structures. In fact, most R users believe, dogmatically, the use of loops should be frowned upon, for various cogent reasons. However, there are situations where loops are useful and even necessary:

1. To validate user input

The repeat and while loops are good for collecting user input at the R console or from the shell with an R script, particularly when you want to prompt the user repeatedly until they provide appropriate input. This is actually akin to the do-while loop found in some other languages.

repeat {
  val <- readline("Enter any number between 1 and 5: ")
  if (val > 0 && val < 6)

This loop will keep presenting the user with the prompt until the correct input value is provided–a number ranging from 1 to 5.

2. To enable continuous looping

Some operations where a continuous loop is desirable, e.g.. implementing a client-server situation, will benefit greatly from a continuous loop. For this, we can use repeat {} or while(TRUE) {}. An example of this can be seen in some code I found on http://blog.corynissen.com/2013/05/using-r-to-communicate-via-socket.html and I have posted it for convenience over here

3. To modify a data structure in place

As was demonstrated in the some.cars example above, loops are particularly good for modifying an object’s elements iteratively. However, there’s a small caveat: A for-loop will require that the object be created outside the scope of the loop before it can manipulate its elements.


Well, we’ve just scratched the surface of R loops. For more information, consult the R documentation. Also, if you feel you’re ready for the esoteric and want to take a deep dive, then you’re welcome to study this article by Miles McBain. Finally, Chapter 5 of the book Advanced R by Hadley Wickham has some good points (and yes, I do recommend the hard copy, which I’ve found to be a good companion).


2 thoughts on “R Loops


Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s