Learn/R/8. Strings and a small project
Lesson 8 of 8
Sign in

R, lesson 8

Strings and a small project

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.

Measuring and changing case

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.

Slicing

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)

Joining

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.

Splitting and cleaning

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 .:

A small project

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.

Further reading

  • R documentation: nchar()
  • R documentation: substr()
  • R documentation: strsplit()
  • R documentation: sprintf()
  • An Introduction to R

2 exercises to try what you just read.

Exercise 1

Username maker

Read a full name on one line. It may have extra spaces at the start, at the end, or between the words, and any mix of upper and lower case. Print two lines:

  1. The initials in capitals, each followed by a dot.
  2. A username: the first letter of the first name followed by the whole last name, all in lower case.

Sample input:

Sample output:

Press Ctrl Enter or Check to test your code.

Exercise 2

Gradebook

Each input line holds a student's name and a whole-number score, separated by a space. Write a function grade(score) that returns A for 85 or more, B for 70 or more, C for 50 or more, and F otherwise. Then print:

  • one line per student, in input order, formatted with sprintf("%-8s%3d %s", name, score, grade),
  • Average: followed by the average score with 1 decimal,
  • Top: followed by the name of the student with the highest score (the first one if there is a tie).

Sample input:

Sample output:

Press Ctrl Enter or Check to test your code.

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 HOPPER
G.B.H.
ghopper
Ada 91
Ben 67
Cleo 78
Ada      91 A
Ben      67 C
Cleo     78 B
Average: 78.7
Top: Ada