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.
Syntax
chartr(old, new, x)
Parameters
- old: The old string is to be substituted.
- new: It is the new string.
- 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)
Output
[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)
Output
[1] "Neo, you 2re in 3he 123rix"
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.