How to Use str_replace in R?
Last Updated :
02 Dec, 2021
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,
- replacing string is the string to be replaced
- replaced string is the final string
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,
- dataframe is the input dataframe
- column_name is the column in the dataframe
Example:
R
library (stringr)
data = data.frame (name1= c ( 'java' , 'python' , 'php' ),
name2= c ( 'html' , 'css' , 'jsp' ),
marks= c (78, 89, 77))
print ( str_replace (data$name1, "java" , "oops" ))
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 :
R
library (stringr)
data = data.frame (name1= c ( 'java' , 'python' , 'php' ),
name2= c ( 'html' , 'css' , 'jsp' ),
marks= c (78, 89, 77))
print ( str_replace (data$name1, "java" , "" ))
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:
R
library (stringr)
data = data.frame (name1= c ( 'java' , 'python' , 'php' ),
name2= c ( 'html' , 'css' , 'jsp' ),
marks= c (78, 89, 77))
print ( str_replace_all (data$name1, c ( "java" = "oops" , "php" = "sql" )))
print ( str_replace_all (data$name2, c ( "html" = "R" , "jsp" = "servlets" )))
|
Output:
[1] "oops" "python" "sql"
[1] "R" "css" "servlets"
Share your thoughts in the comments
Please Login to comment...