Substitute characters of a String in R Programming – chartr() Function

chartr() function in R Programming Language is used to do string substitutions. It replaces all the matches of the existing characters of a string with the new characters specified as arguments.

Syntax: chartr(old, new, x)

Parameters: 

  • old: old string to be substituted
  • new: new string
  • x: target string

Example 1: 

R




# R program to illustrate
# chartr function
 
# Initializing a string
x <- "Beginner GFG"
 
# Calling the chartr() function
# which will substitute G with Z
# to the above specified string
chartr("G", "Z", x)


Output : 

[1] "Zeeks ZFZ"

Example 2: 

R




# R program to illustrate
# chartr function
 
# Initializing a string
x <- "w3wiki Beginner"
 
# Calling the chartr() function
# which will substitute G with 1,
# k with 2 and s with 3
# to the above specified string
chartr("Gks", "123", x)


Output: 

[1] "1ee23for1ee23 1ee23"

Contact Us