Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count consecutive numbers in a vector

Tags:

r

vector

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?

like image 719
Simon Avatar asked May 17 '12 21:05

Simon


3 Answers

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
like image 61
sgibb Avatar answered Sep 17 '22 14:09

sgibb


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
like image 37
IRTFM Avatar answered Sep 20 '22 14:09

IRTFM


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
like image 41
thelatemail Avatar answered Sep 17 '22 14:09

thelatemail