The R programming language comes with a number of useful built-in functions to work with strings. In this tutorial, we will look at how to replace a character in a string in R with the help of some examples.
How to replace a character in a string in R?

You can use the gsub()
function in R to replace every occurrence of a character with another character (or string) in a string. The following is the syntax –
# replace pattern with replacement in x gsub(pattern, replacement, x)
Here, pattern
is the character (or string) pattern you want to replace, replacement
is the character (or string) you want to replace the pattern
with and x
is the string in which you want to perform this replacement.
If, on the other hand, you want to replace only the first occurrence of a character in a string, then you can use the sub()
function. The following is the syntax –
# replace first occurrence of pattern with replacement in x sub(pattern, replacement, x)
The syntax is very similar to the gsub()
function. It returns a string with the first occurrence of the character replaced by the pattern.
Examples
Let’s now look at some examples of using the above syntax –
Replace every occurrence of a character in a string
Let’s replace every occurrence of the character “a” in the string “Panama” with the character “o”. For this, we pass the pattern "a"
, the replacement "o"
, and the string s
as arguments to the gsub()
function.
# create a string s <- "Panama" # replace "a" with "o" print(gsub("a", "o", s))
Output:
[1] "Ponomo"
You can see that every occurrence of “a” is replaced by “o” in the above string.
Replace the first occurrence of a character in a string
If you want to replace only the first occurrence of the character in the string, use the sub()
function instead. Its syntax is similar to the gsub()
function.
Let’s use the same string from above, “Panama” but this time we’ll replace just the first occurrence of the character “a” with “o”.
# create a string s <- "Panama" # replace first occurrence of "a" with "o" print(sub("a", "o", s))
Output:
[1] "Ponama"
We get “Ponama” as the output.
Note that you can use the gsub()
and the sub()
function to replace any string pattern (and not just a single character).
You might also be interested in –
- Compare Two Strings in R (With Examples)
- R – Remove Whitespaces From String
- Convert String to Uppercase in R
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.