match Function in R with examples

match Function in R, The position of the first match between two objects is returned by the match() function in R.

The following is the fundamental syntax for this function.

match (object1, object2)

The examples below demonstrate how to utilize this function in various contexts.

Match One Value in a Vector (Example 1)

To discover the first occurrence of a certain value in a vector, use the match() function as shown below.

Syntax

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

First, will define a value to look for in vector.

FindPositionof <- 20

Now we create a vector of values.

vector <- c(82,58, 89,81, 210, 20, 115)

Yes, let’s find the first occurrence of value 20

match(FindPositionof, vector)
[1] 6

This indicates that the number 20 appears for the first time at the sixth position of the vector.

If there are numerous values that match, only the first match’s position will be returned.

The following vector, for example, has three values of twenty.

Define the value to search for in the vector

FindPositionof <- 20

Create a value vector with several ’20’ values

vector <- c(20, 20, 10, 120, 110, 20)

As usual, let’s find the first occurrence of 20

match(FindPositionof, vector)
[1] 1

Positions 1, 2, and 6 all have the value 20, however, only position 1 is returned.

Matching Values in Two Vectors (Example 2)

The following code demonstrates how to use the match() method to locate the first occurrence of values from one vector in another.

Let’s define two vectors

vector1 <- c(55, 22, 13, 45, 15, 86)
vector2 <- c(55, 86, 11, 210, 120, 125)

We can now locate the first occurrence of vector1 values within vector2.

match(vector1, vector2)
[1]  1 NA NA NA NA  2

Here’s how to interpret the output:

In vector1, the value 55 appears for the first time in position 1 of vector2.

Vector2 never contains the number 22 from vector1.

Vector2 never contains the number 13 from vector1.

Vector2 never contains the value 45 from vector1.

Vector2 never contains the value 15 from vector1.

In vector1, the value 86 appears for the first time in position 2 of vector2.

In circumstances where there is no match, we can alternatively give a different value to use.

Instead of NA, we could, for example, return a value of 0:

vector1 <- c(55, 22, 13, 45, 15, 86)
vector2 <- c(55, 86, 11, 210, 120, 125)

within vector2 identify the first occurrence of values in vector1

match(vector1, vector2, nomatch=0)
[1] 1 0 0 0 0 2

Conclusion

The position of the first match between two R objects is returned by the match() function.

Handling missing values in R Programming » finnstats

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

five × four =