To write an R program for rotating a matrix, we are using the matrix() built-in function. The matrix() function is an in-built fiction in R that will create a matrix from the given set of values. The syntax of the function is,
matrix(data = NA, nrow = 4, ncol = 6, dimnames = NULL)
In this R program, we directly give the values to the built-in function for creating a matrix and then use t(apply()) for rotating it. Finally, print the function result.
Here we use variables Matx for assigning a matrix with values 1 to 9. Rotate the matrix by calling like t(apply(Matx, 2, rev)). Here the apply() returns a vector or array obtained by applying a function to an array or matrix. The function t() helps to get the transpose of the given matrix of the data frame.
STEP 1: Assign variable Matx with matrix values
STEP 2: Create a matrix of 1 to 9 elements with 3 rows
STEP 3: Rotate it by calling like t(apply(Matx, 2, rev))
STEP 4: Assign the result into a variable final
STEP 5: print the result matrix final
Matx= matrix(1:9, 3)
print("Original matrix:")
print(Matx)
final = t(apply(Matx, 2, rev))
print("Rotate the matrix 90 degree clockwise:")
print(final)
[1] "Original matrix:" [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 [1] "Rotate the matrix 90 degree clockwise:" [,1] [,2] [,3] [1,] 3 2 1 [2,] 6 5 4 [3,] 9 8 7