4.3 Character Vectors

Text in R is represented by character vectors. In programming, text often is referred to as a string. We can assign strings to variables, just like we did it before with numbers and bools:

> x <- "hello"
> y <- 'world'

Strings are entered using either matching double (") or single (') quotes. We’ve previously discussed that vectors may contain strings or numbers, but only elements of one type. Mixing numbers and strings results in numeric elements being coerced to strings:

> c(3.46, TRUE, "hello", 1+6i, 3L)
[1] "3.46"  "TRUE"  "hello" "1+6i"  "3"    

The function paste() is an important function that you can use to create and build strings. paste() takes one or more R objects, converts them to type “character”, and then concatenates them to form strings.

> paste("one", "two", "three")
[1] "one two three"

As you can see, the default separator is a blank space (sep = " "). You can also select another character, e.g. sep = "...":

> paste("one", "two", "three", sep = "...")
[1] "one...two...three"

The vectors passed to paste() can have length > 1. In this case, they are concatenated term-by-term, and a vector is returned. We can use the argument collapse if we want to concatenate the values in the result to a single string.

> x <- c("one", "two", "three")
> y <- c("X", "Y", "Z")
> paste(x, y, sep = "...")
[1] "one...X"   "two...Y"   "three...Z"
> paste(x, y, sep = "...", collapse = "-")
[1] "one...X-two...Y-three...Z"

If you give paste() vectors of different length, then it will apply the recycling rule. This means that it will just re-use the elements of the shorter vector until it reaches the end of the longer vector:

> paste(c("X", "Y"), 1:5)
[1] "X 1" "Y 2" "X 3" "Y 4" "X 5"

Sometimes, you might want to concatenate the arguments without seperator. In this case, either use sep = "" (empty string) or the function paste0():

> paste("one", "two", "three", sep = "")
[1] "onetwothree"
> paste0("one", "two", "three")
[1] "onetwothree"

4.3.1 Exercises: Character vectors

See Section 18.0.8 for solutions.

  1. Create a single string with elements A1, B2, A3, B4 …, A99, B100.

  2. Create a single string with elements A1, B1, A2, B2, …, A100, B100.

  3. Given the following vectors hello <- "Hello", world <- "World" and bang <- "!", how would you use paste() and paste0() to get the following strings: "Hello World !" "HelloWorld!" "Hello World!" "Hello-World!" "Hello World!!!" "Hello World! Hello World! Hello World!"?