1

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

2 Answers2

0

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
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

We can use rowid from data.table

library(data.table)
rowid(vec)
#[1] 1 2 3 1 2 1
akrun
  • 874,273
  • 37
  • 540
  • 662