For example, I have a matrix:
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 5 6 7 8
[3,] 9 10 11 12
[4,] 13 14 15 16
I want it to become
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 2 3 4 5 6 7 8
[2,] 9 10 11 12 13 14 15 16
Thanks.
Let me expand on Zheyuan Li's answer, since these things can be a bit mysterious for the uninitiated. Basically, the same matrix
function used to create a matrix from a vector, can also be used to reshape a matrix.
All one needs to realize is that a matrix is much like a vector but with a $dim
attribute for its shape, and that the values of that underlying vector are stored by column.
To create your original matrix, you could do:
A <- matrix(1:16, nrow=4, byrow=TRUE)
print(attributes(A))
The byrow
argument tells matrix
to allocate the elements of the input vector in a rowwise fashion to the matrix, instead of columnwise.
However, it does not change the fact that after this allocation, the internal storing of values in the matrix is still by column. The byrow
argument has then simply changed the ordering of elements in the underlying vector, as can easily be seen:
print(as.numeric(A))
What we need to get your desired output, is to first get the sequence in your matrix ordered by column - so that the underlying vector is 1:16
again. For this we can use the transpose function t()
. After the transpose, we can bring the now nicely ordered values into the desired 2x8 shape in a rowwise fashion. So:
B <- matrix(t(A), nrow=2, byrow=TRUE)
print(B)