How to Use the charmatch() Function in R

The charmatch() function in R is “used to find to seek matches for the elements of its first argument among those of its second. For example, charmatch(c(“a”, “b”, “c”), c(“a”, “c”)) returns c(1, NA, 2).

Syntax

charmatch(x, table, nomatch = NA_integer_)

Parameters

  1. x: It is the values to be matched.
  2. table: It is the values to be matched against.
  3. nomatch: It is the (integer) value to be returned at non-matching positions.

Return Value

The charmatch() function returns an integer vector of the same length as the input R object, giving the indices of the items in the table which matched or nomatch.

Example 1: R program to use charmatch() Function

Using the c() function with three elements, let’s create a vector.

var <- c("data", "meta", "sata")

charmatch("me", var)

Output

[1] 2

You can see that the charmatch() function returns the index of the matching element.

Example 2: Partial match

Exact matches are preferred to partial matches. Let’s pass on the different arguments.

var <- c("data", "meta", "sata")

charmatch("sa", var)

Output

[1] 3

If there is a single exact match or no exact match and a unique partial match, then the index of the matching value is returned; if multiple exact or multiple partial matches are found, then 0 is returned, and if no match is found, then nomatch is returned.

If no match is found, then it returns NA.

var <- c("data", "meta", "sata")

charmatch("ne", var)

Output

[1] NA

That’s it.

Leave a Comment