Open In App

How to Remove Dollar Signs in R?

Improve
Improve
Like Article
Like
Save
Share
Report

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




# declaring a string
str = "$Remove Dollar $Sign"
print("Original String")
print(str)
  
# removing dollar sign from string
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




# declaring a data frame
data_frame < - data.frame(col1=c(1: 5),
                          col2=c("Ge$eks$", "$For",
                                 "Geeks", "$I$s", "$Fun$"))
print("Original DataFrame")
  
print(data_frame)
  
# removing $ sign from data frame column
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




# declaring a data frame
str_vec < - c("Ge$eks$", "$For", "Geeks",
              "$I$s", "$Fun$")
print("Original String")
print(str_vec)
  
# removing $ sign from data frame column
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
Previous
Next
Share your thoughts in the comments
Similar Reads