2

How can we in a, obtain the index of the first element of the repeated value (index of first 1, first 2, first 3 ...)?

a <- c(rep(1, 3), rep(2, 2), rep(3, 1), rep(4, 2))

desired.output <- c(1, 4, 6, 7)
  • 2
    Essentially answered here - https://stackoverflow.com/questions/5577727/is-there-an-r-function-for-finding-the-index-of-an-element-in-a-vector – thelatemail Nov 19 '19 at 22:20
  • Also `sapply(unique(a), function(x) which.max(x == a))` but there are much better answers already. – Ronak Shah Nov 19 '19 at 23:49

2 Answers2

6

Another option is match

match(unique(a), a)
# [1] 1 4 6 7

From help('match')

match returns a vector of the positions of (first) matches of its first argument in its second.

markus
  • 25,843
  • 5
  • 39
  • 58
3

One option is tapply

as.vector(tapply(seq_along(a), a, FUN = `[`, 1))
#[1] 1 4 6 7

Or using

which(!duplicated(a))

Or with which and diff

which(c(TRUE, !!diff(a)))

Or when the vector is not numeric

which(c(TRUE, a[-1] != a[-length(a)]))
akrun
  • 874,273
  • 37
  • 540
  • 662