What is the match() function in R?
Overview
The match() function in R is used to:
- Return the index position of the first element present in a vector with a specific value.
- Return the index position of the first matching elements of the first vector in the second vector.
Syntax
match(x, table, nomatch = NA_integer_, incomparables = NULL)
Syntax for the match() function
Parameter values
The match() function takes the following parameter values:
x: This is the vector object that contains the values that need to be matched. This parameter value is required.table: This represents the values that are to be matched against the values of the vector object. This parameter value is required.nomatch: This is the value that is returned when no match is found. This parameter value is optional.incomparables: These are the vector values that cannot be matched. This parameter value is optional.
Return value
The match() function returns the index position of a specified value in a vector object. It can also return a vector of the same length as the input vector.
Example 1
To return the index position of the first element present in a vector:
# creating a vector objectmyvector <- c( 11, 18, 7, 38, 18, 98, 66, 7, 18, 42, 56, 13)# obtaining the index position of 18 in the vectormatch(18, myvector)
Explanation
- Line 2: We create a vector object called
myvector. - Line 5: We use the
match()function to obtain and print the value of the first index position of18inmyvector.
Example 2
To return the index position of the first matching elements of the first vector in the second vector:
# creating vector objectsa = c('one', 'two', 'three', 'four', 'five', 'four', 'three', 'two', 'one')b = c('five', 'two', 'four')# obtaining the index position of matching elements in b found in amatch(b, a)
Explanation
- Lines 2–3: We create the vector objects
aandb. - Line 6: We use the
match()function to obtain and print the index numbers of the elements inathat match any of the first entries of the elements inb.