Match() Function in R , returns the position of first occurrence of elements of Vector 1 in Vector 2. If an element of vector 1 doesn’t match any element of vector 2 then it returns “NA”. Output of Match Function in R will be a vector.
Syntax of Match function in R:
|v1||Vector to which the values to be matched|
|v2||Vector to which the values should be matched against|
|nomatch||Value to be returned when there is no match|
|incomparables||Values to be excluded from the match function|
Examples of Match function:
# Simple match function in R print(match(10, c(1,12,19,10,3,11,5,10,4)))
4th position has value 10, so the output will be
# match function in R with vectors v1 <- c(2,5,6,3,7) v2 <- c(15,16,7,3,2,7,5) match(v1,v2)
The above code returns the matched position (first matched position) of first vector in second vector, when no match found it returns NA. so the output will be
match function in R with nomatch=0:
# match function in R with nomatch=0 match(v1,v2,nomatch=0)
if the match not found then it is replaced with 0 instead of NA. so the output will be
match function in R with incomparables:
# match function in R with incomparables match(v1,v2,incomparables=2)
In the above example value 2 is excluded from the match function, so NA is returned for the position of value 2, so the output will be
If we want to know, only whether the value has been matched or not then we can use %in% operator.
# return whether the value is matched or not v1 %in% v2
So, the 3rd value in vector1 doesn’t have any match in vector2.