10

Related question here.

So I have a character vector with currency values that contain both dollar signs and commas. However, I want to try and remove both the commas and dollar signs in the same step.

This removes dollar signs =

d = c("$0.00", "$10,598.90", "$13,082.47")
gsub('\\$', '', d)

This removes commas =

library(stringr)
str_replace_all(c("10,0","tat,y"), fixed(c(","), "")

I'm wondering if I could remove both characters in one step.

I realize that I could just save the gsub results into a new variable, and then reapply that (or another function) on that variable. But I guess I'm wondering about a single step to do both.

Community
  • 1
  • 1
ATMathew
  • 12,566
  • 26
  • 69
  • 76

2 Answers2

16

Since answering in the comments is bad:

gsub('\\$|,', '', d)

replaces either $ or (|) , with an empty string.

joran
  • 169,992
  • 32
  • 429
  • 468
  • what are the double back slash for?@joran – Demo Jan 31 '17 at 19:57
  • 1
    @WhiteBig `$` is a special character in regexes and so much be escaped. You can read about it via `?regex`. – joran Jan 31 '17 at 20:09
  • @WhiteBig Kind of. It's just that \ is itself a special character, so it too needs to be escaped. So you escape the `$`: `\$`, but then \ needs to be escaped as well, so you end up with `\\$`. – joran Jan 31 '17 at 20:18
  • got you, can we put single back slash before $ and , separately? – Demo Jan 31 '17 at 20:20
  • @WhiteBig No. The `$` must have two, and the `,` doesn't need any (not a special character). – joran Jan 31 '17 at 20:21
4

take a look at ?regexp for additional special regex notation:

> gsub('[[:punct:]]', '', d)
[1] "000"     "1059890" "1308247"
Justin
  • 42,475
  • 9
  • 93
  • 111
  • I think that will strip the decimal point as well, which seems to not be what the OP wanted. @joran's answer above seems to do it exactly without over-reaching. – thelatemail Jul 05 '12 at 00:21
  • @thelatemail you're correct! I shouldn't answer questions when there is tequila around! the answer joran provided is much better. – Justin Jul 05 '12 at 14:01