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 |
Imagine you want to insert a double quote inside of a string that is already surrounded by double quotes:
The code below has an error. It demonstrates what happens when escape characters are not used.
# creation a stringmystring <- "Hello pals, welcome on board to the "Captain" boat"# printign the string variablemystring
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 \"
# creation a stringmystring <- "Hello pals, welcome on board to the \"Captain\" boat" # using the \" escape character# printign the string variablemystring# using the cat() function to print the string variable without a backlashcat(mystring)
It is worth noting that the
cat()
function helps use print themystring
variable without the backslash, unlike auto-printing themystring
variable using\"