How to Remove Dollar Signs in R?
The gsub() method in base R is used to replace all the matches of a pattern from a string. In case the pattern is not contained within the string, it will be returned as it is. It takes regular expression as a parameter which is used to replace with a new specified string.
Syntax:
gsub(pattern, replacement, string)
Parameters :
- pattern: the string to be matched
- replacement: the string to be used for replacement
- string: string
Example:
In this example, the $ sign in the string variable is replaced with “” (blank character) using the gsub() method.
R
str = "$Remove Dollar $Sign"
print ( "Original String" )
print (str)
str_mod = gsub ( "\\$" , "" , str)
print ( "Modified String" )
print (str_mod)
|
Output
[1] "Original String"
[1] "$Remove Dollar $Sign"
[1] "Modified String"
[1] "Remove Dollar Sign"
Dollar signs can also be removed from a dataframe column or row, by using the gsub() method. All the instances of the $ sign are removed from the entries contained within the data frame.
Example:
In this example, all the instances of $ sign is replaced with a blank character in col2 of the data frame.
R
data_frame < - data.frame (col1= c (1: 5),
col2= c ( "Ge$eks$" , "$For" ,
"Geeks" , "$I$s" , "$Fun$" ))
print ( "Original DataFrame" )
print (data_frame)
data_frame$col2 = gsub ( "\\$" , "" , data_frame$col2)
print ( "Modified DataFrame" )
print (data_frame)
|
Output
A string vector can also be specified containing different strings which may or may not contain $ sign within it. The gsub() method can also be used to remove occurrences of $ sign from the vector.
Example:
R
str_vec < - c ( "Ge$eks$" , "$For" , "Geeks" ,
"$I$s" , "$Fun$" )
print ( "Original String" )
print (str_vec)
str_mod = gsub ( "\\$" , "" , str_vec)
print ( "Modified String" )
print (str_mod)
|
Output
[1] "Original String"
[1] "Ge$eks$" "$For" "Geeks" "$I$s" "$Fun$"
[1] "Modified String"
[1] "Geeks" "For" "Geeks" "Is" "Fun"
Last Updated :
28 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...