[R] maxtrix to permutation vector

Romain Francois romain.francois at dbmail.com
Fri May 29 20:55:07 CEST 2009


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:
> 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     
>
>  
>
> CONFIDENTIALITY NOTICE: This e-mail communication (inclu...{{dropped:23}}
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>
>   


-- 
Romain Francois
Independent R Consultant
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr




More information about the R-help mailing list