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

Timur Elzhov Timur.Elzhov at jinr.ru
Fri Dec 6 19:17:03 CET 2002


On Fri, Dec 06, 2002 at 06:57:16PM +0100, Martin Maechler wrote:

>     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)]
Great! but, if length(x1) >> length(x2) you'll get in surprise.
Try, for instance (suppose, length(x2) == 2):

R>  c(1,2,3,4,5,6,7,8)[c(TRUE,FALSE)]
[1] 1 3 5 7

> 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.
Ok, that's useful example, thanks :)


Timur.




More information about the R-help mailing list