# [R] returning the largest element in an array/matrix?

Henrik Bengtsson hb at maths.lth.se
Tue Mar 7 14:53:36 CET 2006

```This is a problem how to convert vector indices to array indices. Here
is a general solution utilizing the fact that matrices are stored
column by column in R (this extends to arrays of any dimension):

arrayIndex <- function(i, dim) {
ndim <- length(dim);      # number of dimension
v <- cumprod(c(1,dim));  # base

# Allocate return matrix
j <- matrix(NA, nrow=length(i), ncol=ndim);

i <- (i-1);     # one-based indices
for (kk in 1:ndim)
j[,kk] <- (i %% v[kk+1])/v[kk];
1 + floor(j);  # one-based indices
}

# Now we can the optimized which.max() function:

m <- matrix(1:14, nrow=7, ncol=4)
arrayIndex(which.max(m), dim=dim(m))

Gives:
[,1] [,2]
[1,]    7    2

# The less efficient:
arrayIndex(which(m==max(m)), dim=dim(m))

Gives:
[,1] [,2]
[1,]    7    2
[2,]    7    4

BTW, isn't there such a function in R already?  I tried to find it,
but I couldn't.

Cheers

Henrik

On 3/7/06, Petr Pikal <petr.pikal at precheza.cz> wrote:
> Hi
>
> If you do not insist on which.max() you can use
>
> which(mat==max(mat), arr.ind=T)
>
> HTH
> Petr
>
>
>
>
> On 6 Mar 2006 at 20:55, Michael wrote:
>
> Date sent:              Mon, 6 Mar 2006 20:55:20 -0800
> From:                   Michael <comtech.usa at gmail.com>
> To:                     R-help at stat.math.ethz.ch
> Subject:                [R] returning the largest element in an array/matrix?
>
> > Hi all,
> >
> > I want to use "which.max" to identify the maximum in a 2D array/matrix
> > and I want "argmin" and return the row and column indices.
> >
> > But "which.max" only works for vector...
> >
> > Is there any convinient way to solve this problem?
> >
> > Thanks a lot!
> >
> >  [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > R-help at stat.math.ethz.ch mailing list
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > http://www.R-project.org/posting-guide.html
>
> Petr Pikal
> petr.pikal at precheza.cz
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help