[R] Locate first index

Damon Wischik djw1005 at cam.ac.uk
Sat Sep 20 11:58:02 CEST 2003


> Since I'm sure that I have seen the not-so-good  min(which(a == x)) or
> which(a == x)[1] several times before, I've added a note about
> this (in the SEE ALSO section) of help(which) --- still in the
> optimistic assumption that people read help pages... ;-)

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

I have generally avoided which.min, because it looks (to me) as if it is
finding the location of the minima of a numerical vector. This is on the
grounds that "which" returns a vector of locations, so I expect
"which.min" to do the same, i.e. to behave like which(x==min(x)). I know
(from reading the help pages) that this is not what it does.  However, I
don't like putting "which.min" into my code for this purpose, because it
makes it harder for me to read.

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

Damon.




More information about the R-help mailing list