Open In App

How to Use str_replace in R?

str_replace() is used to replace the given string with a particular value in R Programming Language. It is available in stringr library, so we have to load this library.

Syntax:



str_replace( "replacing string", "replaced string")

where,

We will use str_replace in dataframe. We can replace particular string in dataframe column by using the following syntax



str_replace(dataframe$column_name, "replacing string", "replaced string")

where,

Example:




# load the library
library(stringr)
 
# create a dataframe with 3 columns
data = data.frame(name1=c('java', 'python', 'php'),
                  name2=c('html', 'css', 'jsp'),
                  marks=c(78, 89, 77))
 
# replace the java with oops in name1 column
print(str_replace(data$name1, "java", "oops"))
 
# replace the htmlwith oops in name2 column
print(str_replace(data$name2, "html", "HTML5"))

Output:

[1] "oops"   "python" "php"   
[1] "HTML5" "css"   "jsp"  

Method 2: Replace String with Nothing

We can replace the string with “” empty.

Syntax:

str_replace(dataframe$column_name, "replacing string", "")

Example :




# load the library
library(stringr)
 
# create a dataframe with 3 columns
data = data.frame(name1=c('java', 'python', 'php'),
                  name2=c('html', 'css', 'jsp'),
                  marks=c(78, 89, 77))
 
# replace the java with nothing in name1 column
print(str_replace(data$name1, "java", ""))
 
# replace the html with nothing in name2 column
print(str_replace(data$name2, "html", ""))

Output:

[1] ""       "python" "php"   
[1] ""    "css" "jsp"

Method 3: Replace Multiple Strings

We can replace multiple string in a particular column by using str_replace_all method.

Syntax:

str_replace_all(dataframe$column_name, c(“string1” = “new string”,……………..,”stringn” = “new string”))

Example:




# load the library
library(stringr)
 
# create a dataframe with 3 columns
data = data.frame(name1=c('java', 'python', 'php'),
                  name2=c('html', 'css', 'jsp'),
                  marks=c(78, 89, 77))
 
# replace the java with oops and php with sql in name1 column
print(str_replace_all(data$name1, c("java"="oops", "php"="sql")))
 
# replace the html with r  and jsp with servletsin name2 column
print(str_replace_all(data$name2, c("html"="R", "jsp"="servlets")))

Output:

[1] "oops"   "python" "sql"   
[1] "R"        "css"      "servlets"

Article Tags :