Match function in R

March 1, 2017
By

(This article was first published on R – Greetz to Geeks, and kindly contributed to R-bloggers)

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 on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Sponsors

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)