We know that the duplicated() function outputs a vector of logicals. What I want, however, is a vector of integers such that, if this is the (n+1)th time that this particular el
Here's a possible solution using base R (not sure if vectorized enough for you)
as.numeric(ave(x, x, FUN = seq)) - 1L
## [1] 0 0 1 0 1 2 1 3 4 2
Or something similar using data.table
package
library(data.table)
as.data.table(x)[, y := seq_len(.N) - 1L, by = x][]
# x y
# 1: c 0
# 2: b 0
# 3: b 1
# 4: a 0
# 5: a 1
# 6: b 2
# 7: c 1
# 8: b 3
# 9: b 4
# 10: c 2
Or maybe a dplyr
option
library(dplyr)
data.frame(x) %>%
group_by(x) %>%
mutate(y = row_number() - 1L)
# Source: local data frame [10 x 2]
# Groups: x
#
# x y
# 1 c 0
# 2 b 0
# 3 b 1
# 4 a 0
# 5 a 1
# 6 b 2
# 7 c 1
# 8 b 3
# 9 b 4
# 10 c 2