Combine Multiple Vectors into a Single Vector

str_c() combines (concatenates) multiple character vectors into a single character vector. Elements from each vector in the correspondingly same positions are pieced together.

library(stringr)
x <- c("waffle", "butter", "syrup")y <- c( "x3", "x1", "x2")z <- c( "$2", "$4", "$8")
str_c(x, y)

Output:

[1] "wafflex3" "butterx1" "syrupx2"
str_c(x, y, z)

Output:

[1] "wafflex3$2" "butterx1$4" "syrupx2$8"

Use sep to specify a separator between each string piece.

str_c(x, y, z, sep = ", ")

Output:

[1] "waffle, x3, $2" "butter, x1, $4" "syrup, x2, $8"

Here the single length vector in Walmart is recycled three times to combine with elements in x, y and z.

str_c(x, y, z, "in Walmart", sep = ", ")

Output:

[1] "waffle, x3, $2, in Walmart" "butter, x1, $4, in Walmart" "syrup, x2, $8, in Walmart"

The argument collapse defaults to NULL. If otherwise specified, the resulted vector will be flattened into a vector of length 1, as performed by str_flatten().

str_c(x, y, z, sep = ", " , collapse = " - ")

Output:

[1] "waffle, x3, $2 - butter, x1, $4 - syrup, x2, $8"

🏆 One level up !

str_c() is similar to the base R function paste0(), but differs in two ways. The first difference lies in the handling of missing value NA. In paste0(), NA combines as a normal string. In str_c(), NA does not combine with any string, and is returned as a missing value; this can cause loss of information during string combination.

# NA combines as a normal stringpaste0(c("a", NA, "b"), "c")

Output:

[1] "ac" "NAc" "bc"
# NA not combine with any string str_c(c("a", NA, "b"), "c") 

Output:

[1] "ac" NA "bc"

To avoid loss of information, consider use str_replace_NA() to turn NA into a "NA" character string, before string combination.

str_c( str_replace_na(c("a", NA, "b")), "c" )

Output:

[1] "ac" "NAc" "bc"

The second difference between paste0() and str_c() lies in the extent by which a shorter vector is recycled (repeated) to match the length of a longer vector during combination.

# letters "a" and "b" recycles to match numbers 1 to 4paste0(c("a", "b"), 1:4)

Output:

[1] "a1" "b2" "a3" "b4"

In the example of str_c() below, while “a” can be recycled to match numbers 1 to 4, attempt to combine with c("a", "b") will induce an error.

str_c("a", 1:4)

Output:

[1] "a1" "a2" "a3" "a4"
# not run; this line will cause an errorstr_c(c("a", "b"), 1:4)