TExcelTAD
Home › R › R Escape Characters

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.

r · try it yourself
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 (é)
r · try it yourself
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:

r · try it yourself
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:

r · try it yourself
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:

r · try it yourself
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?

  1. "say "hi""
  2. "say \"hi\""
  3. "say /"hi/""
  4. "say ''hi''"

What does \t produce?

  1. The letter t
  2. A tab
  3. A new line
  4. A backslash

What is special about r"(C:\new)"?

  1. It is a regular expression
  2. Backslashes are kept literally (raw string)
  3. It runs R code
  4. It is an error