R, lesson 8
Text in R lives in character vectors, so every string function works on one string or on many at once. Here are the tools you will reach for most.
word <- "Banana"
nchar(word) # 6 characters
toupper(word) # "BANANA"
tolower(word) # "banana"Note that length(word) is 1: it counts strings in the vector, not characters. nchar()
counts characters.
substr(x, start, stop) returns the characters from position start to stop, counting from 1:
substr("Banana", 1, 3) # "Ban"
substr("Banana", 6, 6) # "a" (the last character)paste() joins values with a space, paste0() joins them with nothing, and the collapse
argument squeezes a whole vector into one string:
For numbers with a fixed layout, use sprintf(). A width pads the value: %-8s left-aligns
text in 8 characters, %3d right-aligns a whole number in 3.
strsplit(x, pattern) cuts a string at each match and returns a list with one element per
input string. Take the first with [[1]]. The pattern is a regular expression, so " +" means
"one or more spaces", which copes with messy spacing:
Splitting with "" gives single characters, and rev() reverses a vector, so
paste(rev(strsplit("stop", "")[[1]]), collapse = "") gives "pots".
trimws(x) removes spaces at both ends. gsub(pattern, replacement, x) replaces every match and
sub() replaces only the first. grepl(pattern, x) returns TRUE where the pattern is found.
Add fixed = TRUE to any of them to treat the pattern as plain text instead of a regular
expression, which avoids surprises with characters like .:
The second exercise brings the whole course together: reading input (lesson 3), decisions (lesson 4), a loop (lesson 5), a helper function (lesson 6), vectors (lesson 7) and formatted text (this lesson). Build it a step at a time. First read and print the data back unchanged, then add the grade function, then the summary lines. Run it after every step so you always know which change broke something.
2 exercises to try what you just read.
paste("New", "York") # "New York"
paste0("file", 3, ".csv") # "file3.csv"
paste(c("a", "b", "c"), collapse = "-") # "a-b-c"sprintf("%-6s|%4.1f", "Tea", 2.5) # "Tea | 2.5"words <- strsplit("the quick brown", " +")[[1]] # "the" "quick" "brown"gsub("cat", "dog", "cat and catfish") # "dog and dogfish"
grepl(".", "abc", fixed = TRUE) # FALSE: no literal dot grace Brewster HOPPERG.B.H.
ghopperAda 91
Ben 67
Cleo 78Ada 91 A
Ben 67 C
Cleo 78 B
Average: 78.7
Top: Ada