How to Remove Dollar Signs in R (With Examples)


You can easily remove dollar signs and commas from data frame columns in R by using gsub() function. This tutorial shows three examples of using this function in practice.

Remove Dollar Signs in R

The following code shows how to remove dollar signs from a particular column in a data frame in R:

#create data frame 
df1 <- data.frame(ID=1:5,
                 sales=c('$14.45', '$13.39', '$17.89', '$18.99', '$20.88'),
                 stringsAsFactors=FALSE)
df1

  ID  sales
1  1 $14.45
2  2 $13.39
3  3 $17.89
4  4 $18.99
5  5 $20.88

#remove dollar signs from sales column
df1$sales = as.numeric(gsub("\\$", "", df1$sales))

df1

  ID sales
1  1 14.45
2  2 13.39
3  3 17.89
4  4 18.99
5  5 20.88

Remove Dollar Signs & Commas in R

The following code shows how to remove both dollar signs and columns from a particular column in a data frame in R:

#create data frame 
df2 <- data.frame(ID=1:3,
                 sales=c('$14,000', '$13,300', '$17,890'),
                 stringsAsFactors=FALSE)
df2

  ID   sales
1  1 $14,000
2  2 $13,300
3  3 $17,890

#remove dollar signs and commas from sales column
df2$sales = as.numeric(gsub("[\\$,]", "", df2$sales))

df2

  ID sales
1  1 14000
2  2 13300
3  3 17890

Note that you can now perform calculations on the sales column since the dollar signs and commas are removed.

For example, we can now calculate the sum of the sales column:

#calculate sum of sales
sum(df2$sales)

[1] 45190

Additional Resources

How to Perform a VLOOKUP (Similar to Excel) in R
How to Extract Year from Date in R
How to Append Rows to a Data Frame in R

Leave a Reply

Your email address will not be published. Required fields are marked *