[R] function to find coodinates in an array

François Pinard pinard at iro.umontreal.ca
Fri Aug 17 05:15:29 CEST 2007


[Ana Conesa]

> I am looking for a function/way to get the array coordinates of given
> elements in an array. What I mean is the following:
> - Let X be a 3D array
> - I find the ordering of the elements of X by ord <- order(X)
>   (this returns me a vector)
> - I now want to find the x,y,z coordinates of each element of ord

[Moshe Olshansky]

>If your array's dimensions were KxMxN and the "linear"
>index is i then
>n <- ceiling(i/(K*M))
>i1 <- i - (n-1)*(K*M)
>m <- ceiling(i1/K)
>k <- i1 - (m-1)*K

>and your index is (k,m,n)

The reshape package might be helpful, here.  If I understand the problem 
correctly, given this artificial example:

   X <- sample(1:24)
   dim(X) <- c(2, 3, 4)

you would want:

   library(reshape)
   melt(X)[order(X), -4]

so getting the indices in a three columns data frame.

-- 
François Pinard   http://pinard.progiciels-bpi.ca



More information about the R-help mailing list