In R, you can reshape matrices using functions like matrix()
, array()
, and dim()
. These functions allow you to change the dimensions of a matrix or convert it to a different shape.
In this example,
mat
of dimensions 2x3, created using the matrix()
function.dim()
function to change the dimensions of mat
to 3x2. This reshapes the matrix into a different dimension.mat <- matrix(1:6, nrow = 2, ncol = 3)
dim(mat) <- c(3, 2)
print(mat)
[,1] [,2] [1,] 1 3 [2,] 2 4 [3,] 5 6
In this example,
mat
of dimensions 2x3, created using the matrix()
function.array()
function to convert mat
into a 3-dimensional array with dimensions 2x3x1.mat <- matrix(1:6, nrow = 2, ncol = 3)
array_mat <- array(mat, dim = c(2, 3, 1))
print(array_mat)
, , 1 [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6
In this tutorial, we learned How to Reshape Matrices in R language with well detailed examples.