Assignment 10A

Author

Daanish Rasheed

Sentiment Analysis

Approach

The project replicates and builds on the sentiment analysis example from Chapter 2 of Text Mining with R: A Tidy Approach by Julia Silge and David Robinson. The chapter uses text scoring by looking up each word in a sentiment dictionary and summing the results. It exemplifies this by scoring the novels of Jane Austen using the AFINN, Bing, and NRC dictionaries.

In the first part of the project, I will replicate the code from the book in a Quarto document, referencing the book and the source. This includes loading the dictionaries, tidying the novels into one-word-per-row format, scoring sentiment throughout each novel in 80-line chunks, comparing all three dictionaries for Pride and Prejudice, identifying the most positive and negative words, creating word clouds, and the most negative chapters in each novel.

Secondly, I will replace the current corpus with US State of the Union addresses, from the sotu package, as well as add the Syuzhet lexicon, from the syuzhet package, making a total of four lexicons. Because speeches do not have chapters or lines, I will score by year rather than by 80-line intervals, normalized for 1,000 words to control for variations in speech length. I will perform comparisons between the four lexicons using trajectories, correlation, lexicon coverage, and the most impactful words, and interpret the results in the context of the Austen example, including the impact of the new domain and scoring one word at a time

Code Base

Reproducing Chapter 2 Example

library(tidytext)
Warning: package 'tidytext' was built under R version 4.6.1
library(janeaustenr)
Warning: package 'janeaustenr' was built under R version 4.6.1
library(dplyr)

Attaching package: 'dplyr'
The following objects are masked from 'package:stats':

    filter, lag
The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union
library(stringr)
library(tidyr)
library(ggplot2)
library(wordcloud)
Warning: package 'wordcloud' was built under R version 4.6.1
Loading required package: RColorBrewer
library(reshape2)
Warning: package 'reshape2' was built under R version 4.6.1

Attaching package: 'reshape2'
The following object is masked from 'package:tidyr':

    smiths
library(purrr)
get_sentiments("afinn")
# A tibble: 2,477 × 2
   word       value
   <chr>      <dbl>
 1 abandon       -2
 2 abandoned     -2
 3 abandons      -2
 4 abducted      -2
 5 abduction     -2
 6 abductions    -2
 7 abhor         -3
 8 abhorred      -3
 9 abhorrent     -3
10 abhors        -3
# ℹ 2,467 more rows
get_sentiments("bing")
# A tibble: 6,786 × 2
   word        sentiment
   <chr>       <chr>    
 1 2-faces     negative 
 2 abnormal    negative 
 3 abolish     negative 
 4 abominable  negative 
 5 abominably  negative 
 6 abominate   negative 
 7 abomination negative 
 8 abort       negative 
 9 aborted     negative 
10 aborts      negative 
# ℹ 6,776 more rows
get_sentiments("nrc")
# A tibble: 13,872 × 2
   word        sentiment
   <chr>       <chr>    
 1 abacus      trust    
 2 abandon     fear     
 3 abandon     negative 
 4 abandon     sadness  
 5 abandoned   anger    
 6 abandoned   fear     
 7 abandoned   negative 
 8 abandoned   sadness  
 9 abandonment anger    
10 abandonment fear     
# ℹ 13,862 more rows
tidy_books <- austen_books() %>%
  group_by(book) %>%
  mutate(
    linenumber = row_number(),
    chapter = cumsum(str_detect(text,
                                regex("^chapter [\\divxlc]",
                                      ignore_case = TRUE)))) %>%
  ungroup() %>%
  unnest_tokens(word, text)
nrc_joy <- get_sentiments("nrc") %>%
  filter(sentiment == "joy")

tidy_books %>%
  filter(book == "Emma") %>%
  inner_join(nrc_joy) %>%
  count(word, sort = TRUE)
Joining with `by = join_by(word)`
# A tibble: 301 × 2
   word          n
   <chr>     <int>
 1 good        359
 2 friend      166
 3 hope        143
 4 happy       125
 5 love        117
 6 deal         92
 7 found        92
 8 present      89
 9 kind         82
10 happiness    76
# ℹ 291 more rows
jane_austen_sentiment <- tidy_books %>%
  inner_join(get_sentiments("bing")) %>%
  count(book, index = linenumber %/% 80, sentiment) %>%
  pivot_wider(names_from = sentiment, values_from = n, values_fill = 0) %>%
  mutate(sentiment = positive - negative)
Joining with `by = join_by(word)`
Warning in inner_join(., get_sentiments("bing")): Detected an unexpected many-to-many relationship between `x` and `y`.
ℹ Row 435434 of `x` matches multiple rows in `y`.
ℹ Row 5051 of `y` matches multiple rows in `x`.
ℹ If a many-to-many relationship is expected, set `relationship =
  "many-to-many"` to silence this warning.
ggplot(jane_austen_sentiment, aes(index, sentiment, fill = book)) +
  geom_col(show.legend = FALSE) +
  facet_wrap(~book, ncol = 2, scales = "free_x")

pride_prejudice <- tidy_books %>% 
  filter(book == "Pride & Prejudice")

pride_prejudice
# A tibble: 122,204 × 4
   book              linenumber chapter word     
   <fct>                  <int>   <int> <chr>    
 1 Pride & Prejudice          1       0 pride    
 2 Pride & Prejudice          1       0 and      
 3 Pride & Prejudice          1       0 prejudice
 4 Pride & Prejudice          3       0 by       
 5 Pride & Prejudice          3       0 jane     
 6 Pride & Prejudice          3       0 austen   
 7 Pride & Prejudice          7       1 chapter  
 8 Pride & Prejudice          7       1 1        
 9 Pride & Prejudice         10       1 it       
10 Pride & Prejudice         10       1 is       
# ℹ 122,194 more rows
afinn <- pride_prejudice %>% 
  inner_join(get_sentiments("afinn")) %>% 
  group_by(index = linenumber %/% 80) %>% 
  summarise(sentiment = sum(value)) %>% 
  mutate(method = "AFINN")
Joining with `by = join_by(word)`
bing_and_nrc <- bind_rows(
  pride_prejudice %>% 
    inner_join(get_sentiments("bing")) %>%
    mutate(method = "Bing et al."),
  pride_prejudice %>% 
    inner_join(get_sentiments("nrc") %>% 
                 filter(sentiment %in% c("positive", 
                                         "negative"))
    ) %>%
    mutate(method = "NRC")) %>%
  count(method, index = linenumber %/% 80, sentiment) %>%
  pivot_wider(names_from = sentiment,
              values_from = n,
              values_fill = 0) %>% 
  mutate(sentiment = positive - negative)
Joining with `by = join_by(word)`
Joining with `by = join_by(word)`
Warning in inner_join(., get_sentiments("nrc") %>% filter(sentiment %in% : Detected an unexpected many-to-many relationship between `x` and `y`.
ℹ Row 215 of `x` matches multiple rows in `y`.
ℹ Row 5178 of `y` matches multiple rows in `x`.
ℹ If a many-to-many relationship is expected, set `relationship =
  "many-to-many"` to silence this warning.
bind_rows(afinn, 
          bing_and_nrc) %>%
  ggplot(aes(index, sentiment, fill = method)) +
  geom_col(show.legend = FALSE) +
  facet_wrap(~method, ncol = 1, scales = "free_y")

get_sentiments("nrc") %>% 
  filter(sentiment %in% c("positive", "negative")) %>% 
  count(sentiment)
# A tibble: 2 × 2
  sentiment     n
  <chr>     <int>
1 negative   3316
2 positive   2308
get_sentiments("bing") %>%
  count(sentiment)
# A tibble: 2 × 2
  sentiment     n
  <chr>     <int>
1 negative   4781
2 positive   2005
bing_word_counts <- tidy_books %>%
  inner_join(get_sentiments("bing")) %>%
  count(word, sentiment, sort = TRUE) %>%
  ungroup()
Joining with `by = join_by(word)`
Warning in inner_join(., get_sentiments("bing")): Detected an unexpected many-to-many relationship between `x` and `y`.
ℹ Row 435434 of `x` matches multiple rows in `y`.
ℹ Row 5051 of `y` matches multiple rows in `x`.
ℹ If a many-to-many relationship is expected, set `relationship =
  "many-to-many"` to silence this warning.
bing_word_counts
# A tibble: 2,585 × 3
   word     sentiment     n
   <chr>    <chr>     <int>
 1 miss     negative   1855
 2 well     positive   1523
 3 good     positive   1380
 4 great    positive    981
 5 like     positive    725
 6 better   positive    639
 7 enough   positive    613
 8 happy    positive    534
 9 love     positive    495
10 pleasure positive    462
# ℹ 2,575 more rows
bing_word_counts %>%
  group_by(sentiment) %>%
  slice_max(n, n = 10) %>% 
  ungroup() %>%
  mutate(word = reorder(word, n)) %>%
  ggplot(aes(n, word, fill = sentiment)) +
  geom_col(show.legend = FALSE) +
  facet_wrap(~sentiment, scales = "free_y") +
  labs(x = "Contribution to sentiment",
       y = NULL)

custom_stop_words <- bind_rows(tibble(word = c("miss"),  
                                      lexicon = c("custom")), 
                               stop_words)

custom_stop_words
# A tibble: 1,150 × 2
   word        lexicon
   <chr>       <chr>  
 1 miss        custom 
 2 a           SMART  
 3 a's         SMART  
 4 able        SMART  
 5 about       SMART  
 6 above       SMART  
 7 according   SMART  
 8 accordingly SMART  
 9 across      SMART  
10 actually    SMART  
# ℹ 1,140 more rows
tidy_books %>%
  anti_join(stop_words) %>%
  count(word) %>%
  with(wordcloud(word, n, max.words = 100))
Joining with `by = join_by(word)`

tidy_books %>%
  inner_join(get_sentiments("bing")) %>%
  count(word, sentiment, sort = TRUE) %>%
  acast(word ~ sentiment, value.var = "n", fill = 0) %>%
  comparison.cloud(colors = c("gray20", "gray80"),
                   max.words = 100)
Joining with `by = join_by(word)`
Warning in inner_join(., get_sentiments("bing")): Detected an unexpected many-to-many relationship between `x` and `y`.
ℹ Row 435434 of `x` matches multiple rows in `y`.
ℹ Row 5051 of `y` matches multiple rows in `x`.
ℹ If a many-to-many relationship is expected, set `relationship =
  "many-to-many"` to silence this warning.

p_and_p_sentences <- tibble(text = prideprejudice) %>% 
  unnest_tokens(sentence, text, token = "sentences")

p_and_p_sentences$sentence[2]
[1] "by jane austen"
austen_chapters <- austen_books() %>%
  group_by(book) %>%
  unnest_tokens(chapter, text, token = "regex", 
                pattern = "Chapter|CHAPTER [\\dIVXLC]") %>%
  ungroup()

austen_chapters %>% 
  group_by(book) %>% 
  summarise(chapters = n())
# A tibble: 6 × 2
  book                chapters
  <fct>                  <int>
1 Sense & Sensibility       51
2 Pride & Prejudice         62
3 Mansfield Park            49
4 Emma                      56
5 Northanger Abbey          32
6 Persuasion                25
bingnegative <- get_sentiments("bing") %>% 
  filter(sentiment == "negative")

wordcounts <- tidy_books %>%
  group_by(book, chapter) %>%
  summarize(words = n())
`summarise()` has regrouped the output.
ℹ Summaries were computed grouped by book and chapter.
ℹ Output is grouped by book.
ℹ Use `summarise(.groups = "drop_last")` to silence this message.
ℹ Use `summarise(.by = c(book, chapter))` for per-operation grouping
  (`?dplyr::dplyr_by`) instead.
tidy_books %>%
  semi_join(bingnegative) %>%
  group_by(book, chapter) %>%
  summarize(negativewords = n()) %>%
  left_join(wordcounts, by = c("book", "chapter")) %>%
  mutate(ratio = negativewords/words) %>%
  filter(chapter != 0) %>%
  slice_max(ratio, n = 1) %>% 
  ungroup()
Joining with `by = join_by(word)`
`summarise()` has regrouped the output.
# A tibble: 6 × 5
  book                chapter negativewords words  ratio
  <fct>                 <int>         <int> <int>  <dbl>
1 Sense & Sensibility      43           161  3405 0.0473
2 Pride & Prejudice        34           111  2104 0.0528
3 Mansfield Park           46           173  3685 0.0469
4 Emma                     15           151  3340 0.0452
5 Northanger Abbey         21           149  2982 0.0500
6 Persuasion                4            62  1807 0.0343

Extending Analysis

The sotu package contains the text of the U.S. President’s State of the Union address along with metadata, with sotu_meta containing president, year, party and type of speech. The text spans over two centuries. There is no text to break into chapters/lines so the unit of text will be per year.

library(sotu)
Warning: package 'sotu' was built under R version 4.6.1
sotu_df <- sotu_meta %>%
  mutate(text = sotu_text) %>%
  select(president, year, party, text)

sotu_tidy <- sotu_df %>%
  unnest_tokens(word, text)

total_words <- sotu_tidy %>% count(year, name = "total_words")

glimpse(sotu_df)
Rows: 240
Columns: 4
$ president <chr> "George Washington", "George Washington", "George Washington…
$ year      <int> 1790, 1790, 1791, 1792, 1793, 1794, 1795, 1796, 1797, 1798, …
$ party     <chr> "Nonpartisan", "Nonpartisan", "Nonpartisan", "Nonpartisan", …
$ text      <chr> "Fellow-Citizens of the Senate and House of Representatives:…
nrow(sotu_tidy)
[1] 1988226

The Syuzhet dictionary was created by Matthew Jockers in the Nebraska Literary Lab, using human coded sentence level data in a corpus of fiction. It can be accessed through the syuzhet R package. Unlike the AFINN word list it is a numerical list, with values ranging from approximately -1 to 1.

library(syuzhet)
Warning: package 'syuzhet' was built under R version 4.6.1
syuzhet_lex <- get_sentiment_dictionary("syuzhet") %>%
  as_tibble() %>%
  select(word, value)

afinn_lex <- get_sentiments("afinn")
bing_lex  <- get_sentiments("bing")
nrc_lex   <- get_sentiments("nrc") %>%
  filter(sentiment %in% c("positive", "negative"))

range(syuzhet_lex$value)
[1] -1  1
nrow(syuzhet_lex)
[1] 10748

Speeches differ a lot in length, so unlike Austen’s fixed 80-line sections, raw sums would mostly track how long each address was. To balance this, I will divide each year’s net score by its total word count and express it per 1,000 words.

score_numeric <- function(lex, method) {
  sotu_tidy %>%
    inner_join(lex, by = "word") %>%
    group_by(year) %>%
    summarise(raw = sum(value)) %>%
    mutate(method = method)
}
score_binary <- function(lex, method) {
  sotu_tidy %>%
    inner_join(lex, by = "word") %>%
    count(year, sentiment) %>%
    pivot_wider(names_from = sentiment, values_from = n, values_fill = 0) %>%
    mutate(raw = positive - negative) %>%
    select(year, raw) %>%
    mutate(method = method)
}
sotu_scores <- bind_rows(
  score_numeric(afinn_lex, "AFINN"),
  score_binary(bing_lex, "Bing et al."),
  score_binary(nrc_lex, "NRC"),
  score_numeric(syuzhet_lex, "Syuzhet")
) %>%
  left_join(total_words, by = "year") %>%
  mutate(score = raw / total_words * 1000) %>%
  group_by(method) %>%
  mutate(z = as.numeric(scale(score))) %>%
  ungroup()
Warning in inner_join(., lex, by = "word"): Detected an unexpected many-to-many relationship between `x` and `y`.
ℹ Row 857799 of `x` matches multiple rows in `y`.
ℹ Row 2698 of `y` matches multiple rows in `x`.
ℹ If a many-to-many relationship is expected, set `relationship =
  "many-to-many"` to silence this warning.
Warning in inner_join(., lex, by = "word"): Detected an unexpected many-to-many relationship between `x` and `y`.
ℹ Row 228 of `x` matches multiple rows in `y`.
ℹ Row 2225 of `y` matches multiple rows in `x`.
ℹ If a many-to-many relationship is expected, set `relationship =
  "many-to-many"` to silence this warning.
Warning in inner_join(., lex, by = "word"): Detected an unexpected many-to-many relationship between `x` and `y`.
ℹ Row 1572157 of `x` matches multiple rows in `y`.
ℹ Row 4201 of `y` matches multiple rows in `x`.
ℹ If a many-to-many relationship is expected, set `relationship =
  "many-to-many"` to silence this warning.
ggplot(sotu_scores, aes(year, score, fill = method)) +
  geom_col(show.legend = FALSE) +
  facet_wrap(~method, ncol = 1, scales = "free_y") +
  labs(x = NULL, y = "Net sentiment per 1,000 words")

Because the lexicons use different scales, the raw values are not directly comparable. Standardizing each (z-score) puts them on one axis:

ggplot(sotu_scores, aes(year, z, color = method)) +
  geom_line(alpha = 0.8) +
  labs(x = NULL, y = "Standardized net sentiment (z-score)", color = NULL)

cor_mat <- sotu_scores %>%
  select(year, method, score) %>%
  pivot_wider(names_from = method, values_from = score) %>%
  select(-year) %>%
  cor(use = "pairwise.complete.obs")

round(cor_mat, 2)
            AFINN Bing et al.  NRC Syuzhet
AFINN        1.00        0.85 0.74    0.87
Bing et al.  0.85        1.00 0.73    0.87
NRC          0.74        0.73 1.00    0.87
Syuzhet      0.87        0.87 0.87    1.00
lexicons <- list(
  "AFINN"       = afinn_lex   %>% mutate(pos = value > 0),
  "Bing et al." = bing_lex    %>% mutate(pos = sentiment == "positive"),
  "NRC"         = nrc_lex     %>% mutate(pos = sentiment == "positive"),
  "Syuzhet"     = syuzhet_lex %>% mutate(pos = value > 0)
)

coverage <- imap_dfr(lexicons, function(lex, name) {
  tibble(
    lexicon       = name,
    words         = n_distinct(lex$word),
    positive      = sum(lex$pos),
    negative      = sum(!lex$pos),
    neg_pos_ratio = round(negative / positive, 2),
    pct_tokens_matched = round(
      100 * nrow(semi_join(sotu_tidy, distinct(lex, word), by = "word")) /
        nrow(sotu_tidy), 1)
  )
})

coverage
# A tibble: 4 × 6
  lexicon     words positive negative neg_pos_ratio pct_tokens_matched
  <chr>       <int>    <int>    <int>         <dbl>              <dbl>
1 AFINN        2477      878     1599          1.82                6.2
2 Bing et al.  6783     2005     4781          2.38                6.4
3 NRC          5543     2308     3316          1.44               10.8
4 Syuzhet     10747     3587     7161          2                  14  

In the chapter, the word-level view exposed the “miss” anomaly. Here is the same check for Bing and for the new Syuzhet lexicon on SOTU text.

top_bing <- sotu_tidy %>%
  inner_join(bing_lex, by = "word") %>%
  count(word, sentiment, name = "contribution") %>%
  mutate(lexicon = "Bing et al.")
Warning in inner_join(., bing_lex, by = "word"): Detected an unexpected many-to-many relationship between `x` and `y`.
ℹ Row 857799 of `x` matches multiple rows in `y`.
ℹ Row 2698 of `y` matches multiple rows in `x`.
ℹ If a many-to-many relationship is expected, set `relationship =
  "many-to-many"` to silence this warning.
top_syuzhet <- sotu_tidy %>%
  inner_join(syuzhet_lex, by = "word") %>%
  count(word, value) %>%
  mutate(sentiment = if_else(value > 0, "positive", "negative"),
         contribution = n * abs(value),
         lexicon = "Syuzhet") %>%
  select(word, sentiment, contribution, lexicon)
Warning in inner_join(., syuzhet_lex, by = "word"): Detected an unexpected many-to-many relationship between `x` and `y`.
ℹ Row 1572157 of `x` matches multiple rows in `y`.
ℹ Row 4201 of `y` matches multiple rows in `x`.
ℹ If a many-to-many relationship is expected, set `relationship =
  "many-to-many"` to silence this warning.
bind_rows(top_bing, top_syuzhet) %>%
  group_by(lexicon, sentiment) %>%
  slice_max(contribution, n = 5, with_ties = FALSE) %>%
  ungroup() %>%
  mutate(word = reorder_within(word, contribution, list(lexicon, sentiment))) %>%
  ggplot(aes(contribution, word, fill = sentiment)) +
  geom_col(show.legend = FALSE) +
  scale_y_reordered() +
  facet_wrap(lexicon ~ sentiment, scales = "free") +
  labs(x = "Contribution to sentiment", y = NULL)

sotu_scores %>%
  group_by(method) %>%
  summarise(
    most_positive_year = year[which.max(z)],
    most_negative_year = year[which.min(z)]
  )
# A tibble: 4 × 3
  method      most_positive_year most_negative_year
  <chr>                    <int>              <int>
1 AFINN                     1950               1942
2 Bing et al.               1790               1938
3 NRC                       1790               1917
4 Syuzhet                   1955               1942

Conclusion

Unlike the narrative nature of Austen’s novels which are divided into chunks of 80 lines to follow the narrative flow of the story, State of the Union speeches have no plot so the most natural division would be by time. Each year is one large chunk of text. This resulted in a larger variation in chunk sizes meaning normalisation was required at 1,000 words. This also means that whilst the chapter mentioned that the chunk size can affect results, the overall sentiment of the whole address will be more averaged with many sentiments in the middle meaning scores for each year will be more consistent.

The chapter found that although there was variation in the magnitude of the three lexicons, they were consistent with the direction of change. These plots show the correlation between the 4 lexicons, including the new Syuzhet. This shows that the correlation is lower than would have been expected in relation to the visual analysis of the plots for Pride and Prejudice from the chapter, showing that the choice of lexicon was more important in this corpus.

The Syuzhet lexicon is different in a few ways. It is a numeric, sentence validated, fiction based lexicon. So it is most similar to the AFINN lexicon. As opposed to being binary, Bing and NRC are binary. The coverage and size are different. The weights are small in value and nuanced so there is more impact from common words with slight sentiment. This is because there are more of them.

Words that come up as the main contributors to the plots may have more of a policy meaning rather than an emotional one. This is the same issue as with the word ‘miss’ in Austen. It is worth looking at the word level plots to see if this is the case. Using a custom stop word list is one method to do this.

All 4 methods are unigram based meaning they cannot account for negations or rhetoric. The results should be seen as a comparison of lexicons within one corpus. They are not an exact measurement of the tone of any administration.