char.expand in R: How to Find Unique Match of Elements

The char.expand() method is especially useful when abbreviations are allowed in function arguments and need to be uniquely expanded with respect to a target table of possible values.

char.expand in R

The char.expand() is a built-in function that seeks a unique match of its first argument among the elements of its second. If successful, it returns this element; otherwise, it performs an action specified by the third argument.


char.expand(input, target, nomatch = stop("no match"))


input: character string to be expanded.

target: character vector with the values to be matched against.

nomatch: an R expression to be evaluated in case expansion was not possible.

Return Value

It returns the length-one character vector, one of the elements of the target.


Let’s create a vector using the c() function and then use the char.expand() method.

var <- c("data", "meta", "sata")
char.expand("sa", var, warning("no expand"))


[1] "sata"

Let’s see other variants of this example.

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

char.expand("d", var, warning("no expand"))


[1] "data"

You can see that it can fetch unique results from only one keyword.

Let’s pass the keyword which will not match the elements of the vector and see the output.

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

char.expand("ta", var, warning("no expand"))


[1] NA
Warning message:
In eval(nomatch) : no expand

It returns NA when it does not find any match.

That is it for char.expand() Function in R.

Leave a Comment