Marta
Marta

Reputation: 3843

R count parts of same characters in vector

I've a vector, that consist only from 0 and 1, for example:

 a<-c(0,0,1,1,1,0,0,0,1,1,0,1)
 b<-c(0,0,1,1)
 c<-c(0,1,0,1,0,1)
 d<-c(1,0,0,1,0,1)

How to count, how many times in a vector appears sequences of 0?

It means that for vector a I expect answer 3. For b - 1, c - 3, d - 2.

Upvotes: 1

Views: 66

Answers (1)

agstudy
agstudy

Reputation: 121568

Using rle:

sum(rle(a)$values==0)

For all a,b,c,d:

sapply(list(a,b,c,d),function(x)sum(rle(x)$values==0))
[1] 3 1 3 2

Upvotes: 4

Related Questions