Count consecutive numbers in 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 which case the answer will be 3 and 2.

Could this be a script?

+7
source share
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 
+17
source

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 collapsed selection:

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

Others answered the question. I would just add two points:

Data entry thread: use scan (the default for the class is "numeric", no rep or comma is needed), and it also works for characters separated by a space if you add a "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 really is 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 
+5
source

All Articles