Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a value in a vector with the one before and after in r?

Tags:

r

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").

like image 364
Alaa Avatar asked Jan 10 '19 16:01

Alaa


People also ask

How do I match two values of a vector in R?

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.

How do I get corresponding values in R?

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.

How do you use matches in R?

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.

How do you find matches in R?

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.


1 Answers

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
like image 78
Darren Tsai Avatar answered Oct 10 '22 23:10

Darren Tsai