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.
Bu egzersiz
String Manipulation with stringr in R
kursunun bir parçasıdırEgzersiz talimatları
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_andto 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_strto see whatstr_c()does with the missing values. - Take the next step in our order, by using
paste()onmy_toppings_andwithcollapse = ", ". - Take the next step in our order, by using
str_c()onmy_toppings_strwithcollapse = ", ". See the difference: just oneNAwill make our entire resultNA.
Uygulamalı interaktif egzersiz
Bu örnek kodu tamamlayarak bu egzersizi bitirin.
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 = ", "
___