# [R] how to find index of maximum?

Prof Brian D Ripley ripley at stats.ox.ac.uk
Mon Jul 12 17:42:45 CEST 1999

```On Mon, 12 Jul 1999, Martin Maechler wrote:

>
>     Peter> Dear R-users, Is there a simple way to find the index of the
>     Peter> maximum of a vector?
>
> Peter meant:
>      Something more efficient than
>
>       		  x == max(x)
> or
> 		which(x == max(x))
> or
> 		match(max(x), x)

The first does not give what Peter asked for.  I usually use

seq(along=x)[x == max(x)]

Also, watch out for duplicates, as match only gives the first one.

Now, one can be more efficient than seq(along=x)[x == max(x)], but you
need an enormous vector to need to do so. The usual problem is that
one wants to do this for each row of a matrix, and my library nnet
(VR5.x) or MASS (VR6.x) has a function in C to do that (and break ties).

Brian

--
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```