0

I want to convert $ankit to \$ankit in R. I have tried the following, which does not work:

gsub("$","\$","$ankit", fixed=TRUE)
# Error: '\$' is an unrecognized escape in character string starting ""\$"
gsub("$","\\$","$ankit", fixed=TRUE)
# [1] "\\$ankit"
gsub("$","\\U0024","$ankit", fixed=TRUE)
# [1] "\\U0024ankit"
gsub("$","\U0024","$ankit", fixed=TRUE)
# [1] "$ankit"
Frank
  • 66,179
  • 8
  • 96
  • 180
Ankit
  • 153
  • 1
  • 6
  • 5
    You have to do `\\$` `cat(gsub("$","\\$","$ankit", fixed=TRUE), '\n')` also check `nchar('\\$')` – akrun Sep 04 '15 at 14:06
  • Are you saying that \\$ works, and its just that while displaying the answer R is showing the additional \ in "\\$ankit" just to write it in an escaped manner. – Ankit Sep 04 '15 at 14:23
  • You can check [here](http://stackoverflow.com/questions/11806501/backslash-in-r-string) – akrun Sep 04 '15 at 14:25
  • Thanks \\$ indeed works. I was getting confused due to the fact that the output when displayed on R console itself had escape sequence. – Ankit Sep 04 '15 at 14:39

1 Answers1

1

I believe you have to double escape characters in R because the first \ escapes the second \, and the second one escapes the desired character.

You also have to double square brackets when using regular expressions for the same reason. [[:alnum:]]

See R's regex instructions and the examples in grep . \\$ will do what you want as @akrun suggests in his comment.

Paul James
  • 520
  • 4
  • 17