Get startedGet started for free

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 exercise is part of the course

String Manipulation with stringr in R

View Course

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 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.

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 = ", "
___
Edit and Run Code