[R] fast code {for max/min finding}

Martin Maechler maechler at stat.math.ethz.ch
Fri Dec 6 18:58:02 CET 2002


>>>>> "Timur" == Timur Elzhov <Timur.Elzhov at jinr.ru>
>>>>>     on Fri, 6 Dec 2002 20:41:26 +0300 writes:

    Timur> On Fri, Dec 06, 2002 at 01:12:27PM -0400, Pantelis
    Timur> Andreou wrote:
    >> I have two vectors x1 and x2 both in increasing order.  I
    >> want to select the x1[j]th entry which is the max min of
    >> the x2[i]th entry. I can do this using if and for
    >> statements but is there a quick way to do it without
    >> running a loop?
    Timur> Use `which' function:

    Timur> x1[which(x2 == max(x2))]
which is equivalent to the {shorter/faster}
	   x1[x2 == max(x2)]

If this is what he meant, an even faster solution might be

   x1[which.max(x2)]

Note that this however might be different! 
If the maximum is not unique, Timur's proposal returns a vector
of length > 1, where which.max(.) always returns the location of
the *first* maximum in x2.


Martin Maechler <maechler at stat.math.ethz.ch>	http://stat.ethz.ch/~maechler/
Seminar fuer Statistik, ETH-Zentrum  LEO C16	Leonhardstr. 27
ETH (Federal Inst. Technology)	8092 Zurich	SWITZERLAND
phone: x-41-1-632-3408		fax: ...-1228			<><




More information about the R-help mailing list