how to elegantly substitute repeated values with a different vector?

Viewed 44

In R, a vector like this:

x <- c(0,0,1,1,0,0,1,1,0,0,1,1,1,1,0,1,0,1,0,1)

I want x to be like this:

y = c(0,0,1,1,0,0,2,2,0,0,3,3,3,3,0,4,0,5,0,6)

Could anyone help me solve this question?

1 Answers

An option would be rle

inverse.rle(within.list(rle(x), values[values!=0] <- seq_along(values[values!=0])))
#[1] 0 0 1 1 0 0 2 2 0 0 3 3 3 3 0 4 0 5 0 6

Or with rleid from data.table

library(data.table)
x1 <- x*rleid(x)
match(x1, unique(x1[x1!=0]), nomatch = 0)
#[1] 0 0 1 1 0 0 2 2 0 0 3 3 3 3 0 4 0 5 0 6
Related