[R] Locate first index

Martin Maechler maechler at stat.math.ethz.ch
Sat Sep 20 10:15:10 CEST 2003


>>>>> "Marc" == Marc Schwartz <MSchwartz at medanalytics.com>
>>>>>     on Fri, 19 Sep 2003 16:26:12 -0500 writes:

    Marc> On Fri, 2003-09-19 at 15:57, Douglas Bates wrote:

    DB> It may be easier to use the match function which is
    DB> defined to return the index of the first match.
    DB> 
    DB> > corretor <- c(15, 23, 27, 34, 25, 27, 26) 
    DB> > match(27, corretor)
    DB>  [1]

indeed!

    Marc> True and presumably much faster as the size of the
    Marc> search vector and the offset of the first match
    Marc> increases. If this is being done repeatedly, timing
    Marc> would become important.

yes, and match() is much more readable too.

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... ;-)

Martin




More information about the R-help mailing list