R is a programming language which is mainly used for statistical work. We can use for
loops in R in different ways. We can use R for
loop with the vector data type and in a regular way like other programming languages too.
Syntax
The syntax of the for loop is like below.
for (VAL in SEQUENCE)
{
STATEMENT
}
- VAL is used in each iteration to set current element value.
- SEQUENCE is the list, an array of the values those will be iterated.
- STATEMENT will be executed in each iteration. We can also call is the body of the for loop.
For Loop
We will start with a simple for loop example. We will iterate over the given list which will start from 1
and count to the 10
.We will print each element in each iteration.
for(i in 1:10) { print(i) }

We can see that each element is printed to the standard output.
Vector For Loop
Vector is a very popular and useful data structure in R programming language. We will create a Vector which holds years from 2015 to 2019. Then we will iterate over this vector and print each element to the standard output.
for (year in c(2015,2016,2017,2018,2019)){ print(paste("Year:", year)) }

Matrix For Loop
Matrix is another useful data type used in the R programming language. We can also call matrix as multi-level array or vector. We can iterate over given matrix by using multiple and nested for loops. We will create a matrix which is 4×4 and then print to the screen accordingly.
mymatrix <- matrix(1:16,nrow=4,ncol=4) for(i in 1:dim(mymatrix[1])){ for(j in 1:dim(mymatrix)[2]){ mymatrix[i,j]=i*j } } print(mymatrix)
Nested For Loop
We have all ready used some nested for loop in previous example. We can use nested or multi level loops with for like below. We will use 3 level and start from 1 to 3 and multiple them.
for(i in 1:3){ for(j in 1:3){ for(k in 1:3){ print(i*j*k) } } }

Using Next Statement To Skip Iteration
During the iteration of the for loop we may need to skip for specific iterations. We can use next
statement to skip specified iterations or cases. In this example, we will skip odd numbers.
for(i in 1:10){ if (!i%%2){ next } print(i) }
