lg929
lg929

Reputation: 234

How to count number of occurrences of a consecutive string of the same number in R

I have a string of 0's and 1's like this in R:

x<-c(1,1,1,0,0,1,1,0,0,1,0,1,1,1,1,1,0,1,1,1)

I would like to count how many strings of 1's there are (i.e., with no 0's in between). For my example here, I'd like to get the output 4, since there are 4 strings of 1's that are consecutive.

Let me know if I should clarify what I mean.

Thanks in advance for your help!

Upvotes: 1

Views: 154

Answers (1)

akrun
akrun

Reputation: 886978

We can try rle

sum(with(rle(x), lengths[!!values])>1)
$[1] 4

Or

sum(with(rle(x!=0), lengths*values)>1)

Or with rleid

library(data.table)
sum(table(rleid(x)[x!=0])>1)
#[1] 4

Upvotes: 2

Related Questions