Aggle
Aggle

Reputation: 31

Function for determine and count binary sequences

I'm looking the function (or package), which can doing subj. For example, I have a vector of binary sequences with "1" and "0", starting with "1" and finished at next "1" value, such "10", "10000", "1000", etc. Vector looking like this:

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

Finally, I need a vector with values, each of all representing length of consequentially sequences:

y <- functionname(x)
y
[1] 3 2 4 1 3 3 1

Upvotes: 2

Views: 64

Answers (3)

Sowmya S. Manian
Sowmya S. Manian

Reputation: 3843

cumsum(x)
[1] 1 1 1 2 2 3 3 3 3 4 5 5 5 6 6 6 7

table(cumsum(x))

# 1 2 3 4 5 6 7 
# 3 2 4 1 3 3 1 

unname(table(cumsum(x)))
# [1] 3 2 4 1 3 3 1

To get count of then in turn 1, 10, 100, 1000,..

table(table(cumsum(x)))
# 1 2 3 4 
# 2 1 3 1 

unname(table(table(cumsum(x))))
# 2 1 3 1

Upvotes: 4

Onyambu
Onyambu

Reputation: 79288

rle(cumsum(x))$length
[1] 3 2 4 1 3 3 1

Upvotes: 3

Brian Davis
Brian Davis

Reputation: 992

tapply(x,cumsum(x),length)
1 2 3 4 5 6 7 
3 2 4 1 3 3 1

Upvotes: 2

Related Questions