What are escape characters in R?

Overview

An escape character in R is used whenever you are trying to add an illegal character or a character that would otherwise be difficult to add to a string.

Some of the escape characters in R are:

Escape Code

Result

\"

Double quote

\n

Start a new line

\t

Horizontal tab

\b

Back space

\\

Single backspace or a back slash

Example

Imagine you want to insert a double quote inside of a string that is already surrounded by double quotes:

Code 1

The code below has an error. It demonstrates what happens when escape characters are not used.

# creation a string
mystring <- "Hello pals, welcome on board to the "Captain" boat"
# printign the string variable
mystring

Output

Error: unexpected symbol in "mystring <- "Hello pals, welcome on board to the "Captain"

This is the reason why we use the escape characters. Therefore, to solve this problem of having a double quotation mark inside a string enclosed in a double quotation mark, we use the \"

Code 2

# creation a string
mystring <- "Hello pals, welcome on board to the \"Captain\" boat" # using the \" escape character
# printign the string variable
mystring
# using the cat() function to print the string variable without a backlash
cat(mystring)

It is worth noting that the cat() function helps use print the mystring variable without the backslash, unlike auto-printing the mystring variable using \"