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")
.
We can use the match() function to match the values in two vectors. We'll be using it to evaluate which values are present in both vectors, and how to reorder the elements to make the values match.
To find the row corresponding to a nearest value in an R data frame, we can use which. min function after getting the absolute difference between the value and the column along with single square brackets for subsetting the row.
The match() function in R is used to: Return the index position of the first element present in a vector with a specific value. Return the index position of the first matching elements of the first vector in the second vector.
Find positions of Matching Elements between Vectors in R Programming – match() Function. match() function in R Language is used to return the positions of the first match of the elements of the first vector in the second vector. If the element is not found, it returns NA.
Use rle()
to identify runs of equal values. lengths == 1
means there is no equal values before or after the current one.
with(rle(x), rep(ifelse(lengths == 1, "no", "yes"), lengths))
# [1] "yes" "yes" "no" "no" "yes" "yes"
Edit: more concise version(thanks for @dww's comment)
with(rle(x), rep(lengths != 1, lengths))
# [1] TRUE TRUE FALSE FALSE TRUE TRUE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With