R String Basics

Strings are sequences of characters. In R, strings are values enclosed in single or double quotes. Real-world datasets always contain strings — product names, city labels, customer feedback, and codes. Knowing how to create, inspect, and combine strings is fundamental to data cleaning.

Creating Strings

name    <- "Anjali Sharma"
city    <- 'Mumbai'
empty   <- ""                  # empty string
multiwd <- "Data Science in R"

# Single vs double quotes
msg1 <- "She said 'Hello'"     # double wraps single
msg2 <- 'He replied "Hi"'      # single wraps double

Escape Sequences

Sequence   Meaning         Example
─────────────────────────────────────────────────
\n         New line        "Line 1\nLine 2"
\t         Tab             "Name:\tPriya"
\\         Backslash       "C:\\Users\\file"
\"         Double quote    "He said \"yes\""
\'         Single quote    'It\'s fine'
cat("Name:\tPriya\nCity:\tMumbai\n")
# Name:    Priya
# City:    Mumbai

String Length

nchar("Hello, World!")    # 13  — characters in the string
length("Hello, World!")   # 1   — number of strings (just one)

cities <- c("Delhi","Mumbai","Bengaluru","Pune")
nchar(cities)   # 5 6 9 4  — length of each city name

Combining Strings

# paste() — default separator is space
paste("Hello", "World")             # "Hello World"
paste("A", "B", "C", sep="-")      # "A-B-C"
paste(c("x","y","z"), collapse="+") # "x+y+z"

# paste0() — no separator
paste0("ID", 101)                   # "ID101"
paste0("user_", 1:3)                # "user_1" "user_2" "user_3"

Extracting Substrings

text <- "Data Science in R"
#        123456789012345678

substr(text, 1, 4)     # "Data"
substr(text, 6, 12)    # "Science"
substr(text, 17, 18)   # "R"
Diagram:
  D a t a   S c i e n c e   i n   R
  1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8
  └────┘     └─────────┘           └┘
  1 to 4     6 to 12               17

Case Conversion

toupper("hello world")    # "HELLO WORLD"
tolower("R Is GREAT")     # "r is great"

# Title case (capitalize each word)
toTitleCase("data science in r")   # "Data Science In R"
# (from tools package — library(tools) needed)

Trimming Whitespace

raw <- "   Anjali Sharma   "
trimws(raw)                # "Anjali Sharma"   (both ends)
trimws(raw, which="left")  # "Anjali Sharma   " (left only)
trimws(raw, which="right") # "   Anjali Sharma" (right only)

Checking String Content

startsWith("Hello", "He")       # TRUE
endsWith("report.csv", ".csv")  # TRUE
grepl("data", "data science")   # TRUE  (contains "data"?)
grepl("Data", "data science")   # FALSE (case-sensitive by default)
grepl("Data", "data science", ignore.case=TRUE)  # TRUE

Formatting Strings with sprintf()

name   <- "Rohan"
score  <- 87.456
rank   <- 3

sprintf("Student: %s | Score: %.1f | Rank: %d", name, score, rank)
# "Student: Rohan | Score: 87.5 | Rank: 3"

# Format codes:
# %s = string, %d = integer, %f = float, %.2f = 2 decimal places

Converting to and from String

as.character(42)       # "42"
as.character(TRUE)     # "TRUE"
as.numeric("3.14")     # 3.14
as.integer("100")      # 100

String basics power every data cleaning step — removing extra spaces, checking formats, extracting parts of codes, and combining labels. Clean string data is a prerequisite for accurate analysis, and these tools handle the most common string tasks without additional packages.

Leave a Comment

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