str_c

The function stringr::str_c() combines multiple character vectors into a single character vector. It is similar to the paste0() function.

Tidyverse reference page

Scalar and vector

We can combine one string to a vector of strings.

Add “day” to the end of the weekday prefixes.

#Create a vector
vec <- c("Mon", "Tues", "Wednes", "Thurs", "Fri")
#Combine with day at the end
weekdays <- stringr::str_c(vec, "day")
#View
weekdays |> stringr::str_view()
[1] │ Monday
[2] │ Tuesday
[3] │ Wednesday
[4] │ Thursday
[5] │ Friday

A separator can be chosen between the strings to be combined with sep=.

Using the created weekdays vector print out the weekdays with “Weekday” at the start and the sperator : (note the space after the :).

#Combine with day at the end
stringr::str_c("Weekday", weekdays, sep = ": ") |>
    stringr::str_view()
[1] │ Weekday: Monday
[2] │ Weekday: Tuesday
[3] │ Weekday: Wednesday
[4] │ Weekday: Thursday
[5] │ Weekday: Friday

Of course you can combine more than two string objects.

Create a longer sentence with the weekday in the middle.

#Combine with day at the end
stringr::str_c("The day ", weekdays, " is a weekday.") |>
    stringr::str_view()
[1] │ The day Monday is a weekday.
[2] │ The day Tuesday is a weekday.
[3] │ The day Wednesday is a weekday.
[4] │ The day Thursday is a weekday.
[5] │ The day Friday is a weekday.

Vector and vector

You can combine multiple vectors together.

Create sentences stating the national plants of the four UK countries.

#Create vectors
plants <- c("Rose", "Thistle", "Leek", "Shamrock")
countries <- c("England", "Scotland", "Wales", "Northern Ireland")
#Combine vectors
stringr::str_c("The ", plants, " is the national plant of ", countries) |>
    stringr::str_view()
[1] │ The Rose is the national plant of England
[2] │ The Thistle is the national plant of Scotland
[3] │ The Leek is the national plant of Wales
[4] │ The Shamrock is the national plant of Northern Ireland

Recycling elements

With paste0() vectors of different length can be combined using the recycling rule.

#Create vectors
vec1 <- c("a", "b", "c")
vec2 <- c("y", "z")
#Combine vectors
paste0(vec1, vec2)
[1] "ay" "bz" "cy"

On the other hand str_c() does not work with vectors of different lengths. If you run the below command it will not work.

#Combine vectors
stringr::str_c(vec1, vec2)

Missing values

Missing values in R are presented as NA.

When a NA is used in paste0() it will treat it as a string. You can see this in action in the below command when the "b" is combined with "NA".

#Create vectors
vec1 <- c("a", "b", "c")
vec2 <- c("x", NA, "z")
#Combine vectors
paste0(vec1, vec2)
[1] "ax"  "bNA" "cz" 

A NA with str_c() produces a NA. Notice how the second value is a proper missing value (NA) with no quotes

#Combine vectors
stringr::str_c(vec1, vec2) 
[1] "ax" NA   "cz"