11.1 Character Vectors: Strings

Computers work at least as much with text as they do with numbers. In computer science the values that refer to text are called strings.

In R, as in most other programming languages, we use quotes as delimiters, meaning that they mark the beginning and the end of strings. Recall that in R, strings are of type character. For example:

greeting <- "hello"
typeof(greeting)
## [1] "character"

Of course, a single string does not exist on its own in R. Instead it exists as the only element of a character-vector of length 1.

is.vector(greeting)
## [1] TRUE
length(greeting)
## [1] 1

To make strings we can use double quotes or single quotes. Since the string-value does not include the quotes themselves but only what appears between them, it does not make any difference which type of quotes we use:

greeting1 <- "hello"
greeting2 <- 'hello'
greeting1 == greeting2
## [1] TRUE

When we make a character vector of length greater than one, we can even use both single and double quotes:

politeWords <- c("Please?", 'Thank you!')
politeWords
## [1] "Please?"    "Thank you!"

Notice that when R prints politeWords to the console it uses double-quotes. Indeed, double-quoting is the recommended and most common way to construct strings in R.