[R] escaping backslash in a string

Peter Dalgaard
Mon, 29 Nov 2004 17:35:34 -0000

Dan Lipsitt <danlipsitt at gmail.com> writes:

> 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] "\\"

Nononononono.... If you want to know what is inside a string, use
cat() not (implicitly) print()

> cat( "\\.")
\.>

The thing is that print() itself escapes "weird" characters, including
the escape character:

> x <- readLines() # ctr-D terminates (on Linux anyway)
\.
> x
[1] "\\."


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

Yes. Not at all.

--
   O__  ---- Peter Dalgaard             Blegdamsvej 3
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907