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

The match() function in R is used to match the values in two vectors and return the position of the elements of the first vector in the second vector. It takes two vectors as arguments and returns a vector of the positions of the first argument in the second. It is useful for performing lookups in a data frame or vector and can be used in combination with other functions like subset() or with() to quickly extract data. Examples of the use of the match() function can be found in the R documentation.


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.

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

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

x