- A+

Category：Languages

I'm trying to identify mismatched values based on one element value before or after the focal value in a vector. Any thought about how to do it?

Let's say, I have a vector: `x<-c(1,1,2,1,3,3)`

. If `element[i]`

matches with the element before or after item `i`

(`element[i-1]`

and `element[i+1]`

). If there is a match `element[i]`

should equal "yes", otherwise it should equal "no".

The expected output for `x<-c(1,1,2,1,3,3)`

should be `c("yes","yes","no","no","yes","yes")`

.

Use `rle()`

to identify runs of equal values. `rle(x)$length == 1`

means there is no equal values before or after the current one.

`rep(ifelse((len <- rle(x)$lengths) == 1, "no", "yes"), len) # [1] "yes" "yes" "no" "no" "yes" "yes" `

Edit: more concise version(thanks for **@dww's** comment)

`rep((len <- rle(x)$lengths) == 1, len) # [1] FALSE FALSE TRUE TRUE FALSE FALSE `