Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of alternations in a coin flip sequence

I have a sequence of ones and zeros and I would like to count the number of alternations. e.g.

x <- rbinom(10, 1, 1/2)
> x
 [1] 0 0 1 1 1 1 1 0 1 0

Thus I would like to count (in R) how many times the sequence alternates (or flips) from one to zero. In the above sequence the number of alternations (counted by hand) is 4.

like image 724
Frank Zafka Avatar asked Nov 30 '22 18:11

Frank Zafka


1 Answers

You can use diff() :

> x <- rbinom(10,1,1/2)

> x
 [1] 0 0 0 1 1 1 1 0 1 0

> sum(diff(x)!=0)
[1] 4
like image 97
Joris Meys Avatar answered Dec 15 '22 13:12

Joris Meys