charmatch in R: How to Do Partial String Matching in R

The charmatch() function attempts to match the elements of its first argument among those of its second.

charmatch in R

The charmatch() is a built-in R function that finds matches between two arguments. To do a Partial String Matching in R, use the charmatch() function. The charmatch() function accepts three arguments and returns the integer vector of the same length as input.


charmatch(x, table, nomatch = NA_integer_)


x: It is the values to be matched.

table: It is the values to be matched against.

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.


Let’s create a vector using the c() function with three elements.

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

charmatch("me", var)


[1] 2

You can see that the charmatch() function returns the index of the matching element. Exact matches are preferred to partial matches.

Let’s pass on the different arguments.

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

charmatch("sa", var)


[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)


[1] NA

That is it for charmatch() function in R.

See also

char.expand in R

endingString in R

chartr in R

nchar in R

as.character in R

Leave a Comment