Open In App

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

Last Updated : 23 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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 <- "Geeks 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 <- "GeeksforGeeks Geeks"

# 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"

Next Article

Similar Reads