Here we are explaining how to write an R program to rotate a given matrix 90-degree clockwise rotation. Here we are using a built-in function matrix() for this conversion. This method helps to creates a matrix from the given set of values. The syntax of this function is,
Below are the steps used in the R program to rotate a given matrix 90-degree clockwise rotation. In this R program, we directly give the values to built-in functions. And print the function result. Here we used variables Matx for assigning 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.
Matx = matrix(1:9, 3)
print("Original matrix:")
## [1] "Original matrix:"
print(Matx)
## [,1] [,2] [,3]
## [1,] 1 4 7
## [2,] 2 5 8
## [3,] 3 6 9
final = t(apply(Matx, 2, rev))
print("Rotate the matrix 90 degree clockwise:")
## [1] "Rotate the matrix 90 degree clockwise:"
print(final)
## [,1] [,2] [,3]
## [1,] 3 2 1
## [2,] 6 5 4
## [3,] 9 8 7