find contiguous stretches of equal data in a vector

Posted by mariotomo on Stack Overflow See other posts from Stack Overflow or by mariotomo
Published on 2010-04-15T08:23:32Z Indexed on 2010/04/15 8:53 UTC
Read the original article Hit count: 244

Filed under:

I have a numeric vector, it contains patches of elements that are repeating, something like:

R> data <- c(1,1,1,2,2,2,3,3,2,2,2,2,2,3,3,1,1,1,1,1)
R> data
 [1] 1 1 1 2 2 2 3 3 2 2 2 2 2 3 3 1 1 1 1 1
R> 

I need to extract contiguous patches of elements equals to a specific value... but I'm only interested in the patch around a specific position. so, my input is: (1) the numeric vector, (2) the desired value, (3) the position. I want to return a logic vector indicating which positions satisfy the request.

if at that position the data does not equal the value, I return all FALSE.

possible outcomes that are not all F would be:

 [1] 1 1 1 2 2 2 3 3 2 2 2 2 2 3 3 1 1 1 1 1

 [1] T T T F F F F F F F F F F F F F F F F F
 [2] F F F T T T F F F F F F F F F F F F F F
 [3] F F F F F F T T F F F F F F F F F F F F
 [4] F F F F F F F F T T T T T F F F F F F F
 [5] F F F F F F F F F F F F F T T F F F F F
 [6] F F F F F F F F F F F F F F F T T T T T

© Stack Overflow or respective owner

Related posts about r