Skip to content

{Spam?} Re: sort a 3 dimensional array across third dimension ?

2 messages · Claudia Beleites, jamaas

#
On 02/18/2011 04:11 PM, Maas James Dr (MED) wrote:
Why sapply?

Sure you can to it in one step:
y<- aperm (apply (x, 1:2, sort), c(2, 3, 1))
I just think two lines are more readable.

Note that all these numbers are the "directions" of the array and don't have 
anything to do with the actual size. Just try it out with different array sizes.

 > a <- array (runif (9000), c (3, 3, 1000))
 > a [,,1:2]
, , 1

        [,1]   [,2]    [,3]
[1,] 0.8721 0.5102 0.47370
[2,] 0.7721 0.5744 0.98281
[3,] 0.9357 0.1969 0.08784

, , 2

        [,1]   [,2]   [,3]
[1,] 0.1485 0.6878 0.1018
[2,] 0.3784 0.3864 0.9814
[3,] 0.9219 0.5664 0.4565

 > y<- aperm (apply (a, 1:2, sort), c(2, 3, 1))
 > y [,,1:2]
, , 1

           [,1]      [,2]      [,3]
[1,] 1.121e-03 1.517e-03 0.0008285
[2,] 7.118e-05 3.303e-04 0.0003870
[3,] 7.445e-04 2.461e-05 0.0005980

, , 2

          [,1]      [,2]     [,3]
[1,] 0.001375 0.0049272 0.004581
[2,] 0.002204 0.0004947 0.001148
[3,] 0.004214 0.0006355 0.001610

 > y [,,999:1000]
, , 1

        [,1]   [,2]   [,3]
[1,] 0.9989 0.9980 0.9998
[2,] 0.9982 0.9973 0.9994
[3,] 0.9994 0.9978 0.9993

, , 2

        [,1]   [,2]   [,3]
[1,] 0.9997 0.9992 0.9999
[2,] 0.9986 0.9981 0.9997
[3,] 0.9998 0.9988 0.9996


BTW: as your MARGINS are short, only 3 x 3 = 9 calls to FUN are necessary. I 
don't think you can gain much time here. The calculation with 3 x 3 x 1000 on my 
computer had 3 ms elapsed, and increasing every direction by a factor of 10 
still needs 1/3 s.



Claudia