R match() Function: How to Match Elements in R

The R match() function returns the position of the first match between two data objects. You can use the %in% operator If we want to know only whether the value has been matched.

R match() Function

The match() is a built-in R function that returns a vector of (first) matches of its first argument in its second argument. The %in% operator is a more intuitive interface as a binary operator, which returns a logical vector indicating a match or not for its left operand.

Syntax

match(x, table, nomatch = NA_integer_, incomparables = NULL)

x %in% table

Arguments

x: It is a vector or NULL to which the values to be matched.

table: It is a vector or NULL to which the values should be compared against.

nomatch: It is the value to be returned when there is no match.

incomparables: They are values to be excluded from the match function.

Return Value

It returns a vector of the same length as an input value.

Examples of match() function in R

Let’s define two vectors and use the match() function to match between two data objects.

rv <- 11
s_rv <- c(19, 21, 11, 18, 46)

match(rv, s_rv)

Output

[1] 3

The 3rd position has a value of 11, so the output will be 3.

Let’s match the two vectors with more than one element.

rv <- c(11, 12, 19, 22, 25)
s_rv <- c(19, 21, 11, 18, 46)

match(rv, s_rv)

Output

[1] 3 NA 1 NA NA

The above code returns the matched position (first matched position) of the first vector in the second vector; when no match is found, it returns NA will be returned.

match() function in R with nomatch=0

If the match is not found, then it is replaced with 0 instead of NA. So it will help us to replace the NA value with 0.

rv <- c(11, 12, 19, 22, 25)
s_rv <- c(19, 21, 11, 18, 46)

match(rv, s_rv, nomatch=0)

Output

[1] 3 0 1 0 0

Apply comparables to the match() function in R

If you want to exclude 11 value from the match() function, pass the comparables argument, so NA is returned for the position of value 11.

rv <- c(11, 12, 19, 22, 25)
s_rv <- c(19, 21, 11, 18, 46)

match(rv, s_rv, incomparables = 11)

Output

[1] NA NA 1 NA NA

Applying match() Function to String

We can apply the match() function to character strings as well. Consider the following example character string.

rc <- c("data", "tata", "ta", "a")

match("ta", rc)

Output

[1] 3

The first match of “ta” is at the third position. You can see that tata also contains ta, but it will not return its index because it will check for the specific word and not a word’s substring.

That is it for match() function in R.

Leave a Comment