Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function for determine and count binary sequences

Tags:

r

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
like image 557
Aggle Avatar asked Sep 22 '26 17:09

Aggle


1 Answers

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
like image 155
Sowmya S. Manian Avatar answered Sep 25 '26 06:09

Sowmya S. Manian