Looping in R (for, while, repeat) With Examples

R supports three looping statements for, while, and repeat loops. Looping or loops are control statements in R Programming that are used to run block of code multiple times. These are nothing new to programming, these statements exist in pretty much all programming languages.

In this article, I will explain the following looping statements in R with examples.

  • For Loop Statement
  • While Loop Statement
  • Repeat Loop Statement

1. Looping with for

Looping for statement in R is a basic statement that is used when you want to repeat a task a defined number of times or for every element in the sequence (vector, list e.t.c). For more details and examples, refer to for loops in R.

looping in r

1.1 for Syntax

Following is the syntax of the for statement. Here, the sequence can be a vector, array, list, matrix, data.frame e.t.c.


# for syntax
for (var in sequence) {
    statement(s)    
}

1.2 for Statement in R Example

Following is an example, Here, 0:4 is a numeric vector and variable var takes one value at a time for each iteration. since our vector contains 5 values, it executes print() statement for 5 times. Because the first value in our sequence (0:4) is 0, the iteration starts by replacing i with 0 and then 1, 2,3,4.


# for example
for (var i in 0:4) {
  print(i)
}

# Output
#[1] 0
#[1] 1
#[1] 2
#[1] 3
#[1] 4

3. Looping with while

The while looping statement in R is used to execute the block of code multiple times until the given condition becomes false. In the while loop always the condition executes first.

Following is a while loop flow diagram.

loops in r

3.1 while Syntax & Flow


# while syntax
while ( condition ) 
{
  #one or more statements
}

3.2 while Example

The following example executes the while block until the condition i<=n becomes false. Here, first n is assigned a value 5 and i is assigned a value 1. The loop executes until i reaches n.


# while example
n=5
i=1
while (i <= n) {
  print(i)
  i = i + 1
}

# Output
#[1] 1
#[1] 2
#[1] 3
#[1] 4
#[1] 5

4. Looping with repeat

The repeat loop statement in R is similar to do while statement in other languages. repeat run the block of statements repeatedly until the break jump statement has been encountered. You have to use the break statement to terminate or exit the loop. Not using this will end up repeat statement in indefinite loop.

This statement is mostly used if you wanted to execute the repeated block at least one time.

Below is a flow chart of how a repeat loop statement works.

4.1 repeat syntax


# repeat syntax
repeat 
{ 
   #one or more statements
 
   if( condition ) 
   {
      break
   }
}

4.2 repeat example

The following is an example of a repeat statement.


# repeat example
i = 1
repeat {
  print(i)
  i = i + 1

  if(i >= 5 )
    break
}

# Output
#[1] 1
#[1] 2
#[1] 3
#[1] 4

5. Break & Next Statement

The break and next statements are Jump statements in R that are used to interrupt the looping statements.

The break is used within the scope of any above looping statements in R to stop and exit the iteration without looping through all the items in sequence or the condition becomes false. Below is an example.

The next is similar to continue from other programming languages that is used to skip the rest of the iterator and jump to the next item in the sequence. Below is an example of the break & next statement using with for statement and if else statement.


# Continue or next
numbers <- c('One','Two',"Three","Four","Five")
for(i in numbers) {
  if(i == "Two")
    next
  if( i == "Four")
    break
  print(i)
}
# [1] "One"
#[2] "Three"

6. Are Loops Outdated?

I am forced to say YES. Recently with most advanced functions, we don’t have to use for or while loops as we can achieve the same task in different ways using a family of apply functions apply()lapply()tapply()sapply()vapply(), and mapply()

When possible I would recommend using these functions over for or while loops as apply function works efficiently.


# Using apply() function
fun1 <- function(a) {print(a + 1)}
lapply(0:4, fun1)

Yields below output.

looping example r

7. Conclusion

In this article, you have learned looping in R and how to use loops to iterate each element of a Sequence type object (For example Vector, List). There are three types of loops in R the for, the while and the repeat.

Related Articles

References

NNK

SparkByExamples.com is a Big Data and Spark examples community page, all examples are simple and easy to understand and well tested in our development environment Read more ..

Leave a Reply

You are currently viewing Looping in R (for, while, repeat) With Examples