R String Functions
The Strings lesson introduced paste(), nchar() and substr(). This lesson collects the string functions you'll use most when cleaning and formatting text. All of them are vectorised: they process every element of a character vector at once.
| Task | Function |
|---|---|
| Join | paste(), paste0(), strrep() |
| Length | nchar() |
| Case | toupper(), tolower(), casefold() |
| Extract / replace by position | substr(), substring() |
| Trim spaces | trimws() |
| Split | strsplit() |
| Detect / replace patterns | grepl(), sub(), gsub() |
| Starts / ends with | startsWith(), endsWith() |
| Format | sprintf(), format(), formatC() |
Cleaning messy text
r · try it yourself
raw <- c(" Alice ", "BOB", " carol ")
clean <- trimws(raw)
clean
tolower(clean)
# capitalise the first letter
paste0(toupper(substr(clean, 1, 1)), tolower(substring(clean, 2)))[1] "Alice" "BOB" "carol"
[1] "alice" "bob" "carol"
[1] "Alice" "Bob" "Carol"
substring(x, first) takes everything from position first to the end.
Splitting and joining
strsplit() returns a list because each input string can split into a different number of pieces:
r · try it yourself
lines <- c("2024-05-01,coffee,3.20", "2024-05-02,tea,2.80")
parts <- strsplit(lines, ",")
parts[[1]]
sapply(parts, `[`, 2) # the 2nd field of every line
strsplit("a b c", " +")[[1]] # split on one or more spaces
paste(rev(strsplit("level up", "")[[1]]), collapse = "")[1] "2024-05-01" "coffee" "3.20"
[1] "coffee" "tea"
[1] "a" "b" "c"
[1] "pu level"
Testing the start and end
r · try it yourself
files <- c("report.pdf", "data.csv", "draft_report.docx", "summary.csv")
endsWith(files, ".csv")
startsWith(files, "draft")
files[endsWith(files, ".csv")][1] FALSE TRUE FALSE TRUE
[1] FALSE FALSE TRUE FALSE
[1] "data.csv" "summary.csv"
Formatting with sprintf()
sprintf() builds a string from a template. Each % placeholder is replaced by the next argument:
| Placeholder | Meaning | Example | Result |
|---|---|---|---|
%s |
string | sprintf("%s!", "hi") |
"hi!" |
%d |
integer | sprintf("%03d", 7L) |
"007" |
%f / %.2f |
decimal | sprintf("%.2f", pi) |
"3.14" |
%e |
scientific | sprintf("%.1e", 12345) |
"1.2e+04" |
%5s / %-5s |
padded right / left | `sprintf("%-5s | ", "ab")` |
%% |
a literal % |
sprintf("%d%%", 50L) |
"50%" |
r · try it yourself
items <- c("Coffee", "Croissant", "Juice")
price <- c(3.2, 2.75, 4)
receipt <- sprintf("%-10s %6.2f", items, price)
writeLines(receipt)
sprintf("Total: %.2f (%d items)", sum(price), length(price))
sprintf("Progress: %d%%", 75L)Coffee 3.20
Croissant 2.75
Juice 4.00
[1] "Total: 9.95 (3 items)"
[1] "Progress: 75%"
format() and formatC()
format() makes numbers look consistent; formatC() gives C-style control including padding with zeros and thousands separators:
r · try it yourself
format(c(1, 10, 100)) # common width
format(1234567.891, big.mark = ",", nsmall = 2)
format(0.123456, digits = 2)
formatC(42, width = 6, flag = "0")
formatC(c(3.14159, 2.5), format = "f", digits = 1)
formatC(1e6, format = "d", big.mark = " ")[1] " 1" " 10" "100"
[1] "1,234,567.89"
[1] "0.12"
[1] "000042"
[1] "3.1" "2.5"
[1] "1 000 000"
Repeating and padding
r · try it yourself
strrep("-", 20)
strrep("ab", 1:3)
formatC("left", width = 10, flag = "-")
formatC("right", width = 10)[1] "--------------------"
[1] "ab" "abab" "ababab"
[1] "left "
[1] " right"
Test yourself
What does trimws(" hi ") return?
- "hi "
- " hi"
- "hi"
- " hi "
What is sprintf("%05.1f", 3.14159)?
- "3.1"
- "003.1"
- "3.14159"
- "00003"
Why does strsplit() return a list?
- Lists are faster
- Each input string can split into a different number of pieces
- It always returns one piece
- For compatibility with Python