Vectorizing a matrix

djq picture djq · Dec 31, 2010 · Viewed 63.8k times · Source

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.

Answer

IRTFM picture IRTFM · Dec 31, 2010

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