Session Ready
Exercise

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.

Instructions
100 XP

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 what paste() did with the missing values.
  • Repeat the paste() statement but instead use str_c(). You can save some typing by leaving off sep = "" since that is the default. Call this string my_toppings_str.
  • Print my_toppings_str to see what str_c() does with the missing values.
  • Take the next step in our order, by using paste() on my_toppings_and with collapse = ", ".
  • Take the next step in our order, by using str_c() on my_toppings_str with collapse = ", ". See the difference: just one NA will make our entire result NA.