Chapter 14: R Strings

1. What is a String in R? (Simple Definition)

A string (or character vector element) is just text data — anything inside quotation marks.

In R:

  • Single quotes ‘ ‘ or double quotes ” ” — both work perfectly
  • The type is always called character (typeof() → “character”, class() → “character”)
R

2. Creating Strings – All the Ways

R

3. Escaping Special Characters (Very Important!)

Inside strings, some characters have special meaning — you must escape them with \

Character you want How to write it in string Example
Double quote “ \” “He said \”Hello\””
Single quote ‘ \’ ‘It\’s hot today’
Backslash \ \\ “C:\\Users\\Webliance\\Documents”
New line \n “Line one\nLine two”
Tab \t “Name\tAge\tCity”

Real example:

R

4. Most Important String Functions (Base R – No Package Needed)

Function What it does Example code Typical Output
nchar() Length of string nchar(“Hyderabad”) 9
paste() / paste0() Combine strings paste(“Temp”, 29.5, “°C”) “Temp 29.5 °C”
paste(…, collapse=) Join vector into one string paste(c(“Mon”,”Tue”), collapse=”, “) “Mon, Tue”
substr() / substring() Extract substring substr(“Hyderabad”, 1, 5) “Hyder”
toupper() / tolower() Change case toupper(“Hyderabad”) “HYDERABAD”
trimws() Remove leading/trailing whitespace trimws(” Hyderabad “) “Hyderabad”
strsplit() Split string by delimiter strsplit(“A,B,C”, “,”)[[1]] c(“A”,”B”,”C”)
grepl() Check if pattern exists (regex) grepl(“bad”, “Hyderabad”) TRUE
gsub() / sub() Replace pattern gsub(“bad”, “good”, “Hyderabad”) “Hyderagood”

5. Modern 2026 Favorite: stringr Package (Highly Recommended!)

Most people now use stringr (part of tidyverse) instead of base functions — more consistent naming, better handling of NA, easier regex.

R

6. Common Beginner Mistakes & Fixes

Mistake 1 — Forgetting quotes → R thinks it’s a variable name

R

Mistake 2 — Mixing numbers and text without care

R

Fix: Keep numbers numeric, text as character, or use factors/data.frames for mixed data.

Mistake 3 — Not escaping quotes

R

7. Your Mini Practice Right Now (Copy → Run!)

R

You just used most of the important string operations!

Summary Cheat-Sheet (Keep This Handy)

  • Create → “text” or ‘text’
  • Escape → \”, \’, \\, \n, \t
  • Length → nchar() or str_length()
  • Combine → paste(), paste0(), str_c(), glue()
  • Case → toupper(), tolower(), str_to_title()
  • Replace → gsub(), str_replace()
  • Detect → grepl(), str_detect()
  • Modern choice → stringr or glue for clean code

Feeling confident with strings now?

Next step?

  • Want to practice regex in R (very powerful for cleaning text)?
  • How strings behave in data frames / dplyr?
  • Or move to factors (special string type for categories)?

Just tell me — next lesson is ready! ☕📝🚀

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *