Hello, 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? Thank you in advance, Pantelis
fast code
4 messages · Pantelis Andreou, Martin Maechler, Timur Elzhov
On Fri, Dec 06, 2002 at 01:12:27PM -0400, Pantelis 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?
Use `which' function: x1[which(x2 == max(x2))] WBR, Timur.
"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 <><
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.