Find positions of Matching Elements between Vectors in R Programming – match() Function

match() function in R Language is used to return the positions of the first match of the elements of the first vector in the second vector. If the element is not found, it returns NA.

Syntax: match(x1, x2, nomatch)

Parameters:
x1: Vector 1
x2: Vector 2
nomatch: value to be returned in case of no match

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to match the vectors
  
# Creating vectors
x1 <- c("a", "b", "c", "d", "e")
x2 <- c("d", "f", "g", "a", "e", "k")
  
# Calling match function
match(x1, x2)

chevron_right


Output:

[1]  4 NA NA  1  5

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to match the vectors
  
# Creating vectors
x1 <- c("a", "b", "c", "d", "e")
x2 <- c("d", "f", "g", "a", "e", "k")
  
# Calling match function
match(x1, x2, nomatch = "-1")

chevron_right


Output:

[1]  4 -1 -1  1  5
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.