The Wayback Machine - https://web.archive.org/web/20240629004434/https://www.geeksforgeeks.org/for-loop-in-r/
Open In App

For loop in R

Last Updated : 06 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

For loop in R Programming Language is useful to iterate over the elements of a list, data frame, vector, matrix, or any other object. It means the for loop can be used to execute a group of statements repeatedly depending upon the number of elements in the object. It is an entry-controlled loop, in this loop, the test condition is tested first, then the body of the loop is executed, the loop body would not be executed if the test condition is false.

For loop in R Syntax: 

for (var in vector)
 {
   statement(s)    
}

Here, var takes on each value of the vector during the loop. In each iteration, the statements are evaluated.

Flowchart of For loop in R:

For loop in RGeeksforgeeks

For loop in R

Iterating over a range in R – For loop

R




# R Program to demonstrate
# the use of for loop
for (i in 1: 4)
{
    print(i ^ 2)
}


Output: 

[1] 1
[1] 4
[1] 9
[1] 16

In the above example, we iterated over the range 1 to 4 which was our vector. Now there can be several variations of this general for loop. Instead of using a sequence 1:5, we can use the concatenate function as well.

Using concatenate function in R – For loop

R




# R Program to demonstrate the use of
# for loop along with concatenate
for (i in c(-8, 9, 11, 45))
{
    print(i)
}


Output: 

[1] -8
[1] 9
[1] 11
[1] 45

Instead of writing our vector inside the loop, we can also define it beforehand.

Using concatenate outside the loop R – For loop

R




# R Program to demonstrate the use of
# for loop with vector
x <- c(-8, 9, 11, 45)
for (i in x)
{
    print(i)
}


Output: 

[1] -8
[1] 9
[1] 11
[1] 45

Nested For-loop in R 

R programming language allows using one loop inside another loop. In loop nesting, we can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or vice versa. The following section shows an example to illustrate the concept: 

Example:

R




# R Program to demonstrate the use of
# nested for loop
for (i in 1:3)
{
    for (j in 1:i)
    {
        print(i * j)
    }
}


Output: 

[1] 1
[1] 2
[1] 4
[1] 3
[1] 6
[1] 9

Jump Statements in R

We use a jump statement in loops to terminate the loop at a particular iteration or to skip a particular iteration in the loop. The two most commonly used jump statements in loops are: 

Break Statement:

A break statement is a jump statement that is used to terminate the loop at a particular iteration. The program then continues with the next statement outside the loop(if any).

Example: 

R




# R Program to demonstrate the use of
# break in for loop
for (i in c(3, 6, 23, 19, 0, 21))
{
    if (i == 0)
    {
        break
    }
   print(i)
}
print("Outside Loop")


Output:

[1] 3
[1] 6
[1] 23
[1] 19
[1] Outside loop

Here the loop exits as soon as zero is encountered. 

Next Statement

It discontinues a particular iteration and jumps to the next iteration. So when next is encountered, that iteration is discarded and the condition is checked again. If true, the next iteration is executed. Hence, the next statement is used to skip a particular iteration in the loop.

Example: 

R




# R Program to demonstrate the use of
# next in for loop
for (i in c(3, 6, 23, 19, 0, 21))
{
    if (i == 0)
    {
        next
    }
    print(i)
}
print('Outside Loop')


Output: 

[1] 3
[1] 6
[1] 23
[1] 19
[1] 21
[1] Outside loop

Creating Multiple Plots within for-Loop in R

R




# create a matrix of data
mat <- matrix(rnorm(100), ncol = 5)
 
# set up the plot layout
par(mfrow = c(2, 3))
 
# loop over columns of the matrix
for (i in 1:5) {
  # create a histogram for each column
  hist(mat[, i], main = paste("Column", i), xlab = "Values", col = "lightblue")
}


Output:

For loop in RGeeksforgeeks

For loop in R

In this example, the for loop iterates over the columns of the matrix mat, and for each column, a histogram of the values is created using the hist() function. The main argument of the hist() function is used to set the title of each plot, and the xlab argument is used to label the x-axis. The col argument is used to set the color of the bars in the histogram to light blue.

The par() function is used to set up the plot layout with mfrow = c(2, 3), which specifies that the plots should be arranged in 2 rows and 3 columns. This means that the for loop will create 5 plots, each of which is a histogram of one of the columns of the matrix mat, arranged in a 2×3 grid.

Here as soon as zero is encountered, that iteration is discontinued and the condition is checked again. Since 21 is not equal to 0, it is printed. As we can conclude from the above two programs the basic difference between the two jump statements is that the break statement terminates the loop and the next statement skips a particular iteration of the loop.



Previous Article
Next Article

Similar Reads

R - Repeat loop
Repeat loop in R is used to iterate over a block of code multiple number of times. And also it executes the same code again and again until a break statement is found. Repeat loop, unlike other loops, doesn't use a condition to exit the loop instead it looks for a break statement that executes if a condition within the loop body results to be true.
2 min read
R - while loop
While loop in R programming language is used when the exact number of iterations of a loop is not known beforehand. It executes the same code again and again until a stop condition is met. While loop checks for the condition to be true or false n+1 times rather than n times. This is because the while loop checks for the condition before entering th
5 min read
How to Loop Through Column Names in R dataframes?
In this article, we will discuss how to loop through column names in dataframe in R Programming Language. Method 1: Using sapply() Here we are using sapply() function with some functions to get column names. This function will return column names with some results Syntax: sapply(dataframe,specific function) where dataframe is the input dataframespe
2 min read
How to Create a For Loop with Range in R?
In this article, we will discuss how to create a for loop with range in R Programming Language. For loop is used to iterate the elements over the given range. We can use for loop to append, print, or perform some operation on the given range of integers. Consider the below syntax of the for loop that also contains some range in it. Syntax: for(iter
2 min read
How to Create a Nested For Loop in R?
A loop in a programming language is a sequence of instructions executed one after the other unless a final condition is met. Using loops is quite frequent in a program. Need of a loop Let us consider a scenario where we want to print natural numbers from 1 to 3. We can simply print them one by one. But suppose the range is high, 1 to 100 or 1 to 10
6 min read
Matrix multiplication in R using for loop
The matrix multiplication is a basic operation in the linear algebra. In R Programming Language we can perform matrix multiplication using a for loop, which provides a basic understanding of the underlying process involved. In R language, we can perform matrix multiplication using a for loop, which provides a basic understanding of the underlying p
6 min read
How To Use A For Loop In R
For loops in R is a fundamental programming construct that allows you to repeat a block of code a specified number of times or for a given range of elements. They are essential for automating repetitive tasks, manipulating data, and performing various computational operations. The basic syntax of a for loop in R Programming Language is: for (variab
3 min read
How to Read Many Files in R with Loop?
When working with data in R Programming Language you often need to read multiple files into your environment. If you have a large number of files, doing this manually is impractical. Instead, you can use a loop to automate the process. This guide will show you how to read many files in R using a loop, making your workflow more efficient and less er
4 min read
three90RightbarBannerImg