# [R] Locate first index

Martin Maechler maechler at stat.math.ethz.ch
Sat Sep 20 18:45:57 CEST 2003

```>>>>> "Damon" == Damon Wischik <djw1005 at cam.ac.uk>
>>>>>     on Sat, 20 Sep 2003 10:58:02 +0100 (BST) writes:

MM> Since I'm sure that I have seen the not-so-good
MM> min(which(a == x)) or which(a == x) several times
MM> section) of help(which) --- still in the optimistic
MM> assumption that people read help pages... ;-)

Damon> I had noticed the remark on the help page,

eehm, hardly possible, since I've only added it today to the
development sources...

You seem to be talking about something else, but related..

Damon> but it had never occurred to me to apply it to
Damon> boolean vectors. It says "for the index of the
Damon> minimum or maximum", so I think it is to be used for
Damon> numeric vectors, without it occurring to me that
Damon> booleans can be typecast into numerics. (I can never
Damon> remember which way round the typecasting goes, so I
Damon> always use explicit constructions like "ifelse(x,1,0)").

Damon> I have generally avoided which.min, because it looks
Damon> (to me) as if it is finding the location of the
Damon> minima of a numerical vector.
Yes, almost: It gives the location (index) of the  (first)
minimum of a numerical vector -- where the "(first)" part is
only needed in case of multiple minima.

Damon> This is on the grounds that "which" returns a vector
Damon> of locations, so I expect "which.min" to do the same,
Damon> i.e. to behave like which(x==min(x)). I know (from
Damon> reading the help pages) that this is not what it does.
but almost, since it *does* give which(x==min(x))
and this is often what is wanted {in the cases where you are
sure that there's only one minimum, or in those where you only
need the location of one of the minima anyways}.

Damon> However, I don't like putting "which.min" into
Damon> my code for this purpose, because it makes it harder

Are you confusing  which.min() and "min.which" (which does not exist)?
The non existing "min.which" is really the subject here, and
it's the one where  match(a,x) can be used instead of
min(which(a == x)).

which.min(x) on the other hand is something very different (as
you indicate too), and really *is* the same (but more
efficiently) as  which(min(x) == x), i.e. in the case of a unique
minimum, it is the same as which(min(x) == x)

Damon> If, on the other hand, there was a command "first" or
Damon> maybe "first.which" which was aliased to which.min, I
Damon> would happily write first.which(x==3)

as Doug Bates said, and we tried to emphasize, you should use
match(3,x)
for the above.

```