R: Partial String Matching

charmatch {base} | R Documentation

## Partial String Matching

### Description

`charmatch` seeks matches for the elements of its first argument among those of its second.

### Usage

    charmatch(x, table, nomatch = NA_integer_)

### Arguments

`x` | the values to be matched: converted to a character vector by `as.character`.
`table` | the values to be matched against: converted to a character vector.
`nomatch` | the (integer) value to be returned at non-matching positions.

### Details

Exact matches are preferred to partial matches (those where the value to be matched has an exact match to the initial part of the target, but the target is longer).

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.

`NA` values are treated as the string constant `"NA"`.

### Value

An integer vector of the same length as `x`, giving the indices of the elements in `table` which matched, or `nomatch`.

### Author(s)

This function is based on a C function written by Terry Therneau.

### See Also

`pmatch`, `match`.

`grep` or `regexpr` for more general (regexp) matching of strings.

### Examples

    charmatch("", "")                             # returns 1
    charmatch("m",   c("mean", "median", "mode")) # returns 0
    charmatch("med", c("mean", "median", "mode")) # returns 2

[Package base version 2.15.1 Index]