A string is text written inside single or double quotes. R stores every string with double quotes internally. This tutorial covers creating, joining, formatting and changing strings.
What You Will Learn
- Quote rules
- paste() and paste0()
- format() for numbers and alignment
- nchar, toupper, tolower, substr, chartr
- strsplit, sub and gsub
- Set functions on character vectors
Prerequisites
Creating Strings
a <- 'Start and end with single quote'
c <- "single quote ' in between double quotes"
d <- 'Double quotes " in between single quote'
print(c); print(d)
[1] "single quote ' in between double quotes" [1] "Double quotes \" in between single quote"
Explanation: Start and end with the same quote type. A double quote inside a string is shown escaped as \" when printed.
Joining with paste()
a <- "Hello"; b <- 'How'; c <- "are you? "
print(paste(a, b, c))
print(paste(a, b, c, sep = "-"))
print(paste(a, b, c, sep = ""))
[1] "Hello How are you? " [1] "Hello-How-are you? " [1] "HelloHoware you? "
More on joining in cat() and paste().
format()
print(format(23.123456789, digits = 4))
print(format(c(6, 13.14521), scientific = TRUE))
print(format(23.47, nsmall = 5))
print(format(13.7, width = 6))
print(format("Hello", width = 8, justify = "c"))
[1] "23.12" [1] "6.000000e+00" "1.314521e+01" [1] "23.47000" [1] " 13.7" [1] " Hello "
Explanation: digits sets significant digits, nsmall the minimum decimals, width pads to a fixed width, and justify aligns text.
Common String Functions
print(nchar("Count the number of characters"))
print(toupper("Changing To Upper"))
print(tolower("Changing To Lower"))
print(substr("Extract", 5, 7))
print(chartr("o", "0", "Welcome to Itronix Solutions"))
[1] 30 [1] "CHANGING TO UPPER" [1] "changing to lower" [1] "act" [1] "Welc0me t0 Itr0nix S0luti0ns"
| Function | Does | stringr equivalent |
|---|---|---|
| nchar() | Number of characters | str_length() |
| toupper()/tolower() | Change case | str_to_upper()/str_to_lower() |
| substr() | Extract part | str_sub() |
| chartr() | Replace characters one-for-one | – |
| strsplit() | Split into pieces | str_split() |
| sub()/gsub() | Replace first/all matches | str_replace()/str_replace_all() |
Split and Replace
print(strsplit("Do you wish you were Mr. Jones?", " ")[[1]])
s <- "England is Beautiful. England is not the part of EU"
print(sub("England", "UK", s))
print(gsub("England", "UK", s))
[1] "Do" "you" "wish" "you" "were" "Mr." "Jones?" [1] "UK is Beautiful. England is not the part of EU" [1] "UK is Beautiful. UK is not the part of EU"
Explanation: strsplit returns a list (one element per input string), so [[1]] takes the first. sub replaces the first match, gsub all matches; both accept regular expressions.
Set Functions and abbreviate()
setA <- c("a", "b", "c", "d", "e"); setB <- c("d", "e", "f", "g")
print(setdiff(setA, setB)); print(union(setA, setB)); print(intersect(setA, setB))
print(setequal(c(1, 2, 3), c(1, 2, 100)))
print(abbreviate(c("abcdefgh", "efgh", "abceg"), 2))
[1] "a" "b" "c" [1] "a" "b" "c" "d" "e" "f" "g" [1] "d" "e" [1] FALSE abcdefgh efgh abceg "abcd" "ef" "abcg"
Explanation: abbreviate shortens strings but keeps them unique – that is why “abcdefgh” and “abceg” need 4 letters.
Series
R series: Install R · Introduction to R · R in Jupyter · Practical Session · Operators · Decision Making · Loops · Functions · Strings · cat() and paste() · Vectors · Lists · Matrices · Data Frames
Interview Questions
Q: sub vs gsub?
sub replaces the first occurrence; gsub replaces all.
Q: How do you get the 3rd to 5th characters of a string?
substr(x, 3, 5).
Practice Exercises
- Count the vowels in a sentence.
- Convert “machine learning tutorials” to Title Case.
- Replace all spaces in a string with underscores.
Summary
Create strings with matching quotes, join them with paste(), format numbers with format(), and transform them with nchar, toupper, substr, strsplit, sub and gsub.
Next: cat() and paste()
Machine Learning Tutorials, Courses and Certifications