R Match – Using match() and %in% to compare vectors

Today we’re going to discuss how to compare two R vectors for the elements (values) which they have in common. We have two options here:

  • The R match () function – returns the indices of common elements
  • the %in% operator – returns a vector of True / False results which indicates if a value in the first vector was present in the second.

R Match – Finding Values in Vectors

Let us get started with the R match () function.

# r match example
> codes = c(10,11,22,12,12,13,34)
# r match example - returns first position of matching value
> match(22, codes)
[1] 3
# r match example - returns first position of repeat values
> match(12, codes)
[1] 4
# r match example - with multiple values
> match (c(22,12), codes)
[1] 3 4

In this example, we searched a vector of numbers for a specific value (22) using the r match function. It returned a vector indicating the value was found in the second position. When we repeated the search, using r match to spot a second value (12), it returns only the first example.

If we feed the R match function a vector of multiple values, it returns the first position of each of the two values.

%in% Operator – Boolean Equivalent

Just need a True / False result?

Consider using the %in% operator. It performs a similar operation and returns the result as a Boolean indicator showing if the value is present.

# R %in% operator example

# check for single value using %in% operator
> 36 %in% codes
[1] FALSE

# check for vector of multiple values using %in% operator
> c(22, 12) %in% codes
[1] TRUE TRUE

# how the %in% operator handles values it doesn't find
> c(22, 12, 43) %in% codes
[1]  TRUE  TRUE FALSE

Summary – R Match and %in% operator

These two tools give us the ability to compare the values of two vectors.