for Loops
Explore how for loops work in R programming to execute statements over collections like vectors, lists, and matrices. Understand loop syntax and utilize nested for loops for complex data structures, enhancing your control flow skills in R.
We'll cover the following...
Syntax of a for loop
The syntax for for loop in R language:
for(value in vector)
{
statements
}
Let’s begin with printing every value in a vector:
In the above code, the statement print(v) is executed for every element in the vector myVector.
A for loop is used to apply the same statements or function calls to a collection of objects.
Let’s visualize the code flow of for loop:
We can also use for loop on lists the same way we do on vectors. Furthermore, for loops can be applied to matrices, as the following example demonstrates. This will also give us an idea of nested for loops.
Here, the first loop
for (r in 1:nrow(myMatrix))
keeps track of the row index and the second nested for loop
for (c in 1:ncol(myMatrix))
keeps track of the column index.
The nested for loop allows us to iterate over the complete matrix one element at a time.