<p>So far, you’ve used a bunch of strings without learning much about the details. Now it’s time to dive into them, learn what makes strings tick, and master some of the powerful string manipulation tools you have at your disposal.</p>
<p>We’ll begin with the details of creating strings and character vectors. You’ll then dive into creating strings from data, then the opposite; extracting strings from data. We’ll then discuss tools that work with individual letters. The chapter finishes with functions that work with individual letters and a brief discussion of where your expectations from English might steer you wrong when working with other languages.</p>
<p>In this chapter, we’ll use functions from the stringr package, which is part of the core tidyverse. We’ll also use the babynames data since it provides some fun strings to manipulate.</p>
<p>You can quickly tell when you’re using a stringr function because all stringr functions start with <code>str_</code>. This is particularly useful if you use RStudio because typing <code>str_</code> will trigger autocomplete, allowing you to jog your memory of the available functions.</p>
<p>We’ve created strings in passing earlier in the book but didn’t discuss the details. Firstly, you can create a string using either single quotes (<code>'</code>) or double quotes (<code>"</code>). There’s no difference in behavior between the two, so in the interests of consistency, the <ahref="https://style.tidyverse.org/syntax.html#character-vectors">tidyverse style guide</a> recommends using <code>"</code>, unless the string contains multiple <code>"</code>.</p>
<p>Beware that the printed representation of a string is not the same as the string itself because the printed representation shows the escapes (in other words, when you print a string, you can copy and paste the output to recreate that string). To see the raw contents of the string, use <code><ahref="https://stringr.tidyverse.org/reference/str_view.html">str_view()</a></code><spandata-type="footnote">Or use the base R function <code><ahref="https://rdrr.io/r/base/writeLines.html">writeLines()</a></code>.</span>:</p>
<p>Creating a string with multiple quotes or backslashes gets confusing quickly. To illustrate the problem, let’s create a string that contains the contents of the code block where we define the <code>double_quote</code> and <code>single_quote</code> variables:</p>
<p>That’s a lot of backslashes! (This is sometimes called <ahref="https://en.wikipedia.org/wiki/Leaning_toothpick_syndrome">leaning toothpick syndrome</a>.) To eliminate the escaping, you can instead use a <strong>raw string</strong><spandata-type="footnote">Available in R 4.0.0 and above.</span>:</p>
<p>A raw string usually starts with <code>r"(</code> and finishes with <code>)"</code>. But if your string contains <code>)"</code> you can instead use <code>r"[]"</code> or <code>r"{}"</code>, and if that’s still not enough, you can insert any number of dashes to make the opening and closing pairs unique, e.g., <code>`r"--()--"</code>, <code>`r"---()---"</code>, etc. Raw strings are flexible enough to handle any text.</p>
<p>As well as <code>\"</code>, <code>\'</code>, and <code>\\</code>, there are a handful of other special characters that may come in handy. The most common are <code>\n</code>, newline, and <code>\t</code>, tab. You’ll also sometimes see strings containing Unicode escapes that start with <code>\u</code> or <code>\U</code>. This is a way of writing non-English characters that work on all systems. You can see the complete list of other special characters in <code><ahref="https://rdrr.io/r/base/Quotes.html">?'"'</a></code>.</p>
<p>Note that <code><ahref="https://stringr.tidyverse.org/reference/str_view.html">str_view()</a></code> uses a blue background for tabs to make them easier to spot. One of the challenges of working with text is that there’s a variety of ways that white space can end up in the text, so this background helps you recognize that something strange is going on.</p>
<p>Create the string in your R session and print it. What happens to the special “\u00a0”? How does <code><ahref="https://stringr.tidyverse.org/reference/str_view.html">str_view()</a></code> display it? Can you do a little googling to figure out what this special character is?</p>
<p>Now that you’ve learned the basics of creating a string or two by “hand”, we’ll go into the details of creating strings from other strings. This will help you solve the common problem where you have some text you wrote that you want to combine with strings from a data frame. For example, you might combine “Hello” with a <code>name</code> variable to create a greeting. We’ll show you how to do this with <code><ahref="https://stringr.tidyverse.org/reference/str_c.html">str_c()</a></code> and <code><ahref="https://stringr.tidyverse.org/reference/str_glue.html">str_glue()</a></code> and how you can use them with <code><ahref="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code>. That naturally raises the question of what string functions you might use with <code><ahref="https://dplyr.tidyverse.org/reference/summarise.html">summarize()</a></code>, so we’ll finish this section with a discussion of <code><ahref="https://stringr.tidyverse.org/reference/str_flatten.html">str_flatten()</a></code>, which is a summary function for strings.</p>
<p><code><ahref="https://stringr.tidyverse.org/reference/str_c.html">str_c()</a></code> takes any number of vectors as arguments and returns a character vector:</p>
<p><code><ahref="https://stringr.tidyverse.org/reference/str_c.html">str_c()</a></code> is very similar to the base <code><ahref="https://rdrr.io/r/base/paste.html">paste0()</a></code>, but is designed to be used with <code><ahref="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code> by obeying the usual tidyverse rules for recycling and propagating missing values:</p>
<p>If you want missing values to display in another way, use <code><ahref="https://dplyr.tidyverse.org/reference/coalesce.html">coalesce()</a></code> to replace them. Depending on what you want, you might use it either inside or outside of <code><ahref="https://stringr.tidyverse.org/reference/str_c.html">str_c()</a></code>:</p>
<p>If you are mixing many fixed and variable strings with <code><ahref="https://stringr.tidyverse.org/reference/str_c.html">str_c()</a></code>, you’ll notice that you type a lot of <code>"</code>s, making it hard to see the overall goal of the code. An alternative approach is provided by the <ahref="https://glue.tidyverse.org">glue package</a> via <code><ahref="https://stringr.tidyverse.org/reference/str_glue.html">str_glue()</a></code><spandata-type="footnote">If you’re not using stringr, you can also access it directly with <code><ahref="https://glue.tidyverse.org/reference/glue.html">glue::glue()</a></code>.</span>. You give it a single string that has a special feature: anything inside <code><ahref="https://rdrr.io/r/base/Paren.html">{}</a></code> will be evaluated like it’s outside of the quotes:</p>
<p>As you can see, <code><ahref="https://stringr.tidyverse.org/reference/str_glue.html">str_glue()</a></code> currently converts missing values to the string <code>"NA"</code> unfortunately making it inconsistent with <code><ahref="https://stringr.tidyverse.org/reference/str_c.html">str_c()</a></code>.</p>
<p>You also might wonder what happens if you need to include a regular <code>{</code> or <code>}</code> in your string. You’re on the right track if you guess you’ll need to escape it somehow. The trick is that glue uses a slightly different escaping technique; instead of prefixing with special character like <code>\</code>, you double up the special characters:</p>
<p><code><ahref="https://stringr.tidyverse.org/reference/str_c.html">str_c()</a></code> and <code>glue()</code> work well with <code><ahref="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code> because their output is the same length as their inputs. What if you want a function that works well with <code><ahref="https://dplyr.tidyverse.org/reference/summarise.html">summarize()</a></code>, i.e., something that always returns a single string? That’s the job of <code><ahref="https://stringr.tidyverse.org/reference/str_flatten.html">str_flatten()</a></code><spandata-type="footnote">The base R equivalent is <code><ahref="https://rdrr.io/r/base/paste.html">paste()</a></code> used with the <code>collapse</code> argument.</span>: it takes a character vector and combines each element of the vector into a single string:</p>
<p>Compare and contrast the results of <code><ahref="https://rdrr.io/r/base/paste.html">paste0()</a></code> with <code><ahref="https://stringr.tidyverse.org/reference/str_c.html">str_c()</a></code> for the following inputs:</p>
<p>Convert the following expressions from <code><ahref="https://stringr.tidyverse.org/reference/str_c.html">str_c()</a></code> to <code><ahref="https://stringr.tidyverse.org/reference/str_glue.html">str_glue()</a></code> or vice versa:</p>
<p>It’s very common for multiple variables to be crammed together into a single string. In this section, you’ll learn how to use four tidyr functions to extract them:</p>
</ul><p>If you look closely, you can see there’s a common pattern here: <code>separate_</code>, then <code>longer</code> or <code>wider</code>, then <code>_</code>, then by <code>delim</code> or <code>position</code>. That’s because these four functions are composed of two simpler primitives:</p>
<code>longer</code> makes the input data frame longer, creating new rows; <code>wider</code> makes the input data frame wider, generating new columns.</li>
<code>delim</code> splits up a string with a delimiter like <code>", "</code> or <code>" "</code>; <code>position</code> splits at specified widths, like <code>c(3, 5, 2)</code>.</li>
</ul><p>We’ll return to the last member of this family, <code>separate_regex_wider()</code>, in <ahref="#chp-regexps"data-type="xref">#chp-regexps</a>. It’s the most flexible of the <code>wider</code> functions, but you need to know something about regular expressions before you can use it.</p>
<p>The following two sections will give you the basic idea behind these separate functions, first separating into rows (which is a little simpler) and then separating into columns. We’ll finish off by discussing the tools that the <code>wider</code> functions give you to diagnose problems.</p>
<p>Separating a string into rows tends to be most useful when the number of components varies from row to row. The most common case is requiring <code><ahref="https://tidyr.tidyverse.org/reference/separate_longer_delim.html">separate_longer_delim()</a></code> to split based on a delimiter:</p>
<p>It’s rarer to see <code><ahref="https://tidyr.tidyverse.org/reference/separate_longer_delim.html">separate_longer_position()</a></code> in the wild, but some older datasets do use a very compact format where each character is used to record a value:</p>
<p>Separating a string into columns tends to be most useful when there are a fixed number of components in each string, and you want to spread them into columns. They are slightly more complicated than their <code>longer</code> equivalents because you need to name the columns. For example, in this following dataset, <code>x</code> is made up of a code, an edition number, and a year, separated by <code>"."</code>. To use <code><ahref="https://tidyr.tidyverse.org/reference/separate_wider_delim.html">separate_wider_delim()</a></code>, we supply the delimiter and the names in two arguments:</p>
<p><code><ahref="https://tidyr.tidyverse.org/reference/separate_wider_delim.html">separate_wider_position()</a></code> works a little differently because you typically want to specify the width of each column. So you give it a named integer vector, where the name gives the name of the new column, and the value is the number of characters it occupies. You can omit values from the output by not naming them:</p>
<p><code><ahref="https://tidyr.tidyverse.org/reference/separate_wider_delim.html">separate_wider_delim()</a></code><spandata-type="footnote">The same principles apply to <code><ahref="https://tidyr.tidyverse.org/reference/separate_wider_delim.html">separate_wider_position()</a></code> and <code><ahref="https://tidyr.tidyverse.org/reference/separate_wider_delim.html">separate_wider_regex()</a></code>.</span> requires a fixed and known set of columns. What happens if some of the rows don’t have the expected number of pieces? There are two possible problems, too few or too many pieces, so <code><ahref="https://tidyr.tidyverse.org/reference/separate_wider_delim.html">separate_wider_delim()</a></code> provides two arguments to help: <code>too_few</code> and <code>too_many</code>. Let’s first look at the <code>too_few</code> case with the following sample dataset:</p>
<p>When you use the debug mode, you get three extra columns added to the output: <code>x_ok</code>, <code>x_pieces</code>, and <code>x_remainder</code> (if you separate a variable with a different name, you’ll get a different prefix). Here, <code>x_ok</code> lets you quickly find the inputs that failed:</p>
<p><code>x_pieces</code> tells us how many pieces were found, compared to the expected 3 (the length of <code>names</code>). <code>x_remainder</code> isn’t useful when there are too few pieces, but we’ll see it again shortly.</p>
<p>Sometimes looking at this debugging information will reveal a problem with your delimiter strategy or suggest that you need to do more preprocessing before separating. In that case, fix the problem upstream and make sure to remove <code>too_few = "debug"</code> to ensure that new problems become errors.</p>
<p>In other cases, you may want to fill in the missing pieces with <code>NA</code>s and move on. That’s the job of <code>too_few = "align_start"</code> and <code>too_few = "align_end"</code> which allow you to control where the <code>NA</code>s should go:</p>
<p>You have a slightly different set of options for handling too many pieces: you can either silently “drop” any additional pieces or “merge” them all into the final column:</p>
<p>In this section, we’ll introduce you to functions that allow you to work with the individual letters within a string. You’ll learn how to find the length of a string, extract substrings, and handle long strings in plots and tables.</p>
<p>You could use this with <code><ahref="https://dplyr.tidyverse.org/reference/count.html">count()</a></code> to find the distribution of lengths of US babynames and then with <code><ahref="https://dplyr.tidyverse.org/reference/filter.html">filter()</a></code> to look at the longest names<spandata-type="footnote">Looking at these entries, we’d guess that the babynames data drops spaces or hyphens and truncates after 15 letters.</span>:</p>
<p>You can extract parts of a string using <code>str_sub(string, start, end)</code>, where <code>start</code> and <code>end</code> are the positions where the substring should start and end. The <code>start</code> and <code>end</code> arguments are inclusive, so the length of the returned string will be <code>end - start + 1</code>:</p>
<p>Note that <code><ahref="https://stringr.tidyverse.org/reference/str_sub.html">str_sub()</a></code> won’t fail if the string is too short: it will just return as much as possible:</p>
<p>We could use <code><ahref="https://stringr.tidyverse.org/reference/str_sub.html">str_sub()</a></code> with <code><ahref="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code> to find the first and last letter of each name:</p>
<p>Sometimes you care about the length of a string because you’re trying to fit it into a label on a plot or table. stringr provides two useful tools for cases where your string is too long:</p>
<ul><li><p><code>str_trunc(x, 30)</code> ensures that no string is longer than 30 characters, replacing any letters after 30 with <code>…</code>.</p></li>
<li><p><code>str_wrap(x, 30)</code> wraps a string introducing new lines so that each line is at most 30 characters (it doesn’t hyphenate, however, so any word longer than 30 characters will make a longer line)</p></li>
<oltype="1"><li>Use <code><ahref="https://stringr.tidyverse.org/reference/str_length.html">str_length()</a></code> and <code><ahref="https://stringr.tidyverse.org/reference/str_sub.html">str_sub()</a></code> to extract the middle letter from each baby name. What will you do if the string has an even number of characters?</li>
<p>So far, we’ve focused on English language text which is particularly easy to work with for two reasons. Firstly, the English alphabet is relatively simple: there are just 26 letters. Secondly (and maybe more importantly), the computing infrastructure we use today was predominantly designed by English speakers. Unfortunately, we don’t have room for a full treatment of non-English languages. Still, we wanted to draw your attention to some of the biggest challenges you might encounter: encoding, letter variations, and locale-dependent functions.</p>
<p>When working with non-English text, the first challenge is often the <strong>encoding</strong>. To understand what’s going on, we need to dive into how computers represent strings. In R, we can get at the underlying representation of a string using <code><ahref="https://rdrr.io/r/base/rawConversion.html">charToRaw()</a></code>:</p>
<p>Each of these six hexadecimal numbers represents one letter: <code>48</code> is H, <code>61</code> is a, and so on. The mapping from hexadecimal number to character is called the encoding, and in this case, the encoding is called ASCII. ASCII does a great job of representing English characters because it’s the <strong>American</strong> Standard Code for Information Interchange.</p>
<p>Things aren’t so easy for languages other than English. In the early days of computing, there were many competing standards for encoding non-English characters. For example, there were two different encodings for Europe: Latin1 (aka ISO-8859-1) was used for Western European languages, and Latin2 (aka ISO-8859-2) was used for Central European languages. In Latin1, the byte <code>b1</code> is “±”, but in Latin2, it’s “ą”! Fortunately, today there is one standard that is supported almost everywhere: UTF-8. UTF-8 can encode just about every character used by humans today and many extra symbols like emojis.</p>
<p>readr uses UTF-8 everywhere. This is a good default but will fail for data produced by older systems that don’t use UTF-8. If this happens, your strings will look weird when you print them. Sometimes just one or two characters might be messed up; other times, you’ll get complete gibberish. For example here are two inline CSVs with unusual encodings<spandata-type="footnote">Here I’m using the special <code>\x</code> to encode binary data directly into a string.</span>:</p>
<p>How do you find the correct encoding? If you’re lucky, it’ll be included somewhere in the data documentation. Unfortunately, that’s rarely the case, so readr provides <code><ahref="https://readr.tidyverse.org/reference/encoding.html">guess_encoding()</a></code> to help you figure it out. It’s not foolproof and works better when you have lots of text (unlike here), but it’s a reasonable place to start. Expect to try a few different encodings before you find the right one.</p>
<p>Encodings are a rich and complex topic; we’ve only scratched the surface here. If you’d like to learn more, we recommend reading the detailed explanation at <ahref="http://kunststube.net/encoding/"class="uri">http://kunststube.net/encoding/</a>.</p>
<p>Working in languages with accents poses a significant challenge when determining the position of letters (e.g., with <code><ahref="https://stringr.tidyverse.org/reference/str_length.html">str_length()</a></code> and <code><ahref="https://stringr.tidyverse.org/reference/str_sub.html">str_sub()</a></code>) as accented letters might be encoded as a single individual character (e.g., ü) or as two characters by combining an unaccented letter (e.g., u) with a diacritic mark (e.g., ¨). For example, this code shows two ways of representing ü that look identical:</p>
<p>Finally, note that a comparison of these strings with <code>==</code> interprets these strings as different, while the handy <code><ahref="https://stringr.tidyverse.org/reference/str_equal.html">str_equal()</a></code> function in stringr recognizes that both have the same appearance:</p>
<p>Finally, there are a handful of stringr functions whose behavior depends on your <strong>locale</strong>. A locale is similar to a language but includes an optional region specifier to handle regional variations within a language. A locale is specified by a lower-case language abbreviation, optionally followed by a <code>_</code> and an upper-case region identifier. For example, “en” is English, “en_GB” is British English, and “en_US” is American English. If you don’t already know the code for your language, <ahref="https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes">Wikipedia</a> has a good list, and you can see which are supported in stringr by looking at <code><ahref="https://rdrr.io/pkg/stringi/man/stri_locale_list.html">stringi::stri_locale_list()</a></code>.</p>
<p>Base R string functions automatically use the locale set by your operating system. This means that base R string functions do what you expect for your language, but your code might work differently if you share it with someone who lives in a different country. To avoid this problem, stringr defaults to English rules by using the “en” locale and requires you to specify the <code>locale</code> argument to override it. Fortunately, there are two sets of functions where the locale really matters: changing case and sorting.</p>
<p>The rules for changing cases differ among languages. For example, Turkish has two i’s: with and without a dot. Since they’re two distinct letters, they’re capitalized differently:</p>
<p>Sorting strings depends on the order of the alphabet, and the order of the alphabet is not the same in every language<spandata-type="footnote">Sorting in languages that don’t have an alphabet, like Chinese, is more complicated still.</span>! Here’s an example: in Czech, “ch” is a compound letter that appears after <code>h</code> in the alphabet.</p>
<p>This also comes up when sorting strings with <code><ahref="https://dplyr.tidyverse.org/reference/arrange.html">dplyr::arrange()</a></code>, which is why it also has a <code>locale</code> argument.</p>
<p>In this chapter, you’ve learned about some of the power of the stringr package: how to create, combine, and extract strings, and about some of the challenges you might face with non-English strings. Now it’s time to learn one of the most important and powerful tools for working with strings: regular expressions. Regular expressions are a very concise but very expressive language for describing patterns within strings and are the topic of the next chapter.</p>