[Rd] gsub + backslashes

Simon Urbanek simon.urbanek at r-project.org
Mon Apr 24 16:29:43 CEST 2006


On Apr 24, 2006, at 10:23 AM, Torsten Hothorn wrote:

>
> Dear developeRs,
>
> I thought that backslashes can be escaped in the usual way (and I  
> think I
> did this before) but I can't see why
>
> R> gsub("\\", "x", "\alpha")
> Error in gsub(pattern, replacement, x, ignore.case, extended, fixed,
> useBytes) :
>          invalid regular expression '\'
>
> gives an error. Or am I just blind?
>

In REs you need to escape backslashes, so you need double-escaping:  
one for the R string representation and one for the RE:

 > gsub("\\\\", "x", "\\alpha")
[1] "xalpha"

For illustration purposes:

 > cat("\\\\")
\\
 > cat("\alpha")
lpha
 > cat("\\alpha")
\alpha

Cheers,
Simon



More information about the R-devel mailing list