21

I'm writing strings which contain backslashes (\) to a file:

x1 = "\\str"

x2 = "\\\str"
# Error: '\s' is an unrecognized escape in character string starting "\\\s"

x2="\\\\str"
write(file = 'test', c(x1, x2))

When I open the file named test, I see this:

\str
\\str

If I want to get a string containing 5 backslashes, should I write 10 backslashes, like this?

x = "\\\\\\\\\\str" 
Henrik
  • 65,555
  • 14
  • 143
  • 159
Fnzh Xx
  • 661
  • 2
  • 8
  • 14
  • 2
    From `R 4.0.0` raw strings are supported. See [Escaping backslash (\) in string or paths in R](https://stackoverflow.com/questions/14185287/escaping-backslash-in-string-or-paths-in-r/63078969#63078969) – Henrik Jul 31 '20 at 08:59

3 Answers3

22

[...] If I want to get a string containing 5 \ ,should i write 10 \ [...]

Yes, you should. To write a single \ in a string, you write it as "\\".

This is because the \ is a special character, reserved to escape the character that follows it. (Perhaps you recognize \n as newline.) It's also useful if you want to write a string containing a single ". You write it as "\"".

The reason why \\\str is invalid, is because it's interpreted as \\ (which corresponds to a single \) followed by \s, which is not valid, since "escaped s" has no meaning.

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • 8
    No equivalent of Python's ["raw strings"](http://stackoverflow.com/a/2081708/1175496) , as in: `r'allows\unescaped\backslashes'` ? – Nate Anderson Oct 27 '15 at 17:24
  • 3
    @TheRedPea Yes, from `R 4.0.0` raw strings are supported. See e.g. [Escaping backslash (\) in string or paths in R](https://stackoverflow.com/questions/14185287/escaping-backslash-in-string-or-paths-in-r/63078969#63078969) – Henrik Jul 31 '20 at 08:57
8

Have a read of this section about character vectors.

In essence, it says that when you enter character string literals you enclose them in a pair of quotes (" or '). Inside those quotes, you can create special characters using \ as an escape character.

For example, \n denotes new line or \" can be used to enter a " without R thinking it's the end of the string. Since \ is an escape character, you need a way to enter an actual . This is done by using \\. Escaping the escape!

zx8754
  • 52,746
  • 12
  • 114
  • 209
seancarmody
  • 6,182
  • 2
  • 34
  • 31
6

Note that the doubling of backslashes is because you are entering the string at the command line and the string is first parsed by the R parser. You can enter strings in different ways, some of which don't need the doubling. For example:

> tmp <- scan(what='')
1: \\\\\str
2: 
Read 1 item
> print(tmp)
[1] "\\\\\\\\\\str"
> cat(tmp, '\n')
\\\\\str 
> 
Greg Snow
  • 48,497
  • 6
  • 83
  • 110