You are currently viewing 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. The loop continues until we reach the last item in the sequence or until the break statement encounter. 

Advertisements

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 the different things about the for loop with several examples.

1. Syntax of for Loop in R

Below is the syntax of the for loop.


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

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

2. The Flow of for Loop

Following is the flow chart of the 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 blocks of code for every element in a sequence (vector, list, array, etc.). The for loop is always used with sequence objects like a list, vector, or array. The loop continues until we reach the last item in the sequence or until the break statement encounters. 


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

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

In this example, I will use the sequence 0:4 and iterate through it with the variable i. During each iteration, i will take on one value from the sequence. First, it will be 0, then 1, 2, and 3, continuing until it reaches the final value in the sequence.

4. for break & next Statements

The break and next statements are Jump statements in R that are used to control the flow of loops.

he break statement is used within a for loop to terminate the iteration prematurely, allowing the loop to exit without completing all iterations. Here is an example:


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

Yields below output.

for loop in r

In R, the next statement is used within loops to skip the rest of the current iteration and move to the next iteration. It functions similarly to the continue statement in other programming languages. Below is an example of how to use the next statement in an 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 use jump statements like a 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, that 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 the 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 must say YES. With recent advancements, we no longer need to use on for loops as we can accomplish the same tasks using a family of apply functions: apply(), lapply(), tapply(), sapply(), vapply(), and mapply(). Whenever possible, I recommend using these functions over for loops, as they operate more 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 learned about the concept of for loops in R and how we can iterate each element of Vector, and List using these loops. A for loop is a basic statement in any programming language when you want to repeat a task a defined number of times. R provides multiple types of loops such as the for loop, the while loop and the repeat loop.

Related Articles

References