R Strings

R provides a rich set of built-in functions for creating, measuring, transforming, and combining text strings.

Creating strings

A string in R is just text wrapped in either double quotes or single quotes, "hello" and 'hello' mean exactly the same thing. Inside a string, a backslash starts an escape sequence: \n inserts a line break, \t inserts a tab, and \" lets you include a literal double quote inside a double-quoted string.

Example

greeting <- "Hello, world!"
multiline <- "Line one\nLine two"
quoted <- "She said \"hi\" to everyone"

cat(greeting, "\n")
cat(multiline, "\n")
cat(quoted, "\n")

Measuring and slicing strings

nchar(x) tells you how many characters are in a string, which is useful for validating input lengths or trimming display text. substr(x, start, stop) extracts the part of a string between two character positions (counting from 1), and it can also be used on the left-hand side of an assignment to replace part of a string in place.

nchar() and substr()

word <- "programming"
nchar(word)             # 11
substr(word, 1, 4)      # "prog"
substr(word, 5, 7)      # "ram"

substr(word, 1, 4) <- "SWIM"
word                     # "SWIMramming"

Changing case and trimming whitespace

Case and Whitespace

title <- "  Learn R Programming  "
toupper(title)     # "  LEARN R PROGRAMMING  "
tolower(title)     # "  learn r programming  "
trimws(title)      # "Learn R Programming" (no leading/trailing spaces)

Joining strings together

paste() glues multiple pieces together, inserting a space between them by default; you can change that separator with the sep argument. paste0() is a shortcut for paste(..., sep = "") that joins pieces with nothing in between, which is handy for building file names or labels. Both functions can also collapse an entire vector into a single string using the collapse argument.

paste() and paste0()

first <- "Learn"
second <- "R"

paste(first, second)                 # "Learn R"
paste(first, second, sep = "-")      # "Learn-R"
paste0(first, second)                # "LearnR"

fruits <- c("apple", "banana", "cherry")
paste(fruits, collapse = ", ")       # "apple, banana, cherry"
FunctionPurposeExample
nchar(x)Count characters in a stringnchar("cat") -> 3
substr(x, a, b)Extract characters from position a to bsubstr("cat", 1, 2) -> "ca"
toupper(x) / tolower(x)Convert to upper or lower casetoupper("cat") -> "CAT"
trimws(x)Remove leading/trailing whitespacetrimws(" cat ") -> "cat"
paste(...) / paste0(...)Join strings together, with or without a separatorpaste0("c", "at") -> "cat"

Exercise: R Strings

What is the main difference between paste() and paste0()?