Search code examples
rperformancevectorpositionfind-occurrences

R function that return a vector with position occurence of each value?


I am searching for a function that return a vector with the position/count of each value of a vector.

Here an example :

I have :

vec<-c("A","A","A","B","B","C")

I want :

c(1,2,3,1,2,1)

I have created a function that works but I am looking for a faster way to get it, as I have a big dataset.

Thank you very much in advance


Solution

  • One way would be to use ave in base R :

    vec<-c("A","A","A","B","B","C")
    result <- as.integer(ave(vec, vec, FUN = seq_along))
    result
    [1] 1 2 3 1 2 1