A4747
A4747

Reputation: 95

Extracting count of continuous non-zero values from vector

Suppose I have a vector

x<-c(1,2,3,4,5,6,7,0,0,1,2,3,0,0,0,3,0,1)

I want to get how long the values in the vector are contiguously non-zero. Meaning for this case I want to get 7, 3, 1, 1.

How can I do this?

Upvotes: 1

Views: 195

Answers (1)

tmfmnk
tmfmnk

Reputation: 40171

One option could be:

with(rle(x != 0), lengths[values])

[1] 7 3 1 1

Upvotes: 2

Related Questions