When writing code, at some point you might want to replace a particular character of a string variable at once, and you may not have an idea how to do it. This shot explains how to conveniently do just that.
To replace a character, especially an old character of a string in R, we use the chartr()
function.
The chartr()
function in R replaces an instance of an old character with a new character in the specified string set.
chartr(old, new, x)
The chartr()
function takes the following parameter values:
old
: This represents the old character of the specified string you wish to replace.new
: This represents the new character.x
: The specified string.The chartr()
function returns a modified string.
# creating a string variablemystring = "Hi Theo would you like to have some cookies?"# replacing "o" with "U" using the chartr() functionchartr("o", "U", mystring)
mystring
.chartr()
function, we change every instance of the o
character in the string to U
.Interestingly, the chartr()
function does not apply to just a single character but also to multiple characters.
# creating a string variablemystring = "Hi Theo would you like to have some cookies?"# replacing "o" with "1", "u" with "2" and "e" with "3"chartr("oue", "123", mystring)
Line 5: We change multiple characters o
, u
, and e
to 1
, 2
and 3
respectively at any of their instances in the string mystring
.