[R] Finding indexes of minum and maximum elements of an array

Duncan Murdoch murdoch.duncan at gmail.com
Mon Dec 27 23:44:54 CET 2010


On 10-12-27 5:26 PM, Eduardo de Oliveira Horta wrote:
> Hello there
>
> I wish to get the "coordinates" of the minimum element of an array.
>
> For example, if the array were
>
>> H = array(c(8:5,1:4),dim=c(2,2,2))
>> H
> , , 1
>
>       [,1] [,2]
> [1,]    8    6
> [2,]    7    5
>
> , , 2
>
>       [,1] [,2]
> [1,]    1    3
> [2,]    2    4
>
> then
>> min(H)
> [1] 1
>
> and
>> max(H)
> [1] 8
>
> Say "idx" were the function I'm looking for. Then, what I'm expecting is
>
>> idx(min(H))
> [1] 1 1 2
>> idx(max(H))
> [1] 1 1 1

I don't know if anyone has written a function with the exact output you 
want, but you can get the vector index using which.min() and 
which.max(). Converting that to a vector index is simply a matter of 
some modular arithmetic.  Here's a quick ugly version:

vector.which.min <- function(H) {
   d <- dim(H)
   i <- which.min(H) - 1
   result <- c()
   for (j in seq_along(d)) {
   	  result <- c(result, i %% d[j])
   	  i <- i %/% d[j]
   }
   result + 1
  }

Duncan Murdoch



More information about the R-help mailing list