0
v <- c(1,1,2,3,3,3,1,1,3,4,4)

I'm trying to create a vector of elements in which the first occurrence of a non-repeated number always increases by one relative to the previous number.

This is the desired output

1,1,2,3,3,3,4,4,5,6,6

What would an efficient way of doing this would be?

HappyPy
  • 9,839
  • 13
  • 46
  • 68

1 Answers1

2

A base R option with rle

> with(rle(v),rep(seq_along(values),lengths))
 [1] 1 1 2 3 3 3 4 4 5 6 6

or data.table::rleid

> data.table::rleidv(v)
 [1] 1 1 2 3 3 3 4 4 5 6 6
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81