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:
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:
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.
As you can see, the default separator is a blank space (sep = " "
). You can also select another character, e.g. sep = "..."
:
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:
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.
Create a single string with elements A1, B2, A3, B4 …, A99, B100.
Create a single string with elements A1, B1, A2, B2, …, A100, B100.
Given the following vectors
hello <- "Hello"
,world <- "World"
andbang <- "!"
, how would you usepaste()
andpaste0()
to get the following strings:"Hello World !"
"HelloWorld!"
"Hello World!"
"Hello-World!"
"Hello World!!!"
"Hello World! Hello World! Hello World!"
?