[R] Permutation of a distance matrix

Charilaos Skiadas cskiadas at gmail.com
Sat Nov 17 04:20:18 CET 2007


On Nov 16, 2007, at 6:42 PM, Andrew Park wrote:

> Hi there,
>
> I would like to find a more efficient way of permuting the rows and  
> columns of a symmetrical matrix that represents ecological or  
> actual distances between objects in space.  The permutation is of  
> the type used in a Mantel test.
>
> Specifically, the permutation has to accomplish something like this:
>
>
> Original matrix addresses:
>
> a11   a12   a13
>
> a21   a22   a23
>
> a31   a32   a33
>
>
> Example permutation
>
> a22   a23   a21
>
> a32   a33   a31
>
> a12   a13   a11
>
> that is relative positions of rows and columns are conserved in the  
> permutation.
>
> The problem is, R-users will know, is that using "for" loops like  
> this is slow, and gets slower the further into the loop you get.
>
> However, I am not a sophisticated programmer, and cannot think of a  
> more efficient way to do this.

Would this work do what you want? (Main point: You can index a vector  
by an array):

n <- 3
x <- apply(expand.grid(1:n,1:n),1,paste,collapse="")
x <- paste("a",x,sep="")
dim(x) <- c(n,n)
prm <- sample(1:n)
h<-apply(expand.grid(prm,prm),1,function(x) x[1]+n*x[2]-n)
matrix(x[h],c(n,n))

> Thanks in advance,
>
> Andy Park (University of Winnipeg).
>

Haris Skiadas
Department of Mathematics and Computer Science
Hanover College



More information about the R-help mailing list