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
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.
# 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
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.
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)
# 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))
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.
`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
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
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.
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)
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.
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)
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.