Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape backslashes in R string

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" 
like image 973
Fnzh Xx Avatar asked Aug 04 '12 06:08

Fnzh Xx


People also ask

How do you escape a backslashes string?

The first two backslashes ( \\ ) indicate that you are escaping a single backslash character. The third backslash indicates that you are escaping the double-quote that is part of the string to match.

What is escape sequence in R?

A sequence in a string that starts with a \ is called an escape sequence and allows us to include special characters in our strings.

Why do backslashes need to be escaped?

The use of the word "escape" really means to temporarily escape out of parsing the text and into a another mode where the subsequent character is treated differently. Depending on the character, a backslash may be telling the compiler/interpreter that the following character has no special meaning.


2 Answers

[...] 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.

like image 92
aioobe Avatar answered Oct 03 '22 17:10

aioobe


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!

like image 39
seancarmody Avatar answered Oct 03 '22 17:10

seancarmody