For Loop in R With Examples

The for loop in R is used to repeatedly execute a set of statements or block of code a specified number of times or until a specified condition is satisfied. The for loop is always used with sequence objects like a list, vector, or array. Loop continues until we reach the last item in the sequence or until the break statement encounter. 

for loop is a basic statement that exists in any programming language when you want to repeat a task a defined number of times. There are three types of loops in R Programming, the for loop, the while loop, and the repeat loop. In this article, you will learn all different things about for loop with several examples.

1. Syntax of for Loop in R

Following is the syntax of the for loop.


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

Here, the sequence can be vector, array, list, matrix, data.frame e.t.c

2. The flow of for Loop

Following is the flow chart of for loop.

for loop r

3. for Loop In R Example

The for loop in R is used to repeatedly execute a set of statements or block of code for every element in a sequence (vector, list, array e.t.c). The for loop is always used with sequence objects like a list, vector, or array. Loop continues until we reach the last item in the sequence or until the break statement encounter. 


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

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

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. Let’s break it down. Because the first value in our sequence (0:4) is 0, the loop starts by replacing i with 0 and then 1, 2,3,4.

4. for break & next Statements

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 for loop to stop and exit the iteration without looping through all the items in sequence. Below is an example.


numbers <- c('One','Two',"Three","Four","Five")
for(i in numbers) {
  if( i == "Four")
    break
  print(i)
}

Yields below output.

for loop in r

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 with R for loop.


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

Yields below output

5. Nested for Loop In R

Like any other language, R programming also supports nested for loops. A loop within another loop is called a nested loop. When you used jump statements like break or next in an inside loop, it just interrupts the inner loop, not the outer loop.


# Nested for loop
for (i in 0:4) {
  for(j in 0:i)
    print(i + j)
}

I will leave this example to you to run and verify the output.

6. Iterate List Using for Loop

In R, List objects are used to store elements of different types like numbers, strings, vectors, and even lists. The good thing in R is, elements in List can be given names and they can be accessed using these names.

You can use the dollar sign in R to access, update, insert, and delete elements from the named List. Let’s see how to use list object with the for loop.


# Using list with for loop
states <- list('NY','CA',"NJ","PA","DE")
for(st in states) {
  if(st == "CA")
    next
  if(st == "PA")
    break
  print(st)
}

Yields below output.

7. Are for Loops Outdated?

I am forced to say YES. Recently with most advanced functions, we don’t have to use for loops as we can achieve the same works 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 loops as apply function works efficiently.


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

Yields below output.

for loop example r

8. Conclusion

In this article, you have learned the syntax of the for loop in R and how to use it to iterate each element of Vector, List. For Loop is a basic statement that exists in any programming language when you want to repeat a task a defined number of times. There are three types of loops in R the for loop, the while loop and the repeat loop.

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 For Loop in R With Examples