Skip to content

maxtrix to permutation vector

7 messages · Ian Coe, Romain Francois, Stavros Macrakis +3 more

#
About this;

 > m <- matrix( 1:9, nr = 3 )
 > dimnames( m ) <- list( c("d", "e", "f"), c("a", "b", "c") )
 >  data.frame( row = rep( rownames(m), ncol(m)), col = rep( 
colnames(m), each = nrow(m)), data  = as.vector(m) )
  row col data
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

or

data.frame(  do.call( expand.grid, dimnames(m) ), data = as.vector(m))

Some timings on my machine with a 700x700 matrix:

 > m <- matrix( rnorm( 700*700 ), nr = 700 )
 > dimnames( m ) <- rep( list( as.character( 1:700) ), 2 )
 > system.time( data.frame( row = rep( rownames(m), ncol(m)), col = rep( 
colnames(m), each = nrow(m)), data  = as.vector(m) ) )
   user  system elapsed
  0.468   0.101   0.594
 > system.time( data.frame(  do.call( expand.grid, dimnames(m) ), data = 
as.vector(m)) )  
user  system elapsed
  0.432   0.106   0.551

Romain
Ian Coe wrote:

  
    
#
Try this:
R C Value
1 a A     1
2 b A     2
3 c A     3
4 a B     4
5 b B     5
6 c B     6
7 a C     7
8 b C     8
9 c C     9
On Fri, May 29, 2009 at 2:08 PM, Ian Coe <ICoe at connectcap.com> wrote:
#
On Fri, 2009-05-29 at 11:08 -0700, Ian Coe wrote:
Here is one way:
+                   Perm = as.vector(mat))
Row Col Perm
1   a   d    1
2   a   e    2
3   a   f    3
4   b   d    4
5   b   e    5
6   b   f    6
7   c   d    7
8   c   e    8
9   c   f    9

And timings for something similar to your 700*700 problem:
+ rc <- expand.grid(rownames(mat), colnames(mat))
+ res <- data.frame(Row = rc$Var2, Col = rc$Var1,
+                   Perm = as.vector(mat))
+ })
   user  system elapsed 
  0.631   0.028   0.690
Row Col Perm
1   1   1    1
2   1   2    2
3   1   3    3
4   1   4    4
5   1   5    5
6   1   6    6

HTH

G
#
Ian Coe wrote:
Hi Ian,

Here's one way you could do it (assuming ori.mat is the original matrix 
and ori.mat has labeled columns and rows):
Cheers,