R Strings

R Tutorial

🔤 R Strings – Complete Tutorial

In R, strings are used to store and manipulate text data such as names, messages, labels, file paths, and categorical values.
They are a core part of data analysis, reporting, and text processing.


1️⃣ What are Strings in R?

  • Strings are character data

  • Written inside quotes

    • Double quotes " "

    • Single quotes ' '


📌 Internally, R stores strings as character vectors.


2️⃣ Creating Strings



3️⃣ Printing Strings: print() vs cat()


📌 cat() interprets escape characters
📌 print() shows raw string


4️⃣ String Length – nchar()



5️⃣ Combine Strings – paste() & paste0()

paste()


paste0() (no space)


Custom Separator



6️⃣ Substring – substr()



7️⃣ Replace Text – gsub()



8️⃣ Find Text – grep() & grepl()

grepl() (TRUE/FALSE)


grep() (index)



9️⃣ Change Case ⭐


 


🔟 Trim Spaces – trimws()



1️⃣1️⃣ Split Strings – strsplit()



1️⃣2️⃣ Strings with NA Values ⚠️


 

📌 Handle NA carefully using is.na().


1️⃣3️⃣ Common String Functions (Quick Table)

Function Purpose
nchar() Length
paste() Combine
substr() Extract
gsub() Replace
grep() Search
toupper() Uppercase
tolower() Lowercase
trimws() Trim spaces

1️⃣4️⃣ Common Mistakes ❌

❌ Forgetting quotes
❌ Confusing paste() & paste0()
❌ Indexing errors in substr()
❌ Ignoring NA values


📌 Interview Questions & MCQs

Q1. How are strings stored in R?

A) Integer
B) Logical
C) Character
D) Factor

Answer: C


Q2. Which function joins strings without space?

A) paste()
B) paste0()
C) cat()
D) sprintf()

Answer: B


Q3. Which function finds pattern and returns TRUE/FALSE?

A) grep()
B) grepl()
C) gsub()
D) substr()

Answer: B


Q4. Which function removes leading/trailing spaces?

A) strip()
B) clean()
C) trimws()
D) remove()

Answer: C


Q5. Output of:

nchar("R")

A) 0
B) 1
C) 2
D) Error

Answer: B


🔥 Real-Life Use Cases

✔ Text data cleaning
✔ File names & paths
✔ Report generation
✔ Data labeling
✔ NLP preprocessing


✅ Summary

  • Strings are character data

  • Created using quotes

  • R provides powerful string functions

  • paste(), substr(), grep() are essential

  • Handle NA & spaces carefully

  • Core topic for R exams, interviews & data science

You may also like...