Putting strings together with stringr
For your first stringr
function, we'll look at str_c()
, the c
is short for concatenate, a function that works like paste()
. It takes vectors of strings as input along with sep
and collapse
arguments.
There are two key ways str_c()
differs from paste()
. First, the default separator is an empty string, sep = ""
, as opposed to a space, so it's more like paste0()
. This is an example of a stringr
function, performing a similar operation to a base
function, but using a default that is more likely to be what you want. Remember in your pizza order, you had to set sep = ""
multiple times.
The second way str_c()
differs to paste()
is in its handling of missing values. paste()
turns missing values into the string "NA"
, whereas str_c()
propagates missing values. That means combining any strings with a missing value will result in another missing value.
Let's explore this difference using your pizza order from the previous chapter.
This is a part of the course
“String Manipulation with stringr in R”
Exercise instructions
We've set up a new my_toppings
vector that has a few missing values and taken the first step of creating our order.
- Print
my_toppings_and
to see whatpaste()
did with the missing values. - Repeat the
paste()
statement but instead usestr_c()
. You can save some typing by leaving offsep = ""
since that is the default. Call this stringmy_toppings_str
. - Print
my_toppings_str
to see whatstr_c()
does with the missing values. - Take the next step in our order, by using
paste()
onmy_toppings_and
withcollapse = ", "
. - Take the next step in our order, by using
str_c()
onmy_toppings_str
withcollapse = ", "
. See the difference: just oneNA
will make our entire resultNA
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
library(stringr)
my_toppings <- c("cheese", NA, NA)
my_toppings_and <- paste(c("", "", "and "), my_toppings, sep = "")
# Print my_toppings_and
___
# Use str_c() instead of paste(): my_toppings_str
my_toppings_str <- ___
# Print my_toppings_str
___
# paste() my_toppings_and with collapse = ", "
___
# str_c() my_toppings_str with collapse = ", "
___