Strings are not glamorous, high-profile components of R, but they do play a big role in many data cleaning and preparation tasks. The stringr package provide a cohesive set of functions designed to make working with strings as easy as possible. If you’re not familiar with strings, the best place to start is the chapter on strings in R for Data Science.
stringr is built on top of stringi, which uses the ICU C library to provide fast, correct implementations of common string manipulations. stringr focusses on the most important and commonly used string manipulation functions whereas stringi provides a comprehensive set covering almost anything you can imagine. If you find that stringr is missing a function that you need, try looking in stringi. Both packages share similar conventions, so once you’ve mastered stringr, you should find stringi similarly easy to use.
All functions in stringr start with
str_ and take a vector of strings as the first argument.
Most string functions work with regular expressions, a concise language for describing patterns of text. For example, the regular expression
"[aeiou]" matches any single character that is a vowel:
There are seven main verbs that work with patterns:
str_detect(x, pattern) tells you if there’s any match to the pattern.
str_count(x, pattern) counts the number of patterns.
str_subset(x, pattern) extracts the matching components.
str_locate(x, pattern) gives the position of the match.
str_extract(x, pattern) extracts the text of the match.
str_match(x, pattern) extracts parts of the match defined by parentheses.
str_replace(x, pattern, replacement) replaces the matches with new text.
str_split(x, pattern) splits up a string into multiple pieces.
As well as regular expressions (the default), there are three other pattern matching engines:
The RegExplain RStudio addin provides a friendly interface for working with regular expressions and functions from stringr. This addin allows you to interactively build your regexp, check the output of common string matching functions, consult the interactive help pages, or use the included resources to learn regular expressions.
This addin can easily be installed with devtools:
R provides a solid set of string operations, but because they have grown organically over time, they can be inconsistent and a little hard to learn. Additionally, they lag behind the string operations in other programming languages, so that some things that are easy to do in languages like Ruby or Python are rather hard to do in R.
Uses consistent function and argument names. The first argument is always the vector of strings to modify, which makes stringr work particularly well in conjunction with the pipe:
Simplifies string operations by eliminating options that you don’t need 95% of the time.
Produces outputs than can easily be used as inputs. This includes ensuring that missing inputs result in missing outputs, and zero length inputs result in zero length outputs.