Match function in R

[This article was first published on R – Greetz to Geeks, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

The match() function returns a vector of the position of first occurrence of the vector1 in vector2. If the element of the vector1 does not exist in vector2, NA is returned.

Syntax: match(vector1, vector2, nomatch = NA_integer_, incomparables = NULL)

vector1: vector, the values to be matched
vector2: vector, the values to be matched against
nomatch: the value which should be returned when no match is found
incomparables: the vector of values that cannot be matched.

By default the nomatch argument will return NA in case the match is not found in vector2.

According to the R Documentation  the %in% operator is equivalent to match(). It is a logical vector which indicates whether a match was located for vector1 in vector2. The result value will be either TRUE or FALSE but never NA. So the %in% operator can be useful in if conditions.

Syntax: vector1 %n% vector2

Examples:

print(match(5, c(1,2,9,5,3,6,7,4,5)))
[1] 4


5 %in% c(1,2,9,5,3,6,7,4,5)
[1] TRUE


8 %in% c(1,2,9,5,3,6,7,4,5)
[1] FALSE


> v1 <- c("a1","b2","c1","d2")
> v2 <- c("g1","x2","d2","e2","f1","a1","c2","b2","a2")
> x <- match(v1,v2)
> x
[1] 6 8 NA 3


> v1 <- c("a1","b2","c1","d2")
> v2 <- c("g1","x2","d2","e2","f1","a1","c2","b2","a2")
> v1 %in% v2
[1] TRUE TRUE FALSE TRUE


> v1 <- c("a1","b2","c1","d2")
> v2 <- c("g1","x2","d2","e2","f1","a1","c2","b2","a2")
> x <- match(v1,v2, nomatch = 0)
> x
[1] 6 8 0 3


> v1 <- c("a1","b2","c1","d2")
> v2 <- c("g1","x2","d2","e2","f1","a1","c2","b2","a2")
> x <- match(v1,v2, nomatch = 0, incomparables = "a1")
> x
[1] 0 8 0 3

 

 

 

 

 

 

 

 

 

 

 

To leave a comment for the author, please follow the link and comment on their blog: R – Greetz to Geeks.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)