[R] Retrieve indexes of the "first occurrence of numbers" in an effective manner

Emmanuel Levy emmanuel.levy at gmail.com
Thu Dec 27 20:17:35 CET 2012


Hi,

That sounds simple but I cannot think of a really fast way of getting
the following:

 c(1,1,2,2,3,3,4,4) would give c(1,3,5,7)

i.e., a function that returns the indexes of the first occurrences of numbers.

Note that numbers may have any order e.g., c(3,4,1,2,1,1,2,3,5), can
be very large, and the vectors are also very large (which prohibits
any loop).

The best I could think of is:

tmp = c(1,1,2,2,3,3,4,4)
u = unique(tmp)
sapply(u, function(x){ which(!is.na(match(tmp,x)))[1]} )

But there might be a useful function I don't know ..

Thanks for any hint.
All the best,

Emmanuel



More information about the R-help mailing list