#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
The function stringr::str_c() combines multiple character vectors into a single character vector. It is similar to the paste0() function.
We can combine one string to a vector of strings.
Add “day” to the end of the weekday prefixes.
[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 :).
[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.
You can combine multiple vectors together.
Create sentences stating the national plants of the four UK countries.
[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
With paste0() vectors of different length can be combined using the recycling rule.
[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.
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".
[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