---
title: "ACCT 420: Textual analysis"
author: 
  - name: Dr. Richard M. Crowley
    email: rcrowley@smu.edu.sg
    affiliation: https://rmc.link/
title-slide-attributes:
  data-background-video: "../Backgrounds/title.mp4"
  data-background-video-loop: "true"
  data-background-size: stretch
format:
  revealjs:
    theme: default
    css: quarto_white.css
    navigation-mode: vertical
    controls: true
    transition: slide
    background-transition: fade
    transition-speed: default
    width: 1536
    height: 864
    logo: ../Logos/logo2.png
    code-link: true
    code-line-numbers: false
    chalkboard:
      theme: whiteboard
    auto-stretch: false
revealjs-plugins:
  - attribution
execute:
  echo: true
  warning: false
  message: false
editor: source
---

# Front Matter {data-background-video="../Backgrounds/section.mp4" data-background-video-loop="true"}

<!--# Note that the downlit and xml2 pacakges are required to compile -->
<!--# Installed extensions include `attribution`, `qrcode`, and `material-icons` -->

```{r helpers, echo=FALSE, warning=FALSE, message=F}
library(knitr)
library(kableExtra)

#' Pretty formatted HTML tables
#' 
#' @param df The dataframe to format as a table
#' @param names Names to use for columns if not using the df column names. Vector
#' @param highlight_cols Columns to highlight. Default is c(1) for highlighting the first row. Use c() to remove.
#' @param highlight_rows Rows to highlight. Default is c() to not highlight any rows.
#' @param color_rows Rows to highlight in color. Default is c() to not highlight any rows.
#' @param highlight_end_rows Rows to highlight. Uses a reverse indexing where 1 is the last row, 2 is second to last, etc.
#' @param full Use to span the full width of a slide. FALSE by default.
#' @param fixed_header Whether the first row should be treated as a header row. TRUE by default.
html_df <- function(df, names=NULL, highlight_cols=c(1), highlight_rows=c(), color_rows=c(), highlight_end_rows=c(), full=F, fixed_header=T) {
  if(!length(names)) {
    names=colnames(df)
  }
  kbl(df,"html", col.names = names, align = c("l",rep('c',length(cols)-1))) %>%
    kable_paper(c("striped","hover"), full_width=full, fixed_thead=F, html_font = "\"Source Sans Pro\", Helvetica, sans-serif") %>%
    {if(length(highlight_cols)) column_spec(., highlight_cols,bold=T, background = "#ffffff99") else .} %>%
    {if(length(highlight_rows)) row_spec(., highlight_rows,bold=T, background = "#ffffff99") else .} %>%
    {if(length(color_rows)) row_spec(., color_rows,bold=T, background = "#aaaaff99") else .} %>%
    {if(length(highlight_end_rows)) row_spec(., nrow(df) + 1 - highlight_end_rows,bold=T, background = "#ffffff99") else .}
}

library(tidyverse)
```

<!--# List packages here that are not being correctly highlighted -->
<!--# The usual cause is calling the library from a echo=FALSE cell -->

```{r}
#| include: false
options(downlit.attached = c("knitr", "kableExtra", "tidyverse"))
```

## Group projects {data-background="../Backgrounds/people.jpg" class="default present-only"}

> Decide on who you would like to work

- Take some time now to form groups and decide which projects topics you prefer

> Submit your group preferences at [https://rmc.link/420groups](https://rmc.link/420groups)

## Group projects {data-background="../Backgrounds/people.jpg" class="default present-only"}

> Pre-defined projects available

1. Fraud detection of all frauds, not just those that got AAERs
    - Panel data problem -- use 5 years of data to build a detection model and apply it to the next year
2. Predicting benign accounting errors
    - Panel data problem -- use 5 years of data to build a *binary prediction* model and apply it to the next year
3. Predicting internal control material weaknesses
    - Panel data problem -- use 5 years of data to build a *count prediction* model and apply it to
4. Forecasting of social media follower counts for S&P 1500 firms
    - *Time series* problem -- use 6 months of data to predict the amount over the next 3 months

> Or: Build your own from available data

- Annual and quarterly reports in the US, press releases, news articles
- Social media: company tweets, executive tweets, COVID tweets
- Stock and crypto prices

## Learning objectives {data-background="../Backgrounds/default.jpg"}

:::: columns

::: {.column width="50%"}

![](../Course_Diagrams/Map-7.png){fig-alt="Roadmap for the course"}

:::

::: {.column width="50%"}

- **Theory:**
    - Natural Language Processing
- **Application:**
    - Analyzing a Citigroup annual report
- **Methodology:**
    - Text analysis
    - Machine learning

:::

::::

## Datacamp {data-background="../Backgrounds/default.jpg"}

- [Sentiment analysis in R the Tidy way](https://www.datacamp.com/courses/sentiment-analysis-in-r-the-tidy-way)</a>
   - The first chapter is helpful if you find the code in this lesson to be a bit too tricky
   - You are welcome to do more, of course
- I will generally follow the same "tidy text" principles as the Datacamp course does -- the structure keeps things easy to manage
   - We will sometimes deviate to make use of certain libraries, which, while less tidy, make our work easier than the corresponding tidy-oriented packages (if they even exist!)


# Textual data and textual analysis {data-background-video="../Backgrounds/section.mp4" data-background-video-loop="true"}

## Review of Session 6 {data-background="../Backgrounds/default.jpg"}

- Last session we saw that textual measures can help improve our fraud detection algorithm
- We actually looked at a bunch of textual measures:
    - Sentiment
    - Readability
    - Topic/content
- We didn't see how to make these though...
    - Instead, we had a nice premade dataset with everything already done

> We'll get started on these today -- sentiment and readability

> We'll cover topic modeling next session

## Why is textual analysis harder? {data-background="../Backgrounds/default.jpg"}

- Thus far, everything we've worked with is what is known as *structured data*
    - Structured data is numeric, nicely indexed, and easy to use
- Text data is *unstructured*
    - If we get an annual report with 200 pages of text...
        - Where is the information we want?
        - What do we want?
        - How do we crunch 200 pages into something that is...
            1. Manageable? (Structured)
            2. Meaningful?

> This is what we will work on today, and we will revist some of this in the remaining class sessions

## Unstructured data {data-background="../Backgrounds/default.jpg"}

- Text
    - Open responses to question, reports, etc.
    - What it isn't:
        - `"JANUARY"`, `"ONE"`, `"FEMALE"`
        - Months, numbers
        - Anything with clear and concise categories
- Images, such as satellite imagery
- Audio, such as phone call recordings 
- Video, such as security camera footage

> All of these require us to determine and *impose* structure

## Some ideas of what we can do {data-background="../Backgrounds/default.jpg"}

1. Text extraction
    - Find all references to the CEO
    - Find if the company talked about global warming
    - Pull all telephone numbers or emails from a document
2. Text characteristics
    - How varied is the vocabulary?
    - Is it positive or negative (sentiment)
    - Is it written in a strong manner?
3. Text summarization or meaning
    - What is the content of the document?
    - What is the most important content of the document?
    - What other documents discuss similar issues?

## Where might we encounter text data in business {data-background="../Backgrounds/default.jpg"}

1. Business contracts
2. Legal documents
3. Any paperwork
4. News
5. Customer reviews or feedback
    - Including transcription (call centers)
6. Consumer social media posts
7. Chatbots and AI assistants

## Natural Language Processing (NLP) {data-background="../Backgrounds/default.jpg"}

- NLP is the subfield of computer science focused on analyzing large amounts of unstructured textual information
    - Much of the work builds from computer science, linguistics, and statistics
- Unstructured text actually has some structure derived from language itself
    - Word selection
    - Grammar
    - Phrases
    - Implicit orderings
- NLP utilizes this implicit structure to better understand textual data


## NLP in everyday life {data-background="../Backgrounds/default.jpg"}

- Autocomplete of the next word in phone keyboards
    - Demo below from <a href="https://www.blog.google/products/search/gboard-now-on-android/">Google's blog</a>
- Voice assistants like Google Assistant, Siri, Cortana, and Alexa
- Article suggestions on websites
- Search engine queries
- Email features like missing attachment detection

![](../Figures/gmail_demo.gif){height="350px" fig-align="center"}

## {data-background="../Figures/Gartner_AI_2023.png" data-background-size="contain" class="photo"}

## Case: How leveraging NLP helps call centers {data-background="../Backgrounds/case.jpg"}

- [Natural Language Processing in Call Centers](https://rmc.link/420class7)
- Short link: [rmc.link/420class7](https://rmc.link/420class7)

{{< qrcode https://rmc.link/420class7 class1 width=300 height=300 >}}


> What are call centers using NLP for?

> How does NLP help call centers with their business?

## Brainstorming... {data-background="../Backgrounds/rain.jpg" class="default present-only"}

<iframe allowfullscreen frameborder="0" height="600px" mozallowfullscreen src="https://app.wooclap.com/events/OYLTZU/questions/5f72e15c2f1630116bb2d6b3" width="100%"></iframe>

## Consider {data-background="../Backgrounds/group.jpg"}

> Where an we make use of NLP in business?

- We can use it for call centers
- We can make products out of it (like [Google Duplex](https://youtu.be/D5VN56jQMWM?t=68) and other tech firms)
- Where else?

## Brainstorming... {data-background="../Backgrounds/rain.jpg" class="default present-only"}

<iframe allowfullscreen frameborder="0" height="600px" mozallowfullscreen src="https://app.wooclap.com/events/OYLTZU/questions/5f72eef3489b2e495a379376" width="100%"></iframe>

# Working with 1 text file {data-background-video="../Backgrounds/section.mp4" data-background-video-loop="true"}

## Before we begin: Special characters {data-background="../Backgrounds/reference.jpg"}

- Some characters in R have special meanings for string functions
    - `\ | ( ) [ { } ^ $ * + ? . !`
- To type a special character, we need to precede it with a `\`
    - Since `\` is a special character, we'll need to put `\` before `\`...
        - To type `$`, we would use `\\$`
- Also, some spacing characters have special symbols:
    - `\t` is tab
    - `\r` is newline (files from Macs)
    - `\r\n` is newline (files from Windows)
    - `\n` is newline (files from Unix, Linux, etc.)
    - You'll need to write `\\` to get the backslashes though

## Loading in text data from files {data-background="../Backgrounds/reference.jpg"}

- Use `read_file()` from `{tidyverse}`'s `{readr}` package to read in text data
- We'll use [Microsoft's annual report from 2021](https://www.sec.gov/ix?doc=/Archives/edgar/data/789019/000156459021039151/msft-10k_20210630.htm)
    - Note that there is a full text link at the bottom which is a .txt file
    - I will instead use a cleaner version derived from the linked file
        - The cleaner version can be made using the same techniques we will discuss today

```{r}
# Read text from a .txt file using read_file()
doc <- read_file("../../Data/0001564590-21-039151.txt")
# str_wrap is from stringr from tidyverse
# The first 500 characters of the second paragraph
cat(str_wrap(substring(doc,1728,2228), 80))
```

## Loading from other file types {data-background="../Backgrounds/default.jpg"}

- Ideally you have a .txt file already -- such files are generally just the text of the documents
- Other common file types:
    - HTML files (particularly common from web data)
        - You can load it as a text file -- just note that there are html tags embedded in it
            - Things like `<a>`, `<table>`, `<img>`, etc.
        - You can load from a URL using `{httr}` or `{RCurl}`
        - In R, you can use `{XML}` or `{rvest}` to parse out specific pieces of html files
        - If you use python, use `lxml` or BeautifulSoup 4 (`bs4`) to quickly turn these into structured documents
        - In R, you can process JSON data using `{jsonlite}`

## Loading from other file types {data-background="../Backgrounds/default.jpg"}

- Ideally you have a .txt file already -- such files are generally just the text of the documents
- Other common file types:
    - PDF files
        - Use `{pdftools}` to extract text into a vector of pages of text
        - Use `{tabulizer}` to extract tables straight from PDF files!
            - This is very painful to code by hand without this package
            - The package itself is a bit difficult to install, requiring Java and `{rJava}`, though

## Example using html {data-background="../Backgrounds/default.jpg"}

```{r, message=F, warning=F}
library(httr)
library(XML)

httpResponse <- GET('https://coinmarketcap.com/currencies/ethereum/')
html = httr::content(httpResponse, "text")
paste0('...', str_wrap(substring(html, 11305, 11363), 80), '...')
xpath <- '//*[@id="section-coin-overview"]/div[2]/span/text()'
hdoc = htmlParse(html, asText=TRUE)  # from XML
price <- xpathSApply(hdoc, xpath, xmlValue)
print(paste0("Ethereum was priced at ", price,
             " when these slides were compiled"))
```

## Automating crypto pricing in a document {data-background="../Backgrounds/default.jpg"}

```{r}
# The actual version I use (with caching to avoid repeated lookups) is in the appendix
cryptoMC <- function(name) {
  httpResponse <- GET(paste('https://coinmarketcap.com/currencies/',name,'/',sep=''))
  html = httr::content(httpResponse, "text")
  xpath <- '//*[@id="section-coin-overview"]/div[2]/span/text()'
  hdoc = htmlParse(html, asText=TRUE)
  plain.text <- xpathSApply(hdoc, xpath, xmlValue)
  plain.text
}
```

```{r}
paste("Ethereum was priced at", cryptoMC("ethereum"))
paste("Litecoin was priced at", cryptoMC("litecoin"))
```

## Basic text functions in R {data-background="../Backgrounds/default.jpg"}

:::: {.columns}

::: {.column width="50%"}

- Subsetting text
- Transformation
    - Changing case
    - Adding or combining text
    - Replacing text
    - Breaking text apart
- Finding text

:::

::: {.column width="50%"}

![](../Figures/stringr.png){width="200px" fig-align="center"}

:::

::::

> We will cover these using `{stringr}` as opposed to base R -- `{stringr}`'s commands are much more consistent

- Every function in `{stringr}` can take a vector of strings for the first argument, which is *tidy*

## Subsetting text {data-background="../Backgrounds/reference.jpg"}

- Base R: Use `substr()` or `substring()`
- `{stringr}`: use `str_sub()`
    - First argument is a vector of strings
    - Second argument is the starting position (inclusive)
    - Third argument is that ending position (inclusive)

```{r}
cat(str_wrap(str_sub(doc, 138177, 138384), 80))
cat(str_wrap(str_sub(doc, 144162 , 144476), 80))
```

## Transforming text {data-background="../Backgrounds/reference.jpg"}

- Commonly used functions:
    - `tolower()` or `str_to_lower()`: make the text lowercase
    - `toupper()` or `str_to_upper()`: MAKE THE TEXT UPPERCASE
    - `str_to_title()`: Make the Text Titlecase
- `paste()` to combine text
    - It puts spaces between by default
        - You can change this with the `sep=` option
    - If everything to combine is in 1 vector, use `collapse=` with the desired separator
    - `paste0()` is paste with `sep=""`

## Examples: Case {data-background="../Backgrounds/default.jpg"}

```{r}
sentence <- str_sub(doc, 138287, 138384)
str_to_lower(sentence)
str_to_upper(sentence)
str_to_title(sentence)
```

- The `str_` prefixed functions support non-English languages as well

```{r, eval=F}
# You can run this in an R terminal! (It doesn't work in Rmarkdown though)
str_to_upper("Cloud usage and demand benefited...", locale='tr')  # Turkish
```

## Examples: `paste` {data-background="../Backgrounds/default.jpg"}

```{r, include=F}
board <- c("Reid Hoffman", "Hugh Johnston", "Teri List", "Satya Nadella", "Sandra E. Peterson", "Penny Pritzker", "Carlos Rodriguez", "Charles W. Scharf", "John W. Stanton", "John W. Thompson", "Emma Walmsley", "Padmasree Warrior")
titles <- c("Partner, Greylock Partners", "Vice Chairman and Chief Financial Officer, PepsiCo", "Former Executive Vice President and Chief Financial Officer, Gap Inc.", "Chairman and Chief Executive Officer", "Lead Independent Director", "Founder and Chairman, PSP Partners", "Executive Chair, ADP, Inc.", "CEO and President, Wells Fargo & Company", "Chairman, Trilogy Partnerships", "Partner, Lightspeed Venture Partners", "CEO, GSK", "Founder, President and CEO, Fable Group Inc.")
```
```{r}
# board is a list of director names
# titles is a list of the director's titles
paste(board, titles, sep=", ")
cat(str_wrap(paste0("Microsoft's board consists of: ",
                    paste(board[1:length(board)-1], collapse=", "),
                    ", and ", board[length(board)], "."), 80))
```

## Transforming text {data-background="../Backgrounds/reference.jpg"}

- Replace text with `str_replace_all()`
    - First argument is text data
    - Second argument is what you want to remove
    - Third argument is the replacement
- If you only want to replace the first occurrence, use `str_replace()` instead

```{r}
sentence
str_replace_all(sentence, "digital transformation", "data science")
```

## Transforming text {data-background="../Backgrounds/reference.jpg"}

- Split text using `str_split()`
    - This function returns a list of vectors!
        - This is because it will turn every string passed to it into a vector, and R can't have a vector of vectors
    - `[[1]]` can extract the first vector
- You can also limit the number of splits using `n=`
    - A bit more elegant solution is using `str_split_fixed()` with `n=`
        - Returns a character matrix (nicer than a list)

## Example: Splitting text {data-background="../Backgrounds/default.jpg"}

```{r}
paragraphs <- str_split(doc, '\n')[[1]]

# number of paragraphs
length(paragraphs)

# First paragraph of the MD&A
cat(str_wrap(paragraphs[206], 80))
```

## Finding phrases in text {data-background="../Backgrounds/default.jpg"}

- How did I find the previous examples?

```{r}
str_locate_all(str_to_lower(doc), "net income")
```

## Finding phrases in text {data-background="../Backgrounds/reference.jpg"}

- 4 primary functions:
    1. `str_detect()`: Reports `TRUE` or `FALSE` for the presence of a string in the text
    2. `str_count()`: Reports the number of times a string is in the text
    3. `str_locate()`: Reports the first location of a string in the text
        - `str_locate_all()`: Reports every location as a list of matrices
    4. `str_extract()`: Reports the matched phrases
- All take a character vector as the first argument, and something to match for the second argument

## Example: Finding phrases {data-background="../Backgrounds/default.jpg"}

- How many paragraphs mention net income in any case?

```{r}
x <- str_detect(str_to_lower(paragraphs), "revenue")
x[51:60]
sum(x)
```

- What is the most net income is mentioned in any paragraph

```{r}
x <- str_count(str_to_lower(paragraphs), "revenue")
x[51:60]
max(x)
```

## Example: Finding phrases {data-background="../Backgrounds/default.jpg"}

- Where is net income first mentioned in the document?

```{r}
str_locate(str_to_lower(doc), "revenue")
```

- First mention of net income
    - This function may look useless now, but it'll be on of the most useful later

```{r}
str_extract(str_to_lower(doc), "revenue")
```

## R Practice {data-background="../Backgrounds/coding.jpg"}

- Text data is already loaded, as if it was loaded using `read_file()`
- Try:
    - Subsetting the text data
    - Transforming the text data
        - To all upper case
        - Replacing a phrase
    - Finding specific text in the document
- Do exercises 1 through 3 in today's practice file
    - Available at: [rmc.link/420r7](https://rmc.link/420r7)

# Pattern matching {data-background-video="../Backgrounds/section.mp4" data-background-video-loop="true"}

## Finding *patterns* in the text (regex) {data-background="../Backgrounds/default.jpg"}

- Regular expressions, aka regex or regexp, are ways of finding patterns in text
- This means that instead of looking for a specific phrase, we can match a set of phrases
- Most of the functions we discussed accept regexes for matching
    - `str_replace()`, `str_split()`, `str_detect()`, `str_count()`, `str_locate()`, and `str_extract()`, plus their variants
- This is why `str_extract()` is so great -- we can extract anything from a document with it!

## Regex example {data-background="../Backgrounds/default.jpg"}

- Finding full sentences mentioning COVID

```{r}
# Extract all sentences mentioning COVID from the annual report
str_extract_all(doc, '(?<=^|\\.\\s{1,5})[^.]*?COVID[^.]*?\\.')
```

## Breaking down the example {data-background="../Backgrounds/default.jpg" .small}

> `'(?<=^|\\.\\s{1,5})[^.]*?COVID[^.]*?\\.'`

- `(?<=...)` is called a *positive look-behind assertion*
    - It succeeds whenever the '...' matches the text before what you want to find
    - `^` is the start of the string
    - `\\.\\s{1,5}` is a period followed by some whitespace characters (up to 5)
        - A quirk of look-behinds is you need to specify a maxmimum length for everything
    - `|` is an *or*
    - Taken together: the look-behind matches if there is a new paragraph or a period followed by whitespace
- `[^.]*?`
    - `[^.]` is anything except a period
    - `*` means 0 or more of the preceeding pattern
    - `?` means keep it as short as possible
- `COVID` is the literal text
- `\\.` is a period

## Breaking down the example {data-background="../Backgrounds/default.jpg"}

- Let's examine the output: `In fiscal year 2021, the COVID-19 pandemic continued to impact our business operations and financial results.`
- Our regex was `(?<=^|\\.\\s{1,5})[^.]*?COVID[^.]*?\\.`
- Matching regex components to output:
    - `(?<=^|\\.\\s{1,5})` $\Rightarrow$ start of the paragraph (via `^`)
    - `[^.]*?` $\Rightarrow$ `In fiscal year 2021, the `
    - `COVID` $\Rightarrow$ `COVID`
    - `[^.]*?` $\Rightarrow$ `-19 pandemic continued to impact our business operations and financial results`
    - `\\.` $\Rightarrow$ `.`

## Useful regex components: Content {data-background="../Backgrounds/reference.jpg"}

- There's a <a href="https://github.com/rstudio/cheatsheets/raw/master/strings.pdf">nice cheat sheet here</a>
    - <a href="https://cran.r-project.org/web/packages/stringr/vignettes/regular-expressions.html">More detailed documentation here</a>
- Matching collections of characters
    - `.` matches everything
    - `[:alpha:]` matches all letters
    - `[:lower:]` matches all lowercase letters
    - `[:upper:]` matches all UPPERCASE letters
    - `[:digit:]` matches all numbers 0 through 9
    - `[:alnum:]` matches all letters and numbers
    - `[:punct:]` matches all punctuation
    - `[:graph:]` matches all letters, numbers, and punctuation
    - `[:space:]` or `\s` match ANY whitespace
        - `\S` is the exact opposite
    - `[:blank:]` matches whitespace except newlines

## Example: Regex content {data-background="../Backgrounds/default.jpg"}

```{r}
text <- c("abcde", 'ABCDE', '12345', '!?!?.', 'ABC123?', "With space", "New\nline")
html_df(data.frame(
  text=text,
  alpha=str_detect(text,'[:alpha:]'),
  lower=str_detect(text,'[:lower:]'),
  upper=str_detect(text,'[:upper:]'),
  digit=str_detect(text,'[:digit:]'),
  alnum=str_detect(text,'[:alnum:]')))

```

## Example: Regex content {data-background="../Backgrounds/default.jpg"}

```{r}
text <- c("abcde", 'ABCDE', '12345', '!?!?.', 'ABC123?', "With space", "New\nline")
html_df(data.frame(
  text=text,
  punct=str_detect(text,'[:punct:]'),
  graph=str_detect(text,'[:graph:]'),
  space=str_detect(text,'[:space:]'),
  blank=str_detect(text,'[:blank:]'),
  period=str_detect(text,'.')))
```

## Useful regex components: Form {data-background="../Backgrounds/reference.jpg"}

- `[ ]` can be used to create a class of characters to look for
    - `[abc]` matches anything that is `a`, `b`, `c`
- `[^ ]` can be used to create a class of everything else
    - `[^abc]` matches anything that isn't `a`, `b`, or `c`
- Quantity, where `x` is some element
    - `x?` looks for 0 or 1 of `x`
    - `x*` looks for 0 or more of `x`
    - `x+` looks for 1 or more of `x`
    - `x{n}` looks for `n` (a number) of `x`
    - `x{n, }` looks for at least `n` of `x`
    - `x{n,m}` looks for at least `n` and at most `m` of `x`
- Lazy operators
    - Regexes always prefer the longest match by default
    - Append `?` to any quantity operator to make it prefer the shortest match possible

## Useful regex components: Form {data-background="../Backgrounds/reference.jpg"}

- Position
    - `^` indicates the start of the string
    - `$` indicates the end of the string
- Grouping
    - `( )` can be used to group components
    - `|` can be used within groups as a logical *or*
    - Groups can be referenced later using the position of the group within the regex
        - `\\1` refers to the first group
        - `\\2` refers to the second group
        - ...

## Example: Regexes on real estate firm names {data-background="../Backgrounds/default.jpg"}

```{r, include=FALSE}
df_RE <- read.csv("../../Data/Session_2-1.csv")
RE_names <- unique(df_RE$conm)
```

```{r}
# Real estate firm names with 3 vowels in a row
str_subset(RE_names, '[AEIOU]{3}')
# Real estate firm names with no vowels
str_subset(RE_names, '^[^AEIOU]+$')
# Real estate firm names with at least 12 vowels
str_subset(RE_names, '([^AEIOU]*[AEIOU]){11,}')
# Real estate firm names with a repeated 4 letter pattern
str_subset(RE_names, '([:upper:]{4}).*\\1')
```

## Why is regex so important? {data-background="../Backgrounds/default.jpg"}

- Regex can be used to match anything in text
    - Simple things like phone numbers
    - More complex things like addresses
- It can be used to parse through large markup documents
    - HTML, XML, LaTeX, etc.
- Very good for validating the format of text
    - For birthday in the format YYYYMMDD, you could validate with:
        - YYYY: `[12][90][:digit:][:digit:]`
        - MM: `[01][:digit:]`
        - DD: `[0123][:digit:]`

> Cavaet: Regexes are generally slow.  If you can code something to avoid them, that is often better.  But often that may be infeasible.

## Some extras {data-background="../Backgrounds/default.jpg"}

- While the `str_*()` functions use regex by default, they actually have four modes
    1. You can specify a regex normally
        - Or you can use `regex()` to construct more customized ones, such as regexes that operate by line in a string
    2. You can specify an exact string to match using `fixed()` -- fast but fragile
    3. You can specify an exact string to match using `coll()` -- slow but robust; recognizes characters that are equivalent
        - Important when dealing with non-English words, since certain characters can be encoded in multiple ways
    4. You can ask for boundaries with `boundary()` such as words, using `boundary("word")`


## Expanding usage {data-background="../Backgrounds/default.jpg"}

- Anything covered so far can be used for text in data
    - Ex.: Firm names or addresses in Compustat

```{r}
# Compustat firm names example
df_RE_names <- df_RE %>%
  group_by(isin) %>%
  slice(1) %>%
  mutate(SG_in_name = str_detect(conm, "(SG|SINGAPORE)"),
         name_length = str_length(conm),
         SG_firm = ifelse(fic=="SGP",1,0)) %>%
  ungroup()

df_RE_names %>%
  group_by(SG_firm) %>%
  mutate(pct_SG = mean(SG_in_name) * 100) %>%
  slice(1) %>%
  ungroup() %>%
  select(SG_firm, pct_SG)
```

## Expanding usage {data-background="../Backgrounds/default.jpg" .small}

```{r, warning=F}
library(DT)
df_RE_names %>%
  group_by(fic) %>%
  mutate(avg_name_length = mean(name_length)) %>%
  slice(1) %>%
  ungroup() %>%
  select(fic, avg_name_length) %>%
  arrange(desc(avg_name_length), fic) %>%
  datatable(options = list(pageLength = 5))
```

## R Practice 2 {data-background="../Backgrounds/coding.jpg"}

- This practice explores the previously used practice data using regular expressions for various purposes
- Do exercises 4 and 5 in today's practice file
    - Available at: [rmc.link/420r7](https://rmc.link/420r7)

# Readability and Sentiment {data-background-video="../Backgrounds/section.mp4" data-background-video-loop="true"}

## Readability {data-background="../Backgrounds/default.jpg"}

- Thanks to the `{quanteda}` package, readability is very easy to calculate in R
    - Use the `textstat_readability()` function
- There are many readability measures, however
    - Flesch Kinkaid grade level: A measure of readability developed for the U.S. Navy to ensure manuals were written at a level any 15 year old should be able to understand
    - Fog: A grade level index that was commonly used in business and publishing
    - Coleman-Liau: An index with a unique calculation method, relying only on character counts

## Readability: Flesch Kincaid {data-background="../Backgrounds/default.jpg"}

$$
0.39 \left(\frac{\#~words}{\#~sentences}\right) + 11.8\left(\frac{\#~syllables}{\#~words}\right) - 15.59
$$

- An approximate grade level required for reading a document
    - *Lower is more readable*
    - A JC or poly graduate should read at a level of 12
        - New York Times articles are usually around 13
    - A Bachelor's degree could be necessary for anything 16 or above

```{r, message=F}
library(quanteda)
library(quanteda.textstats)
textstat_readability(doc, "Flesch.Kincaid")
```

## Readability: Fog {data-background="../Backgrounds/default.jpg"}

$$
\begin{aligned}
  & \left[ Mean(Words~per~sentence) +\right.\\
  &\left.(\%~of~words~>3~syllables)\right] \times 0.4
\end{aligned}
$$

- An approximate grade level required for reading a document
    - *Lower is more readable*

```{r}
textstat_readability(doc, "FOG")
```

## Readability: Coleman-Liau {data-background="../Backgrounds/default.jpg"}

$$
5.88\left(\frac{\#~letters}{\#~words}\right)-29.6\left(\frac{\#~sentences}{\#~words}\right)-15.8
$$

- An approximate grade level required for reading a document
    - *Lower is more readable*

```{r}
textstat_readability(doc, "Coleman.Liau.short")
```


## Converting text to words {data-background="../Backgrounds/default.jpg"}

- Tidy text is when you have one *token* per document per row, in a data frame
- *Token* is the unit of text you are interested in
    - Words: "New"
    - Phrases: "New York Times"
    - Sentences: "The New York Times is a publication."
    - etc.
- The `{tidytext}` package can handle this conversion for us!
    - Use the `unnest_tokens()` function
    - Note: it also converts to lowercase.  Use the option `to_lower=FALSE` to avoid this if needed

```{r, eval=T, warning=F}
# Example of "tokenizing"
library(tidytext)
df_doc <- data.frame(ID=c("0001564590-21-039151"), text=c(doc)) %>%
  unnest_tokens(word, text)
# word is the name for the new column
# text is the name of the string column in the input data
```

## The details {data-background="../Backgrounds/default.jpg"}

```{r}
html_df(head(df_doc))
```

## The details {data-background="../Backgrounds/default.jpg"}

- `{tidytext}` uses the `{tokenizers}` package in the backend to do the conversion
    - You can call that package directly instead if you want to
- Available tokenizers include: (specify with `token=`)
    - "word": The default, individual words
    - "ngram": Collections of words (default of 2, specify with `n=`)
    - A few other less commonly used tokenizers

## Word case {data-background="../Backgrounds/spooky.jpg"}

- Why convert to lowercase?
- How much of a difference is there between "The" and "the"?
    - "Singapore" and "singapore" -- still not much difference
    - Only words like "new" versus "New" matter
        - "New York" versus "new yorkshire terrier"
- Benefit: We get rid of a bunch of distinct words!
    - Helps with *the curse of dimensionality*

## The Curse of dimensionality {data-background="../Backgrounds/spooky.jpg"}

- There are a lot of words
- A LOT OF WORDS
- At least 171,476 according to <a href="https://en.oxforddictionaries.com/explore/how-many-words-are-there-in-the-english-language/">Oxford Dictionary</a>
- What happens if we make a matrix of words per document?

<div class="fragment exclude">
For right now, not much
</div>

<div class="fragment exclude">
- If we have every publicly available government filed press release in the US?
    - 1,479,068 files through July 2018...
        - ~2TB if we include all English words
        - ~45GB if we restrict just to the 3,752 words in the Microsoft annual report...
</div>


## Stopwords {data-background="../Backgrounds/default.jpg"}

- Stopwords -- words we remove because they have little content
    - the, a, an, and, ...
- Also helps with our curse a bit -- removes the words entirely
- We'll use the `stopword` package to remove stopwords

```{r, warning=F}
# get a list of stopwords
stop_en <- stopwords::stopwords("english")  # Snowball English
paste0(length(stop_en), " words: ", paste(stop_en[1:5], collapse=", "))
stop_SMART <- stopwords::stopwords(source="smart")  # SMART English
paste0(length(stop_SMART), " words: ", paste(stop_SMART[1:5], collapse=", "))
stop_fr <- stopwords::stopwords("french")  # Snowball French
paste0(length(stop_fr), " words: ", paste(stop_fr[1:5], collapse=", "))
```

## Applying stopwords to a corpus {data-background="../Backgrounds/default.jpg"}

- When we have a tidy set of text, we can just use `{dplyr}` for this!
    - `{dplyr}`'s `anti_join()` function is like a merge, but where all matches are deleted
    

```{r}
df_doc_stop <- df_doc %>%
  anti_join(data.frame(word=stop_SMART))
nrow(df_doc)
nrow(df_doc_stop)
```

## Converting to term frequency {data-background="../Backgrounds/default.jpg"}

```{r, warning=F, message=F}
terms <- df_doc_stop %>%
  count(ID, word, sort=TRUE) %>%
  ungroup()
total_terms <- terms %>% 
  group_by(ID) %>% 
  summarize(total = sum(n))
tf <- left_join(terms, total_terms) %>% mutate(tf=n/total)
tf
```

```{r, echo=F, warning=F, error=F, message=F}
terms_ns <- df_doc %>%
  count(ID, word, sort=TRUE) %>%
  ungroup()
total_terms_ns <- terms_ns %>% 
  group_by(ID) %>% 
  summarize(total = sum(n))
tf_no_stop <- left_join(terms_ns, total_terms_ns) %>% mutate(tf=n/total)
```

## Sentiment {data-background="../Backgrounds/default.jpg"}

- Sentiment works similarly to stopwords, except we are identifying words with specific, useful meanings
    - We can grab off-the-shelf measures using `get_sentiments()` from `{tidytext}`

:::: {.columns}

::: {.column width="50%"}

```{r}
# Need to install the `textdata` package for the below to work
get_sentiments("afinn") %>%
  group_by(value) %>%
  slice(1) %>%
  ungroup()
```

:::

::: {.column width="50%"}

```{r}
get_sentiments("bing") %>%
  group_by(sentiment) %>%
  slice(1) %>%
  ungroup()
```

:::

::::


## Sentiment {data-background="../Backgrounds/default.jpg"}

:::: {.columns}

::: {.column width="50%"}

NRC Word-Emotion

```{r}
get_sentiments("nrc") %>%
  group_by(sentiment) %>%
  slice(1) %>%
  ungroup()
```

:::

::: {.column width="50%"}

Loughran & McDonald dictionary -- finance specific, targeted at annual reports
```{r}
get_sentiments("loughran") %>%
  group_by(sentiment) %>%
  slice(1) %>%
  ungroup()
```

:::

::::

## Merging in sentiment data {data-background="../Backgrounds/default.jpg"}

```{r}
tf_sent <- tf %>% left_join(get_sentiments("loughran"))
tf_sent[1:5,]
tf_sent[!is.na(tf_sent$sentiment),][1:5,]
```

## Summarizing document sentiment {data-background="../Backgrounds/default.jpg"}

```{r}
tf_sent %>%
  spread(sentiment, tf, fill=0) %>%
  select(constraining, litigious, negative, positive, superfluous, uncertainty) %>%
  colSums()
```

## Visualizing sentiment {data-background="../Backgrounds/default.jpg"}

```{r, warning=F, message=F, echo=T}
tf_sent %>% filter(!is.na(sentiment)) %>%
  group_by(sentiment) %>%
  arrange(desc(n)) %>% mutate(row = row_number()) %>% filter(row < 10) %>%
  ungroup() %>% mutate(word = reorder(word, n)) %>%
  ggplot(aes(y=n, x=word)) + geom_col() + theme(axis.text.x = element_text(angle=90, hjust=1)) + 
  facet_wrap(~sentiment, ncol=3, scales="free_x")
```


## Visualizing a document as a word cloud {data-background="../Backgrounds/default.jpg"}

- `{quanteda}` provides `textplot_wordcloud()`
- `cast_dfm()` converts tidy term frequencies to Quanteda

```{r, message=F, warning=F, fig.height=4.5}
library(quanteda.textplots)
corp <- cast_dfm(tf, ID, word, n)
textplot_wordcloud(dfm(corp), color = RColorBrewer::brewer.pal(9, "Set1"))
```

## Another reason to use stopwords {data-background="../Backgrounds/default.jpg"}

- Without removing stopwords, the word cloud shows almost nothing useful

```{r, message=F, warning=F, fig.height=4.5}
corp_no_stop <- cast_dfm(tf_no_stop, ID, word, n)
textplot_wordcloud(dfm(corp_no_stop), color = RColorBrewer::brewer.pal(9, "Set1"))
```

- You can also check out the `{wordcloud}` and `{wordcloud2}` packages

## R Practice 3 {data-background="../Backgrounds/coding.jpg"}

- Using the same data as before, we will explore
    - Readability
    - Sentiment
    - Word clouds
- Note: Due to missing packages, you will need to run the code in RStudio, not in the DataCamp light console
- Do exercises 6 through 8 in today's practice file
    - Available at: [rmc.link/420r7](https://rmc.link/420r7)

## What's next {data-background="../Backgrounds/default.jpg" class="default exclude"}

- Armed with an understanding of how to process unstructured data, all of the sudden the amount of data available to us is expanding rapidly
- To an extent, anything in the world can be viewed as data, which can get overwhelming pretty fast
- We'll require some better and newer tools to deal with this
- Revisiting last session...
    - Last session we used *topics* in our analysis
    - Topics were derived from the 10-Ks we have been working with


# End Matter {data-background-video="../Backgrounds/section.mp4"}

## Wrap up {data-background="../Backgrounds/ending.jpg"}

- For next session (in 2 weeks):
    - Finish the third assignment
        - Submit on eLearn
    - Datacamp
        - Check out the recommended chapter on text analysis
    - Start on the group project

- Survey on the class session at this QR code:

{{< qrcode https://rmc.link/420survey7 qrsurvey width=200 height=200 >}}

## Packages used for these slides {data-background="../Backgrounds/code.jpg" visibility="uncounted"}


- `{DT}`
- `{downlit}`
- `{httr}`
- `{kableExtra}`
- `{knitr}`
- `{plotly}`
- `{quanteda}`
- `{quarto}`
- `{RColorBrewer}`
- `{readtext}`
- `{revealjs}`
- `{tidytext}`
- `{tidyverse}`, including `{stringr}`
- `{XML}`

## Custom code {data-background="../Backgrounds/code.jpg" class="small" visibility="uncounted" .small}

```{r,eval=F}
library(knitr)
library(kableExtra)
html_df <- function(text, cols=NULL, col1=FALSE, full=F) {
  if(!length(cols)) {
    cols=colnames(text)
  }
  if(!col1) {
    kable(text,"html", col.names = cols, align = c("l",rep('c',length(cols)-1))) %>%
      kable_styling(bootstrap_options = c("striped","hover"), full_width=full)
  } else {
    kable(text,"html", col.names = cols, align = c("l",rep('c',length(cols)-1))) %>%
      kable_styling(bootstrap_options = c("striped","hover"), full_width=full) %>%
      column_spec(1,bold=T)
  }
}
```

## NOTES {class="never"}

- Update Gartner AI diagram (perpetual)
- Run all `get_sentiments()` code interactively first to accept licenses and install data (perpetual)
- Pretty long; data processing to percentage and the curse of dimensionality stuff could be tighter/more time efficient.
- Add in an example of CSR discussion?
