[R] sort a 3 dimensional array across third dimension ?

Claudia Beleites cbeleites at units.it
Fri Feb 18 15:30:26 CET 2011


Dear James,

this is what I understood your sorting along the third dimension to be:
 > x <- array(c(9, 9, 7, 9, 6, 5, 4, 6, 2, 1, 3, 2), dim = list(2, 2, 3))

 > y <- apply (x, 1:2, sort)
 > y
, , 1

      [,1] [,2]
[1,]    2    1
[2,]    6    5
[3,]    9    9

, , 2

      [,1] [,2]
[1,]    3    2
[2,]    4    6
[3,]    7    9


The results of apply are length (result of function) x [shape of x without the 
dimensions you hand to apply).

Thus, your specified result needs rearranging the dimensions:

 > y <- aperm (y, c(2, 3, 1))
 > y
, , 1

      [,1] [,2]
[1,]    2    3
[2,]    1    2

, , 2

      [,1] [,2]
[1,]    6    4
[2,]    5    6

, , 3

      [,1] [,2]
[1,]    9    7
[2,]    9    9


HTH Claudia

-- 
Claudia Beleites
Dipartimento dei Materiali e delle Risorse Naturali
Università degli Studi di Trieste
Via Alfonso Valerio 6/a
I-34127 Trieste

phone: +39 0 40 5 58-37 68
email: cbeleites at units.it



More information about the R-help mailing list