Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

r
communitycreator

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

Onyejiaku Theophilus Chidalu

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])
  }
}
Looping through a matrix using a `for` loop

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])
  }
}
Looping through a matrix using a for loop

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.

RELATED TAGS

r
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring