The number of stretches in the vector when the par

2019-07-31 08:13发布

问题:

How can I find the number of stretches (blocks) in the vector when the param is equal to 0? In this example, the answer would be 3.

The vector param:

param <- c(25, 20, 18, 5, 1, 0, 0, 0, 1, 5, 0, 0, 3, 6, 9, 0, 0)

回答1:

I'm going to assume a "stretch" is at least two or more values. But with your test data

x<- c(25, 20, 18, 5, 1, 0, 0, 0, 1, 5, 0, 0, 3, 6, 9, 0, 0)

I would use the rle() function to calculate the run lengths

with(rle(x), sum(values==0 & lengths>1))
# [1] 3


标签: r vector