Is there a faster way to make a counter index than using a loop? Within continuous runs of equal values, the index must be the same. I think the cycle is very slow, especially when the data is so big.
The input and the desired output are shown for illustration.
x <- c(2, 3, 9, 2, 4, 4, 3, 4, 4, 5, 5, 5, 1)
Desired Result Counter:
c(1, 2, 3, 4, 5, 5, 6, 7, 7, 8, 8, 8, 9)
Please note that non-contiguous runs have different indices. For instance. see desired indices of values 2 and 4
My inefficient code:
group[1]<-1 counter<-1 for (i in 2:n){ if (x[i]==x[i-1]){ group[i]<-counter }else{ counter<-counter+1 group[1]<-counter} }