The goal of this tutorial is to properly use the loop for in R. Even when apply family functions are often recommended in R, the use of the for loop can be useful in several moments of the analysis.
# Unlike other languages where starting value for the variable, final value and step are declared,
# in R we asign a vector to the variable of the for loop
# First we build the simplest loop
for(i in 1:5) {
print(i)
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
# When the code inside the loop takes only one line, we can write everything together
for(i in 1:5) print(i)
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
# As we explain in other tutorials (see seq_len function tutorial), 1:5 is just a way to create a vector 1,2,3,4,5
# This means that we could create any vector to declare the index
index <- c(1, 3, 5, 7, 9)
for(i in index) print(i)
## [1] 1
## [1] 3
## [1] 5
## [1] 7
## [1] 9
# Sometimes we don't want to run the whole loop
# We can break the loop given certain conditions in order to escape the loop
# Notice in this example that the 9 will not be printed
index <- c(1, 3, 5, 7, 9)
for(i in index) {
print(i)
if(i > 5) break
}
## [1] 1
## [1] 3
## [1] 5
## [1] 7
# First we create a matrix full of 1s
my_matrix <- matrix(data = 1, nrow = 5, ncol = 5)
my_matrix
## [,1] [,2] [,3] [,4] [,5]
## [1,] 1 1 1 1 1
## [2,] 1 1 1 1 1
## [3,] 1 1 1 1 1
## [4,] 1 1 1 1 1
## [5,] 1 1 1 1 1
# Now we walk the matrix using the indexes and two consecutive for loops
# We put on each element the number of the element 1, 2, 3, etc
for(i in 1:nrow(my_matrix)){
for(j in 1:ncol(my_matrix)){
my_matrix[i, j] <- (i-1)*5 + j
}
}
my_matrix
## [,1] [,2] [,3] [,4] [,5]
## [1,] 1 2 3 4 5
## [2,] 6 7 8 9 10
## [3,] 11 12 13 14 15
## [4,] 16 17 18 19 20
## [5,] 21 22 23 24 25
In this tutorial we have learnt how to use the for loop. We have defined 1:5 indexes, asigned a vector, broke the loop and created consecutive loops to walk through a matrix.