Count consecutive numbers in a vector

2019-01-23 08:15发布

问题:

If I have a vector like

"a": 0 0 0 1 1 1 0 0 0 0 1 1 0 0 0

I want to know how many 1 are together in a, in this case the answer would be 3 and 2.

Is there any script that can do this?

回答1:

See ?rle.

## create example vector
a <- c(rep(0, 3), rep(1, 3), rep(0, 4), rep(1, 2), rep(0, 3))

## count continuous values
r <- rle(a)

## fetch continuous length for value 1
r$lengths[r$values == 1]
# [1] 3 2


回答2:

How about this?

test <- c(0,0,0,1,1,1,0,0,0,0,1,1,0,0,0)
rle(test)$lengths[rle(test)$values==1]
#[1] 3 2

For massive data, you can speed it up a bit using some convoluted selecting:

diff(unique(cumsum(test == 1)[test != 1]))
#[1] 3 2


回答3:

Others have answered the question. I would just like to add two observations:

Data entry trick: use scan (defaults to class "numeric", no need for rep's or comma's) and it also works for characters separated by whitespace if you add "character" as an argument.

a <- scan()
1: 0 0 0 1 1 1 0 0 0 0 1 1 0 0 0
16: 
Read 15 items

rle is really the inverse function for rep

 arle <- rle(a)
 rep(arle$values, arle$lengths)
 [1] 0 0 0 1 1 1 0 0 0 0 1 1 0 0 0


标签: r vector