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
- old: The old string is to be substituted.
- new: It is the new string.
- 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
# 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.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.