1

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
mariotomo
  • 9,438
  • 8
  • 47
  • 66
  • 1
    Duplicate: http://stackoverflow.com/questions/1502910/ – Rob Hyndman Apr 15 '10 at 09:29
  • I upvoted the comment because I found the link useful, but I don't think this is a duplicate question. I'm still using my own solution in the code I'm distributing to my users. – mariotomo Jul 05 '10 at 13:59

1 Answers1

2

writing questions here helps thinking about solutions... and I found a related question so I could come up with this one:

contiguousequal <- function(data, value, position) {
  if(data[position] != value)
    return(rep(FALSE, length(data)))
  id <- cumsum(c(1, as.numeric(diff(data) != 0)))
  id == id[position]
}
Community
  • 1
  • 1
mariotomo
  • 9,438
  • 8
  • 47
  • 66