Rafael
Rafael

Reputation: 3196

increase non sequential ones by one in a vector

I have a vector of 1s and 0s. I would like to replace the 1s with its "spot" in the vector.

For example I would like to change

 x = c(1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1)

to

1 1 1 0 2 2 2 0 0 3 0 4

The numbers of 1s and 0s in a row can change.

Upvotes: 2

Views: 38

Answers (3)

akrun
akrun

Reputation: 887881

Here is an option with rle and inverse.rle

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

Or an option using rleid from data.table

library(data.table)
x1 <- rleid(x)
x1[x!= 0] <- rleid(x1[x!=0])
x1 * x
#[1] 1 1 1 0 2 2 2 0 0 3 0 4

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389265

Another way with rle

x * with(rle(x), rep(cumsum(values), lengths))
#[1] 1 1 1 0 2 2 2 0 0 3 0 4

We create a run-length sequence of x and repeat cumsum of values lengths time and multiply it by x so that 0's remain as 0's and only 1's are changed.

Upvotes: 0

Andrew Gustar
Andrew Gustar

Reputation: 18435

Here is one way to do it...

x = c(1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1)

x[x==1] <- cumsum(c(x[1], diff(x)) == 1)[x==1]

x
 [1] 1 1 1 0 2 2 2 0 0 3 0 4

Upvotes: 2

Related Questions