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

Joshua Wiley jwiley.psych at gmail.com
Fri Feb 18 14:16:33 CET 2011


Dear Jim,

This works for your small example.  I was not exactly sure what you
were sorting on.  In my example, I sum all values at each level of the
third dimension and sort by that sum.  Of course, if there are many
levels or the 2 dimensions being summed are quite large, this will be
quite computationally inefficient.  I also show how you could sort but
just the value in cell [1, 1, i] where i moves across all levels of
the third dimension.

## Your data
x <- array(c(9, 9, 7, 9, 6, 5, 4, 6, 2, 1, 3, 2), dim = list(2, 2, 3))
## sorting by sum dims 1&2 at each level of 3rd
x[ , , order(apply(x, 3, sum))]
## sorting by cell [1, 1] at each level of 3rd
x[ , , order(x[1, 1, ])]

HTH,

Josh

On Fri, Feb 18, 2011 at 5:01 AM, Maas James Dr (MED) <J.Maas at uea.ac.uk> wrote:
> I'm attempting to sort a 3 dimensional array that looks like this
>> x
> , , 1
>     [,1] [,2]
> [1,]    9    9
> [2,]    7    9
> , , 2
>     [,1] [,2]
> [1,]    6    5
> [2,]    4    6
> , , 3
>     [,1] [,2]
> [1,]    2    1
> [2,]    3    2
>
> Such that it ends up like this ....
>> y
> , , 1
>     [,1] [,2]
> [1,]    2    1
> [2,]    3    2
> , , 2
>     [,1] [,2]
> [1,]    6    5
> [2,]    4    6
> , , 3
>     [,1] [,2]
> [1,]    9    9
> [2,]    7    9
>
> I think this is sorting across the third dimension but several attempts using either the sort or apply functions have not worked.  Any and all suggestions most welcome.  Thanks
>
> J
>
> ===============================
> Dr. Jim Maas
> University of East Anglia
>
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list