To replace all occurrences of a substring in a string in R, you can use the gsub
function.
In this example,
str
.gsub
function with the substring to be replaced, the replacement string, and the input string as arguments.gsub
function returns a new string with all occurrences of the substring replaced.str <- 'Hello World Hello'
newStr <- gsub('Hello', 'Hi', str)
cat(newStr)
Hi World Hi
In this example,
str
.gsub
function with the character to be replaced, the replacement character, and the input string as arguments.gsub
function returns a new string with all occurrences of the character replaced.str <- 'Hello World Hello'
newStr <- gsub('o', 'X', str)
cat(newStr)
HellX WXrld HellX
In this tutorial, we learned How to Replace All Occurrences of a Substring in a String in R language with well detailed examples.