The char.expand() function in R is “used to seek 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.
Syntax
char.expand(input, target, nomatch = stop("no match"))
Parameters
- 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 impossible.
Return Value
It returns the length-one character vector, one of the elements of the target.
Example 1: Using char.expand() function with Vector
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"))
Output
[1] "sata"
Example 2: Another example
var <- c("data", "meta", "sata")
char.expand("d", var, warning("no expand"))
Output
[1] "data"
You can see that it can fetch unique results from only one keyword.
Example 3: Third example
Let’s pass the keyword that will not match the vector elements and see the output.
var <- c("data", "meta", "sata")
char.expand("ta", var, warning("no expand"))
Output
[1] NA
Warning message:
In eval(nomatch) : no expand
It returns NA when it does not find any match.
That’s it.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language.