R Strings
Text in R is stored in character vectors. A string is written with double quotes "..." or single quotes '...'; both mean the same thing.
greeting <- "Hello"
name <- 'world'
greeting
class(name)
nchar(greeting)[1] "Hello"
[1] "character"
[1] 5
Multi-line strings
A string can span several lines. The line breaks become part of the text. cat() shows them; printing shows the escaped \n:
poem <- "Roses are red,
R is free."
poem
cat(poem, "\n")[1] "Roses are red,\nR is free."
Roses are red,
R is free.
Combining strings
Use paste() (space separator) or paste0() (no separator). The collapse argument joins the elements of a vector into one string:
paste("data", "science")
paste("file", 1:3, sep = "_")
paste0("Q", 1:4)
words <- c("R", "is", "vectorised")
paste(words, collapse = " ")[1] "data science"
[1] "file_1" "file_2" "file_3"
[1] "Q1" "Q2" "Q3" "Q4"
[1] "R is vectorised"
Changing case and extracting parts
title <- "Data Analysis with R"
toupper(title)
tolower(title)
substr(title, 1, 4)
substr(title, nchar(title) - 5, nchar(title))[1] "DATA ANALYSIS WITH R"
[1] "data analysis with r"
[1] "Data"
[1] "with R"
R counts positions from 1, and substr(x, start, stop) includes both ends.
Searching and replacing
grepl() tells you whether a pattern occurs, sub() replaces the first match and gsub() replaces them all. By default the pattern is a regular expression; add fixed = TRUE to search for literal text:
files <- c("report.csv", "notes.txt", "data.csv")
grepl(".csv", files, fixed = TRUE)
sub("csv", "tsv", files)
gsub("a", "A", "banana")
strsplit("red,green,blue", ",")[[1]][1] TRUE FALSE TRUE
[1] "report.tsv" "notes.txt" "data.tsv"
[1] "bAnAnA"
[1] "red" "green" "blue"
strsplit() returns a list (one element per input string), so [[1]] takes the first element.
Comparing strings
Strings are compared character by character. == checks for exact equality (case matters), and %in% checks membership:
"apple" == "Apple"
tolower("apple") == tolower("Apple")
"cat" < "dog"
"kiwi" %in% c("apple", "kiwi", "mango")[1] FALSE
[1] TRUE
[1] TRUE
[1] TRUE
Tip: The String Functions and Regular Expressions lessons later in the course go much deeper:
sprintf(),trimws(),formatC(),regmatches()and more.
Test yourself
What does nchar("R lang") return?
- 5
- 6
- 2
- 1
What does paste(c("a", "b"), collapse = "+") return?
- "a b"
- "a+b"
- c("a+", "b+")
- "ab"
What does substr("statistics", 1, 4) return?
- "stat"
- "tati"
- "stati"
- "tist"