3

I have a vector and I want to get the location (indices) of the first occurrence of each unique value.

vec <- c(4,4,4,3,3,3,5,4,5,4,3,3,56)
(pos <- ?????????)

I want in return

# 1  4  7  13

I.e. 1 is the first index of 4, 4 is the first index of 3, and so on.

Henrik
  • 61,039
  • 13
  • 131
  • 152
Coolwater
  • 663
  • 7
  • 15

3 Answers3

6

Similar to @Pratik's approach

You can use match along with unique

match(unique(vec), vec)

#[1]  1  4  7 13
Ronak Shah
  • 355,584
  • 18
  • 123
  • 178
2

The following code should do the trick for you:

vec <- c(4,4,4,3,3,3,5,4,5,4,3,3,56)

firstUniqueOccurrence <- function(vec) {
    unq <- unique(vec)
    sapply(unq, function(x) {min(which(vec == x))})
}

firstUniqueOccurrence(vec)

[1]  1  4  7 13
Sergey Bushmanov
  • 19,458
  • 6
  • 44
  • 60
2

As per you your vector element, try using below command to get the desired output.

match(c(4,3,5,56), vec)