Skip to content
Prev 181882 / 398513 Next

matrix to vector

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: