How to Use the char.expand() Function in R

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

  1. input: character string to be expanded.
  2. target: character vector with the values to be matched against.
  3. 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.

Leave a Comment