1

Let us consider a binary sequence like the following

00001001110000011000000111111

I would like to count the repeated 1s in the sequence, as follows

00001001230000012000000123456

I was thinking of the following solution

> b<-c(0,0,0,0,1,0,0,1,1,1,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,1,1,1,1)
> rle(b)
  Run Length Encoding
  lengths: int [1:8] 4 1 2 3 5 2 6 6
  values : num [1:8] 0 1 0 1 0 1 0 1

but the result in "lengths" and "num" do not apply to my case.

Mark
  • 1,577
  • 16
  • 43

1 Answers1

1

We can either use the built-in function rleid from data.table to use as a grouping variable in ave, get the sequence and multiply with 'b' so that any value that is 0 will be 0 after the multiplication

library(data.table)
ave(b, rleid(b), FUN = seq_along)*b
#[1] 0 0 0 0 1 0 0 1 2 3 0 0 0 0 0 1 2 0 0 0 0 0 0 1 2 3 4 5 6

Or using rle from base R, we create a group by replicating the sequence of 'values' with the 'lengths' and then use it in ave as before

grp <- with(rle(b), rep(seq_along(values), lengths))
ave(b, grp, FUN = seq_along)*b
#[1] 0 0 0 0 1 0 0 1 2 3 0 0 0 0 0 1 2 0 0 0 0 0 0 1 2 3 4 5 6
akrun
  • 874,273
  • 37
  • 540
  • 662