# [R] matrix to vector

David Winsemius dwinsemius at comcast.net
Fri May 29 21:34:47 CEST 2009

```Not sure it is really "matrix to vector" but here are a few of attempts:

> abM<-matrix(1:9, nrow=3)
> rownames(abM) <- letters[1:3]
> colnames(abM) <- letters[4:6]

> data.frame( cols=colnames(abM)[col(abM)[1:9]], rows= rownames(abM)
[row(abM)[1:9]], vals=abM[1:9])
cols rows vals
1    d    a    1
2    d    b    2
3    d    c    3
4    e    a    4
5    e    b    5
6    e    c    6
7    f    a    7
8    f    b    8
9    f    c    9

> matrix( c(colnames(abM)[col(abM)[1:9]], rownames(abM)[row(abM)
[1:9]], abM[1:9]) ,ncol=3)
# all text values since matrices in R need to be of homogenous type
[,1] [,2] [,3]
[1,] "d"  "a"  "1"
[2,] "d"  "b"  "2"
[3,] "d"  "c"  "3"
[4,] "e"  "a"  "4"
[5,] "e"  "b"  "5"
[6,] "e"  "c"  "6"
[7,] "f"  "a"  "7"
[8,] "f"  "b"  "8"
[9,] "f"  "c"  "9"

But the most compact would be:

>library(reshape)
> melt(abM)
X1 X2 value
1  a  d     1
2  b  d     2
3  c  d     3
4  a  e     4
5  b  e     5
6  c  e     6
7  a  f     7
8  b  f     8
9  c  f     9

On May 29, 2009, at 2:43 PM, Ian Coe wrote:

> Hi,
>
>   Is there a way to  convert a matrix into a vector representing all
> permutations of values and column/row headings with native R
> functions?
> I did this with 2 nested for loops and it took about 25 minutes to run
> on a  ~700x700 matrix.  I'm assuming there must be a smarter way to do
> this with R's vector commands, but being new to R, I'm having trouble
> making it work.
>
> Thanks,
>
> Ian
>
>
>     [a] [b] [c]
>
> [d]    1    4    7
>
> [e]    2    5    8
>
> [f]    3    6    9
>
>
>
> a d 1
>
> a e 2
>
> a f 3
>
> b d 4
>
> b e 5
>
> b f 6
>
> c d 7
>
> c e 8
>
> c f 9
> --
> Ian Coe
>
> Connective Capital Management, LLC
>
> 385 Homer Ave.
>
> Palo Alto, CA 94301
>
> (650) 321-4826 ext. 03
>
--
David Winsemius, MD
Heritage Laboratories
West Hartford, CT

```