How to loop through a Matrix using a "for" loop in R

Overview

To understand how to use for loops in R, click on this shot. To understand a matrix and learn about its creation in R, you can refer to this.

Looping through a matrix

We can loop through a matrix using a for loop in R. The loop starts at the first row of the given matrix and proceeds towards the right.

Code

# creating a matrix
mymatrix <- matrix(c("mango", "banana", "lemon", "orange"), nrow = 2, ncol = 2)
# using a for loop
for (rows in 1:nrow(mymatrix)) {
for (columns in 1:ncol(mymatrix)) {
print(mymatrix[rows, columns])
}
}

Explanation

  • Line 2: We create a 2 by 2 matrix called mymatrix.
  • Line 5: We use a for loop and refer to all the elements present in each row of mymatrix.
  • Line 6: We now use the for loop and refer to all the elements present in each mymatrix column.
  • Line 7: We print all the matrix elements.

Code

# creating a matrix 2D matrix
mymatrix <- array(c("mango", "banana", "lemon", "orange"), dim=c(2, 2))
# getting the dimensions of the matrix
dimensions = dim(mymatrix)
# using a for loop
for (rows in 1:dimensions[1]) {
for (columns in 1:dimensions[2]) {
print(mymatrix[rows, columns])
}
}

Explanation

  • Line 2: We create a 2 by 2 matrix mymatrix having 2 rows and 2 columns using the array() function.
  • Line 5: We use dim() to get the dimensions of mymatrix.
  • Line 8: We use a for loop and refer to all the elements present in each row of mymatrix.
  • Line 9: We now use the for loop and refer to all the elements present in each mymatrix column.
  • Line 10: We print all the matrix elements.

Free Resources