Skip to content

matrix to vector

3 messages · Ian Coe, Peter Dalgaard, David Winsemius

#
Ian Coe wrote:
> cbind(expand.grid(rownames(x),colnames(x)),as.vector(x))
   Var1 Var2 as.vector(x)
1    d    a            1
2    e    a            2
3    f    a            3
4    d    b            4
5    e    b            5
6    f    b            6
7    d    c            7
8    e    c            8
9    f    c            9

 > x <- matrix(rnorm(700*700),700)
 > rownames(x) <- paste("R",1:700)
 > colnames(x) <- paste("C",1:700)
 > system.time(foo <- 
cbind(expand.grid(rownames(x),colnames(x)),as.vector(x)))
    user  system elapsed
   1.082   0.107   1.193

  
    
#
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: