[R] How to remove $ (Dollar sign) from string

(Ted Harding) Ted.Harding at wlandres.net
Tue Apr 10 13:47:04 CEST 2012


On 10-Apr-2012 11:34:13 Nevil Amos wrote:
> How do I remove a "$" character from a string sub() and gsub() with "$" or
> "\$" as pattern do not work.
>> sub("$","","ABC$DEF")
> [1] "ABC$DEF"
>> sub("\$","","ABC$DEF")
> Error: '\$' is an unrecognized escape in character string starting "\$"
>> sub(\$,"","ABC$DEF")
> Error: unexpected input in "sub(\"
> 
> Thanks
> -- 
> Nevil Amos
> Molecular Ecology Research Group
> Australian Centre for Biodiversity
> Monash University
> CLAYTON VIC 3800
> Australia

  sub("\\$","","ABC$DEF")
  # [1] "ABCDEF"

Logic: "$" is a metacharacter which stands for "the end of the thing";
as a check of that, instead of your

  sub("$","","ABC$DEF")

do

  sub("$","+","ABC$DEF")
  # [1] "ABC$DEF+"

Therefore "$" needs to be escaped, so you have to use "\";
but since "\" is itself a metacharacter you have to escape
that too, hence "\\$".

Hoping this hrelps,
Ted.

-------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at wlandres.net>
Date: 10-Apr-2012  Time: 12:46:59
This message was sent by XFMail



More information about the R-help mailing list