[1] "banana"
7 Adv Data wrangling P2
π§© Learning Goals
By the end of this lesson, you should be able to:
- Manipulate and explore strings using the
stringrpackage - Construct regular expressions to find patterns in strings
Helpful Cheatsheets
The stringr cheatsheet (HTML, PDF) will be useful to have open and reference.
Motivation: 30 Years of American Anxieties
In 2018 the data journalism organization The Pudding featured a story called 30 Years of American Anxieties about themes in 30 years of posts to the Dear Abby column (an American advice column).
One way to understand themes in text data is to conduct a qualitative analysis, a methodology in which multiple readers read through instances of text several times to reach a consensus about themes.
Another way to understand themes in text data is computational text analysis.
- This is what we will explore today.
Both qualitative analysis and computational tools can be used in tandem. Often, using computational tools can help focus a close reading of select texts, which parallels the spirit of a qualitative analysis.
To prepare ourselves for a computational analysis, letβs learn about strings.
Strings
Strings are objects of the character class (abbreviated as <chr> in tibbles).
When you print out strings, they display with double quotes:
Working with strings generally will involve the use of regular expressions, a tool for finding patterns in strings.
Regular expressions (regex, for short) look like the following:
"^the" (Strings that start with "the")
"end$" (Strings that end with "end")
Before getting to regular expressions, letβs go over some fundamentals about working with strings. The stringr package (available within tidyverse) is great for working with strings.
Creating strings
Creating strings by hand is useful for testing out regular expressions.
To create a string, type any text in either double quotes (") or single quotes '. Using double or single quotes doesnβt matter unless your string itself has single or double quotes.
Code
[1] "character"
[1] "character"
[1] "character"
[1] 1
[1] 1
[1] 2
We can view these strings βnaturallyβ (without the opening and closing quotes) with str_view():
[1] β This is a string
[1] β If I want to include a "quote" inside a string, I use single quotes
[1] β This is a string
[2] β If I want to include a "quote" inside a string, I use single quotes
Exercise: Create the string It's Thursday. What happens if you put the string inside single quotes? Double quotes?
[1] β It's Thursday
Single quotes results in error.
Because " and ' are special characters in the creation of strings, R offers another way to put them inside a string. We can escape these special characters by putting a \ in front of them:
Code
[1] β This is a string with "double quotes"
[1] β This is a string with 'single quotes'
Given that \ is a special character, how can we put the \ character in strings? We have to escape it with \\.
Exercise: Create the string C:\Users. What happens when you donβt escape the \?
Not escaping it results in an error.
Other special characters include:
-
\t(Creates a tab) -
\n(Creates a newline)
Both can be useful in plots to more neatly arrange text.
[1] β Record temp:{\t}102
[1] β Record temp:
β 102
Can we get str_view() to show the tab instead of {\t}? We can use the html argument to have the string displayed as if on a webpage:
Often we will want to create new strings within data frames. We can use str_c() or str_glue(), both of which are vectorized functions (meaning they take vectors as inputs and provide vectors as outputs - can be used within mutate()):
- With
str_c()the strings to be combined are all separate arguments separated by commas. - With
str_glue()the desired string is written as a template with variable names inside curly braces{}.
Code
# A tibble: 4 Γ 2
first_name last_name
<chr> <chr>
1 Arya Stark
2 Olenna Tyrell
3 Tyrion Lannister
4 Melisandre <NA>
Code
# A tibble: 4 Γ 4
first_name last_name full_name1 full_name2
<chr> <chr> <chr> <glue>
1 Arya Stark Arya Stark Arya Stark
2 Olenna Tyrell Olenna Tyrell Olenna Tyrell
3 Tyrion Lannister Tyrion Lannister Tyrion Lannister
4 Melisandre <NA> <NA> Melisandre NA
Exercise: In the following data frame, create a full date string in month-day-year format using both str_c() and str_glue().
Code
# A tibble: 3 Γ 6
year month day month_num full_date1 full_date2
<dbl> <chr> <dbl> <int> <chr> <glue>
1 2000 Jan 3 1 1-3-2000 1-3-2000
2 2001 Feb 4 2 2-4-2001 2-4-2001
3 2002 Mar 5 3 3-5-2002 3-5-2002
Extracting information from strings
The str_length() counts the number of characters in a string.
Code
# A tibble: 2 Γ 3
name comment comment_length
<chr> <chr> <int>
1 Alice The essay was well organized around the core message and⦠78
2 Bob Good job! 9
The str_sub() function gets a substring of a string. The 2nd and 3rd arguments indicate the beginning and ending position to extract.
- Negative positions indicate the position from the end of the word. (e.g., -3 indicates β3rd letter from the endβ)
- Specifying a position that goes beyond the word wonβt result in an error.
str_sub()will just go as far as possible.
[1] "App" "Ban" "Pea"
[1] "ple" "ana" "ear"
[1] "pple" "anana" "ear"
[1] "a"
Exercise: Using str_sub(), create a new variable with only the middle letter of each word in the data frame below. (Challenge: How would you handle words with an even number of letters?)
Finding patterns in strings with regular expressions
Suppose that youβre exploring text data looking for places where people describe happiness. There are many ways to search. We could search for the word βhappyβ but that excludes βhappinessβ so we might search for βhappiβ.
Regular expressions (regex) are a powerful language for describing patterns within strings.
. . .
We can use str_view() with the pattern argument to see what parts of a string match the regex supplied in the pattern argument. (Matches are enclosed in <>.)
[6] β bil<berry>
[7] β black<berry>
[10] β blue<berry>
[11] β boysen<berry>
[19] β cloud<berry>
[21] β cran<berry>
[29] β elder<berry>
[32] β goji <berry>
[33] β goose<berry>
[38] β huckle<berry>
[50] β mul<berry>
[70] β rasp<berry>
[73] β salal <berry>
[76] β straw<berry>
Essentials of forming a regex
- Letters and numbers in a regex are matched exactly and are called literal characters.
- Most punctuation characters, like
.,+,*,[,], and?, have special meanings and are called metacharacters. -
Quantifiers come after a regex and control how many times a pattern can match:
-
?: match the preceding pattern 0 or 1 times -
+: match the preceding pattern at least once -
*: match the preceding pattern at least 0 times (any number of times)
-
. . .
Exercise: Before running the code below, predict what matches will be made. Run the code to check your guesses. Note that in all regexβs below the ?, +, * applies to the b only (not the a).
- We can match any of a set of characters with
[](called a character class), e.g.,[abcd]matches βaβ, βbβ, βcβ, or βdβ.- We can invert the match by starting with
^:[^abcd]matches anything except βaβ, βbβ, βcβ, or βdβ.
- We can invert the match by starting with
[284] β <exa>ct
[285] β <exa>mple
[288] β <exe>rcise
[289] β <exi>st
[836] β <sys>tem
[901] β <typ>e
Exercise Using the words data, find words that have two vowels in a row followed by an βmβ.
[154] β cl<aim>
[714] β r<oom>
[735] β s<eem>
[844] β t<eam>
- The alternation operator
|can be read just like the logical operator|(βORβ) to pick between one or more alternative patterns. e.g.,apple|bananasearches for βappleβ or βbananaβ.
[1] β <apple>
[13] β canary <melon>
[20] β coco<nut>
[52] β <nut>
[62] β pine<apple>
[72] β rock <melon>
[80] β water<melon>
Exercise: Using the fruit data, find fruits that have a repeated vowel (βaaβ, βeeβ, βiiβ, βooβ, or βuuβ.)
[9] β bl<oo>d orange
[33] β g<oo>seberry
[47] β lych<ee>
[66] β purple mangost<ee>n
- The
^operator indicates the beginning of a string, and the$operator indicates the end of a string. e.g.,^amatches strings that start with βaβ, anda$matches words that end with βaβ. - Parentheses group together parts of a regular expression that should be taken as a bundle. (Much like parentheses in arithmetic statements.)
- e.g.,
ab+is a little confusing. Does it match βabβ one or more times? Or does it match βaβ first, then just βbβ one or more times? (The latter, as we saw in an earlier example.) We can be very explicit and usea(b)+.
- e.g.,
Exercise: Using the words data, find (1) words that start with βyβ and (2) words that donβt start with βyβ.
[975] β <y>ear
[976] β <y>es
[977] β <y>esterday
[978] β <y>et
[979] β <y>ou
[980] β <y>oung
[1] β <a>
[2] β <a>ble
[3] β <a>bout
[4] β <a>bsolute
[5] β <a>ccept
[6] β <a>ccount
[7] β <a>chieve
[8] β <a>cross
[9] β <a>ct
[10] β <a>ctive
[11] β <a>ctual
[12] β <a>dd
[13] β <a>ddress
[14] β <a>dmit
[15] β <a>dvertise
[16] β <a>ffect
[17] β <a>fford
[18] β <a>fter
[19] β <a>fternoon
[20] β <a>gain
... and 954 more
Exploring stringr functions
Read in the βDear Abbyβ data underlying The Puddingβs 30 Years of American Anxieties article.
Take a couple minutes to scroll through the 30 Years of American Anxieties article to get ideas for themes that you might want to search for using regular expressions.
The following are core stringr functions that use regular expressions:
-
str_view()- View the first occurrence in a string that matches the regex -
str_count()- Count the number of times a regex matches within a string -
str_detect()- Determine if (TRUE/FALSE) the regex is found within string -
str_subset()- Return subset of strings that match the regex -
str_extract(), str_extract_all()- Return portion of each string that matches the regex.str_extract()extracts the first instance of the match.str_extract_all()extracts all matches. -
str_replace(), str_replace_all()- Replace portion of string that matches the regex with something else.str_replace()replaces the first instance of the match.str_replace_all()replaces all instances of the match. -
str_remove(), str_remove_all()- Removes the portion of the string that matches the pattern. Equivalent tostr_replace(x, "THE REGEX PATTERN", "")
Exercise: Starting from str_count(), explore each of these functions by pulling up the function documentation page and reading through the arguments. Try out each function using the posts data.
Done!
- Check the ICA Instructions for how to (a) push your code to GitHub and (b) update your portfolio website
