R Escape Characters

R Tutorial

🔤 R Escape Characters

In R, escape characters are special character sequences used inside strings to represent characters that are hard to type, invisible, or have special meaning (like new lines, tabs, quotes, etc.).

👉 Escape characters always start with a backslash \.


1️⃣ What are Escape Characters?

Escape characters allow you to:

  • Insert new lines

  • Add tabs

  • Print quotes inside strings

  • Handle special symbols

📌 Mainly used with character strings.


2️⃣ Common Escape Characters in R ⭐

Escape CharacterMeaning
\nNew line
\tHorizontal tab
\\Backslash
\"Double quote
\'Single quote
\rCarriage return
\bBackspace
\fForm feed
\aAlert (bell)

3️⃣ New Line \n

cat("Hello\nWorld")

Output

Hello
World

4️⃣ Tab Space \t

cat("Name\tMarks")

Output

Name Marks

5️⃣ Printing Quotes Inside Strings ⭐

Double Quote

cat("He said, \"R is powerful\"")

Single Quote

cat('It\'s an R tutorial')

6️⃣ Backslash \\

cat("File path: C:\\Program Files\\R")

📌 Single \ is not allowed directly → must use \\.


7️⃣ Carriage Return \r

cat("Hello\rWorld")

📌 Moves cursor to beginning of the line.


8️⃣ Escape Characters with print() vs cat()

print("Hello\nWorld")

Output:

[1] "Hello\nWorld"
cat("Hello\nWorld")

Output:

Hello
World

📌 cat() interprets escape characters
📌 print() shows them as text


9️⃣ Unicode Escape Sequences ⭐

cat("\u263A")

😊 (Smiley)

📌 Useful for symbols & emojis.


🔟 Common Mistakes ❌

❌ Using single \ instead of \\
❌ Expecting print() to format text
❌ Forgetting escape before quotes
❌ Confusing \n with /n


📌 Interview Questions & MCQs

Q1. Which escape character is used for new line?

A) \t
B) \n
C) \r
D) \b

Answer: B


Q2. How to print a backslash in R?

A) \
B) //
C) \\
D) \b

Answer: C


Q3. Which function interprets escape characters?

A) print()
B) show()
C) cat()
D) display()

Answer: C


Q4. What does \t represent?

A) New line
B) Tab space
C) Backslash
D) Quote

Answer: B


Q5. Output of:

cat("A\nB")

A) A\nB
B) AB
C)

A
B

D) Error

Answer: C


🔥 Real-Life Use Cases

✔ Formatting output
✔ Printing tables
✔ File paths
✔ Logs and reports
✔ User-friendly messages


✅ Summary

  • Escape characters start with \

  • Used for formatting strings

  • \n, \t, \\, \" are most common

  • cat() interprets escapes, print() does not

  • Important for R exams, interviews & data output

You may also like...