[R] gsub() and parenthesis symbols

Thomas Lumley tlumley at u.washington.edu
Fri Aug 3 00:43:57 CEST 2001


On Thu, 2 Aug 2001, Kieran Healy wrote:

> Dear R-users --
>
> I'm using R 1.3.0 on a PC running SuSE Linux 7.1. I'm confused by the
> following behavior from the gsub() function. Am I doing something wrong?
>
> ## A string of characters
> > string<-c("q","w","e","(",")","q","w","e")
>
> ## Use gsub to replace `q' with `A'
> > gsub("q","A",string)
>
> [1] "A" "w" "e" "(" ")" "A" "w" "e" # Works fine
>
> ## Replace `(' [open-parenthesis symbol] with `A'
> > gsub("(","A",string)
>
> Error in gsub(pattern, replacement, x, ignore.case, extended) :
> 	invalid regular expression
>
> ## But NB! -- Replace `)' [close parenthesis symbol] with `A'
> > gsub(")","A",string)
>
> [1] "q" "w" "e" "(" "A" "q" "w" "e" # Works fine!
>
>
> ## Further experimentation reveals the following:
> ## Replace open-paren with close-paren does not work
> > gsub("(",")",string)
>
> Error in gsub(pattern, replacement, x, ignore.case, extended) :
> 	invalid regular expression
>
> ## ... But replace close paren with open paren works fine!
> > gsub(")","(",string)
>
> [1] "q" "w" "e" "(" "(" "q" "w" "e"
>
>
> My understanding is that parentheses are not special characters is
> regexp syntax. And of course I don't understand at all why the open
> paren symbol doesn't work but the close paren symbol does. It seems to
> dislike it only when it appears as the first argument to the function.

Parentheses *are* special characters in POSIX 1003.2 regexps and one of
the examples in help(gsub) uses them.
Also
 gsub("\\(","A",string)
does do want you want, as you would expect if ( were special. Close paren
OTOH is not special except after an unmatched open paren.


	-thomas

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list