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.
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