R chartr() Function: How to Substitute characters of String

The chartr() function in R language translates the characters in character vectors, particularly from upper to lower case or vice versa. The chartr() function is used to substitute characters of a string. 

R chartr() Function

The chartr() is a built-in R function that is used to do string substitutions. The chartr() function 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 to be substituted.

new: It is the new string.

x: It is a target string.

The chartr() function translates each character in x specified in old to the corresponding character set in new.


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) 


[1] "Expecto Matronum"

You can see that capital P is replaced by capital M. The small p in Expecto is as it is.

So, the chartr() function is useful when replacing a character in the R string.

That is it for chartr() function in R.

See also

Convert String to Lowercase

Convert String to Uppercase

Leave a Comment