How to replace an instance of an old character of a string in R

Overview

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.

Replacing a string character

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.

Syntax

chartr(old, new, x)

Parameters

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.

Return value

The chartr() function returns a modified string.

Example 1

# creating a string variable
mystring = "Hi Theo would you like to have some cookies?"
# replacing "o" with "U" using the chartr() function
chartr("o", "U", mystring)

Explanation

  • Line 2: We create a string variable mystring.
  • Line 5: Using the 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.

Example 2

# creating a string variable
mystring = "Hi Theo would you like to have some cookies?"
# replacing "o" with "1", "u" with "2" and "e" with "3"
chartr("oue", "123", mystring)

Explanation

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.

Free Resources