I have a large 2D matrix that is 1000 x 1000. I want to reshape this so that it is one column (or row). For example, if the matrix was:
A B C 1 4 7 2 5 8 3 6 9
I want to turn it in to:
1 2 3 4 5 6 7 8 9
I do not need to preserve the column headers, just the order of the data. How do I do this using reshape2
(which is the package that I presumed was the easiest to use)?
Just to clarify, I mentioned reshape
as I thought it was the best way of doing this. I can see that there are simpler methods which I am perfectly happy with.
The matrix can be created by using matrix function in R and if we want to create a matrix by replicating a vector then we just need to focus on the replication. For example, if we have a vector V and we want to create matrix by replicating V two times then the matrix can be created as matrix(replicate(2,V),nrow=2).
I think it will be difficult to find a more compact method than:
c(m) [1] 1 2 3 4 5 6 7 8 9
However, if you want to retain a matrix structure, then this reworking of the dim attribute would be be effective:
dim(m) <- c(dim(m)[1]*dim(m)[2], 1) m [,1] [1,] 1 [2,] 2 [3,] 3 [4,] 4 [5,] 5 [6,] 6 [7,] 7 [8,] 8 [9,] 9
There would be more compact methods of getting the product of the dimensions but the above method emphasizes that the dim attribute is a two element vector for matrices. Other ways of getting the "9" in that example include:
> prod(dim(m)) [1] 9 > length(m) [1] 9
A possible solution, but without using reshape2:
> m <- matrix(c(1:9), ncol = 3) > m [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 > as.vector(m) [1] 1 2 3 4 5 6 7 8 9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With