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
  • 65,555
  • 14
  • 143
  • 159
Coolwater
  • 703
  • 8
  • 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
  • 377,200
  • 20
  • 156
  • 213
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
  • 23,310
  • 7
  • 53
  • 72
2

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

match(c(4,3,5,56), vec)
Quinten
  • 35,235
  • 5
  • 20
  • 53