R String Functions
R provides a rich set of built-in string functions for searching, replacing, splitting, and formatting text. These functions process entire character vectors at once, making them ideal for cleaning and transforming text columns in a dataset.
Searching Within Strings
# grepl() — returns TRUE/FALSE for each element
emails <- c("alice@gmail.com","bob@yahoo.com","cena@gmail.com","dev@hotmail.com")
grepl("@gmail", emails)
# TRUE FALSE TRUE FALSE
# Filter: get only Gmail addresses
gmail <- emails[grepl("@gmail", emails)]
# "alice@gmail.com" "cena@gmail.com"
# grep() — returns the positions (indices) of matches
grep("@gmail", emails) # 1 3 (positions 1 and 3)
# grep() with value=TRUE returns the actual strings
grep("@gmail", emails, value=TRUE)
# "alice@gmail.com" "cena@gmail.com"
Finding Position of a Pattern
text <- "Learning R is fun and rewarding"
regexpr("R", text) # 10 (first occurrence)
gregexpr("r", text, ignore.case=TRUE) # all occurrences
Replacing Text
# sub() — replace FIRST match only
sub("o", "0", "too cool for school")
# "t0o cool for school"
# gsub() — replace ALL matches
gsub("o", "0", "too cool for school")
# "t00 c00l f0r sch00l"
# Practical: clean phone numbers
phones <- c("(91) 98765-43210", "(91) 87654-32109")
clean_phones <- gsub("[^0-9]", "", phones) # keep digits only
print(clean_phones)
# "919876543210" "918765432109"
Splitting Strings
csv_row <- "Priya,28,Mumbai,85000"
strsplit(csv_row, ",")
# [["Priya", "28", "Mumbai", "85000"]]
# Split a sentence into words
sentence <- "R is great for data analysis"
strsplit(sentence, " ")[[1]]
# "R" "is" "great" "for" "data" "analysis"
# Split multiple strings at once
data <- c("Jan-2024", "Feb-2024", "Mar-2024")
strsplit(data, "-")
# [["Jan","2024"], ["Feb","2024"], ["Mar","2024"]]
Formatting Numbers as Strings
formatC(12345.678, format="f", digits=2) # "12345.68" formatC(12345, format="d", big.mark=",") # "12,345" format(0.00123, scientific=TRUE) # "1.23e-03" format(12345678, big.mark=",", scientific=FALSE) # "12,345,678"
Padding Strings
formatC("R", width=10) # " R" (right-aligned)
formatC("R", width=10, flag="-")# "R " (left-aligned)
formatC(42, width=6, flag="0") # "000042" (zero-padded)
# Practical: create padded IDs
ids <- 1:5
formatC(ids, width=4, flag="0")
# "0001" "0002" "0003" "0004" "0005"
String Manipulation Cheat Sheet
Function Purpose Example
─────────────────────────────────────────────────────────────────
nchar(x) Count characters nchar("hello") = 5
toupper/lower Case conversion toupper("hi") = "HI"
trimws(x) Remove whitespace trimws(" hi ") = "hi"
substr(x,s,e) Extract substring substr("hello",1,3) = "hel"
paste(...) Combine strings paste("a","b") = "a b"
paste0(...) Combine without sep paste0("a","b") = "ab"
gsub(p,r,x) Replace all matches gsub("a","@","banana")
sub(p,r,x) Replace first match sub("a","@","banana")
grepl(p,x) TRUE if pattern found grepl("@","email@x")
grep(p,x) Indices of matches grep("@", emails)
strsplit(x,s) Split by separator strsplit("a,b",",")
sprintf(fmt,...) Format string sprintf("%.2f", 3.14)
Practical: Clean a Messy Name Column
raw_names <- c(" ALICE sharma ", "BOB Kumar", "cena PATEL ")
clean_names <- raw_names |>
trimws() |> # remove whitespace
tolower() |> # all lowercase
gsub("\\s+", " ", x = _) |> # collapse spaces
gsub("(\\w)(\\w*)", "\\U\\1\\L\\2", x=_, perl=TRUE) # title case
print(clean_names)
# "Alice Sharma" "Bob Kumar" "Cena Patel"
String functions handle the messiest real-world data cleaning tasks. Survey responses, imported CSVs, scraped web data, and database fields all require string cleaning before analysis. These functions give you the tools to handle most situations without writing complex custom code.
