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)
- old: The old string is to be substituted.
- new: It is the new string.
- x: It is a target string.
The chartr() function returns a modified string.
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)
 "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.
# creating a string variable main_str <- "Neo, you are in the matrix" chartr("mat", "123", main_str)
 "Neo, you 2re in 3he 123rix"
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.