R chartr() Function

The chartr() function in R is used for character translation and replacement. It replaces all the matches of the existing characters of a string with the new characters specified as the argument.

This function is helpful for simple character substitutions in strings.

Syntax

chartr(old, new, x)

Parameters

  1. old: The old string is to be substituted.
  2. new: It is the new string.
  3. x: It is a target string.

Return value

It returns a modified string.

Ensure that the lengths of old and new are the same. If they are not, chartr() will either recycle the shorter one or throw an error, depending on the situation.

Example 1: Basic usage

Example 2 of chartr() function

# creating a string variable
main_str <- "Neo, you are in the matrix"

chartr("mat", "123", main_str)

Output

[1] "Neo, you 2re in 3he 123rix"

Example 2: Multiple strings

# Vector of strings
text_vector <- c("apple", "pear", "banana", "cherry")

# Replace 'a' with '1' and 'e' with '3' in each string of the vector
new_text_vector <- chartr("ae", "13", text_vector)

# Print the result
print(new_text_vector)

Output

[1] "1ppl3" "p31r" "b1n1n1" "ch3rry"

That’s it.

Leave a Comment