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
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]
}
精彩评论