[R] escaping backslash in a string

Dan Lipsitt
Mon, 29 Nov 2004 17:20:02 -0000

How can I get a single backslash in a character string?

My goal is to escape dots in a string that will be used as a regular
expression. I thought I could do it this way:

gsub(".", "\\.", x)

Unfortunately, "\\" does not represent a literal backslash as I
expected, but rather a pair of backslashes:

> "\\."
[1] "\\."
> "\\"
[1] "\\"

Just a backslash and a dot fails too, since that represents an escaped dot:

> "\."
[1] "."

A single backslash works in the middle of strings sometimes,but it
depends on what the character following it is (presumably depending on
whether the pair of characters represents an escape sequence):

> "a\b"
[1] "a\b"
> "x\y"
[1] "xy"

Is there a way to represent "\"? This seems like a design problem in
the interpreter.

> R.version
         _
platform i386-redhat-linux-gnu
arch     i386
os       linux-gnu
system   i386, linux-gnu
status
major    2
minor    0.1
year     2004
month    11
day      15
language R