R Escape Characters
Some characters can't be typed directly inside a string: a double quote inside a double-quoted string would end the string early, for example. An escape sequence starts with a backslash \ and stands for one special character.
quote <- "She said \"R is great\"."
quote
cat(quote, "\n")[1] "She said \"R is great\"."
She said "R is great".
When R prints a string, it shows the escapes so the output could be pasted back into code. cat() (and writeLines()) show the actual characters.
Common escape sequences
| Escape | Character |
|---|---|
\" |
double quote |
\' |
single quote |
\\ |
backslash |
\n |
new line |
\t |
tab |
\r |
carriage return |
\u00e9 |
Unicode character U+00E9 (é) |
cat("Name\tScore\n")
cat("Ana\t91\n")
cat("Ben\t78\n")
cat("Path: C:\\Users\\ana\n")
cat("Caf\u00e9\n")Name Score
Ana 91
Ben 78
Path: C:\Users\ana
Café
Quotes inside quotes
You can avoid escaping by using the other kind of quote on the outside:
a <- 'He said "hello"'
b <- "It's raining"
writeLines(a)
writeLines(b)
nchar("\n")He said "hello"
It's raining
[1] 1
nchar("\n") is 1: an escape sequence is one character, even though you typed two.
Raw strings
Writing many backslashes, as in Windows paths or regular expressions, gets messy. Since R 4.0 you can write a raw string r"(...)", in which backslashes are taken literally:
path <- r"(C:\data\sales\2024.csv)"
writeLines(path)
identical(path, "C:\\data\\sales\\2024.csv")
pattern <- r"(\d+\.\d+)"
writeLines(pattern)C:\data\sales\2024.csv
[1] TRUE
\d+\.\d+
The parentheses can also be brackets or braces: r"[...]" and r"{...}" work the same way.
A common mistake
A lone backslash before a character that has no escape meaning is an error, not a backslash. This program stops before running anything, because R can't even parse it:
path <- "C:\data"Error: '\d' is an unrecognized escape in character string (<input>:1:13)
Double the backslash ("C:\\data"), use forward slashes ("C:/data", which R accepts on Windows too), or use a raw string.
Test yourself
Which string contains a literal double quote character?
- "say "hi""
- "say \"hi\""
- "say /"hi/""
- "say ''hi''"
What does \t produce?
- The letter t
- A tab
- A new line
- A backslash
What is special about r"(C:\new)"?
- It is a regular expression
- Backslashes are kept literally (raw string)
- It runs R code
- It is an error