Reputation: 5
I am calculating how many consecutive 0s or 1s in a sequence of 10 numbers.
For example 0 0 1 0 1 1 0 1 0 1 1 1
There are 4 (00, 11, 11, 11).
Here is my code.
c <- floor(2 * runif(10))
count = 0
for (i in 1:length(c)) {
a = c[i]
b = c[i+1]
if (a == b) {
count = count + 1
}
count
}
Error: Error in if (a == b) {: missing value where TRUE/FALSE needed
Thank you.
Upvotes: 0
Views: 39
Reputation: 389325
We can use rle
:
with(rle(x), sum(lengths[lengths > 1] - 1))
#[1] 4
data
x <- c(0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1)
Upvotes: 1