How to Use match() Function in R (With Examples)


The match() function in R returns the position of the first match between two objects.

This function uses the following basic syntax:

match(object1, object2)

The following examples show how to use this function in different scenarios.

Example 1: Match One Value in Vector

The following code shows how to use the match() function to find the first occurrence of a specific value in a vector:

#define value to look for in vector
value <- 10

#define vector of values
vector1 <- c(8, 9, 1, 10, 13, 15)

#find first occurrence of 10
match(value, vector1)

[1] 4

This tells us that the value 10 first occurs in the 4th position of the vector.

Note that if there are multiple values that match, only the position of the first match will be returned.

For example, the following vector has two values equal to 10 but only the position of the first 10 is returned:

#define value to look for in vector
value <- 10

#define vector of values with multiple '10' values
vector1 <- c(8, 9, 1, 10, 10, 10)

#find first occurrence of 10
match(value, vector1)

[1] 4

The value 10 occurs in positions 4, 5, and 6, but only position 4 is returned.

Example 2: Match Values in Two Vectors

The following code shows how to use the match() function to find the first occurrence of values in one vector in another vector:

#define vectors of values
vector1 <- c(1, 2, 3, 4, 5, 6)
vector2 <- c(8, 6, 1, 10, 10, 15)

#find first occurrence of values in vector1 within vector2
match(vector1, vector2)

[1]  3 NA NA NA NA  2

Here’s how to interpret the output:

  • The first occurrence of the value 1 in vector1 occurs in position 3 of vector2.
  • The value 2 in vector1 never occurs in vector2.
  • The value 3 in vector1 never occurs in vector2.
  • The value 4 in vector1 never occurs in vector2.
  • The value 5 in vector1 never occurs in vector2.
  • The first occurrence of the value 6 in vector1 occurs in position 2 of vector2.

Note that we can also specify a different value to use in cases where there is no match.

For example, we could return a value of 0 instead of NA:

#define vectors of values
vector1 <- c(1, 2, 3, 4, 5, 6)
vector2 <- c(8, 6, 1, 10, 10, 15)

#find first occurrence of values in vector1 within vector2
match(vector1, vector2, nomatch=0)

[1] 3 0 0 0 0 2

Additional Resources

The following tutorials explain how to use other common functions in R:

How to Use summary() Function in R
How to Use the replicate() Function in R
How to Use the gsub() Function in R
How to Use the par() Function in R

Leave a Reply

Your email address will not be published.