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.
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.
# creating a matrixmymatrix <- matrix(c("mango", "banana", "lemon", "orange"), nrow = 2, ncol = 2)# using a for loopfor (rows in 1:nrow(mymatrix)) {for (columns in 1:ncol(mymatrix)) {print(mymatrix[rows, columns])}}
2
by 2
matrix called mymatrix
.for
loop and refer to all the elements present in each row of mymatrix
.for
loop and refer to all the elements present in each mymatrix
column.# creating a matrix 2D matrixmymatrix <- array(c("mango", "banana", "lemon", "orange"), dim=c(2, 2))# getting the dimensions of the matrixdimensions = dim(mymatrix)# using a for loopfor (rows in 1:dimensions[1]) {for (columns in 1:dimensions[2]) {print(mymatrix[rows, columns])}}
2
by 2
matrix mymatrix
having 2
rows and 2
columns using the array()
function.dim()
to get the dimensions of mymatrix
.for
loop and refer to all the elements present in each row of mymatrix
.for
loop and refer to all the elements present in each mymatrix
column.