How to Use the chartr() Function in R

The chartr() function in R is “used to replace an instance of an old character with a new character in the specified string. It replaces all the matches of the existing characters of a string with the new characters specified as the argument.


chartr(old, new, x)


  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

The chartr() function returns a modified string.

Example 1

Let’s define a character vector and replace one character with another character. The chartr() is case sensitive function.

data <- "Expecto Patronum"

chartr("P", "M", data) 


[1] "Expecto Matronum"

You can see capital M replaces that capital P. So the small p in Expecto is as it is.

So, the chartr() function is proper when replacing a character in the R string.

Example 2

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

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


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

That’s it.

Leave a Comment