[R] replacing "+" in string

R. Michael Weylandt michael.weylandt at gmail.com
Sat Jan 21 23:03:32 CET 2012


Two ways:

i) (If you are not using full regular expressions) Set the fixed = TRUE option.

ii) Escape it.

E.g.,

gsub("\\+", "plus", X)
gsub("+", "plus", X, fixed = TRUE)

Read up on ?regexp for an explanation of what's going on.

Michael

On Sat, Jan 21, 2012 at 2:46 PM, Nevil Amos <nevil.amos at gmail.com> wrote:
> I am trying to replace "+" in a string with another character
> I am getting odd results using sub and gsub
>> X<-"one + two"
>> gsub("+","plus",X)
> [1] "plusoplusnpluseplus plus+plus plustpluswplusoplus"
>> sub("+","plus",X)
> [1] "plusone + two"
>> X<-"one ~ two"
>
> it seems to work fine with other characters:
>
>> sub("~","plus",X)
> [1] "one plus two"
>
>
> How do I enable "+" to be recognised as a normal character?
>
> thanks
>
> Nevil Amos
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list