R计算向量中相同字符的部分

R count parts of same characters in vector

我有一个向量,它只包含 0 和 1,例如:

 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)

如何计算,一个向量中出现了多少次0的序列?

这意味着对于向量 a 我期待答案 3。 对于 b - 1,c - 3,d - 2.

使用rle:

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

对于所有 a、b、c、d:

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