DATA 607 - Week 10 Assignment

Xhulia Turkaj

2023-12-02

In Text Mining with R, Chapter 2 looks at ‘Sentiment Analysis’. In this assignment, you should start by getting the primary example code from chapter 2 working in an R Markdown document. You should provide a citation to this base code. You’re then asked to extend the code in two ways:
• Work with a different corpus of your choosing, and
• Incorporate at least one additional sentiment lexicon (possibly from another R package that you’ve found through research).

The base code used in this assignment is taken from:
‘Text Mining with R’ by Julia Silge and David Robinson (O’Reilly).
Copyright 2017 Julia Silge and David Robinson,978-1-491-98165-8.

Sentiment analysis of “Adventures of Sherlock Holmes” by Arthur Conan Doyle 1859-1930

In this project, I am conducting a sentiment analysis on “The Adventures of Sherlock Holmes” by Arthur Conan Doyle, utilizing the text sourced from the Gutenberg package. My focus is on examining how sentiments vary from one story to another and how different lexicons Bing, Afinn, NRC, and SentimentR affect these sentiment assessments, offering a multi-dimensional view of the emotional tones in the world famous detective series.

The following packages were utilized in this project

library(dplyr)
library(ggplot2)
library(gutenbergr)
library(magrittr)
library(pacman)
library(readtext)
library(reshape2)
library(stringr)
library(sentimentr)
library(syuzhet)
library(textdata)
library(tidyr)
library(tidytext)
library(wordcloud)

Let’s begin by retrieving data from the Gutenberg website and take a quick glimpse of the format.

adventures_Sherlock <-  gutenberg_download(48320)
save(adventures_Sherlock, file = "adventures_Sherlock.Rdata")
## Rows: 12,350
## Columns: 2
## $ gutenberg_id <int> 48320, 48320, 48320, 48320, 48320, 48320, 48320, 48320, 4…
## $ text         <chr> "ADVENTURES OF SHERLOCK HOLMES", "", "", "", "", "[Illust…

Upon reviewing the format of the data I confirmed that each story began with “Adventure” followed by orderly roman numbers I will use the pattern to add a story index column to the data frame which I will then substitute it with the pertaining tittle name

# Identify the start of each story where "Adventure I", "Adventure II", etc., are the only words in the row

story_starts <- which(str_detect(adventures_Sherlock$text, regex("^Adventure [IVXLCDM]+$", ignore_case = TRUE)))
the_end_index <- grep("THE END", adventures_Sherlock$text)

# Create a Story Index Column 

story_index <- rep(NA, nrow(adventures_Sherlock))
current_story <- NA 

for (i in 1:nrow(adventures_Sherlock)) {
    if (i %in% story_starts) {
        if (is.na(current_story)) {
            current_story <- 1 
        } else {
            current_story <- current_story + 1
        }
    }
    if (!is.na(current_story) && current_story == 12 && i >= the_end_index) {
        break 
    }
    story_index[i] <- current_story
}

# Add the story index to the data frame
adventures_Sherlock$Story <- story_index

For each story in the text file, the tittle is located on the third line. In order to extract the title I need to group by story index and retrieve the third line and then merge the titles back into the dataframe using a left join.

story_titles <- adventures_Sherlock %>%
    group_by(Story) %>%
    summarise(title = nth(text, 3), .groups = 'drop')

adventures_Sherlock <- adventures_Sherlock %>%
    left_join(story_titles, by = "Story")

print(adventures_Sherlock[c(1500,3000,4500,7000),])
## # A tibble: 4 × 4
##   gutenberg_id text                                                  Story title
##          <int> <chr>                                                 <dbl> <chr>
## 1        48320 “‘It would be injustice to hesitate,’ said he. ‘You …     2 THE …
## 2        48320 brought in a telegram. It was from Sherlock Holmes, …     4 THE …
## 3        48320 “There is but one thing to do. It must be done at on…     5 THE …
## 4        48320 “My name is Helen Stoner, and I am living with my st…     8 THE …

I will first tokenize into senteces, and then into words.

tidy_Sherlock = adventures_Sherlock |>
  group_by(title) |>
  unnest_tokens(sentence,text,token="sentences") |>
  mutate(sentence.num = row_number()) |>
  ungroup() |>
  unnest_tokens(word,sentence)
print(tidy_Sherlock[c(1500,9000,19000),])
## # A tibble: 3 × 3
##   title                 sentence.num word  
##   <chr>                        <int> <chr> 
## 1 A SCANDAL IN BOHEMIA            69 had   
## 2 THE RED-HEADED LEAGUE           11 wilson
## 3 A CASE OF IDENTITY              41 the

Since the 12 Adventures have classic detective story lines I decided to use the NRC lexicon and visualize the presence of Fear and Surprise in the 12 stories and see which sentiment dominates.

Next I will examine how sentiment changes throughout each story using the Bing lexicon.

 Sherlcok_sentiment <- tidy_Sherlock %>%
  filter(title != "", title != "Introduction") %>% 
  inner_join(get_sentiments("bing")) %>%
  count(title, index = sentence.num %/% 80, sentiment) %>%
  pivot_wider(names_from = sentiment, values_from = n, values_fill = 0) %>% 
  mutate(sentiment = positive - negative)

Sentiment through the 12 Stories of The Adventures of Sherlock Holmes

When analyzing the sentiment plots, it becomes evident that the sentiment index fluctuates significantly, not only varying from one story to another within “The Adventures of Sherlock Holmes” but also within individual stories themselves.

For example we notice how “A Case of Identity”, “A scandal in Bohemia” and “The Red-Headed League” there is a predominantly positive sentiment index, indicating a more upbeat or less tense narrative tone. Likely because they feature clever, humorous plotlines and resolutions without severe danger or dark themes.

While when it comes to “The Man with the Twisted Lip” and “The Adventures of the Speckled Band” we observe predominantly negative sentiment indexes. They reflect the more suspenseful themes of deception, danger, and the threat of violence in these stories.

Comparing the four sentiment dictionaries

Next, I will compare the results of sentiment analyses using four different lexicons - Bing, Afinn, NRC, and SentimentR - to explore how each lexicon interprets the emotional tones in the text. To analyze the differences better I will focus in one of the short stories -The Adventure of the Engineer’s Thumb”-

The three lexicons give results that are different but have similar relative trajectories through the Story. There are similar dips and peaks in sentiment at about the same places in the novel excluding the end part, but the absolute values are significantly different.

SentimentR

Using SentimentR lexicon on the same story we did before “The Adventure of the Engineer’s Thumb”

##       element_id word_count sd ave_sentiment
##    1:          1          2 NA     0.3535534
##    2:          2          0 NA     0.0000000
##    3:          3          6 NA     0.2041241
##    4:          4          0 NA     0.0000000
##    5:          5          0 NA     0.0000000
##   ---                                       
## 1221:       1221          9 NA     0.3333333
## 1222:       1222          0 NA     0.0000000
## 1223:       1223          0 NA     0.0000000
## 1224:       1224          0 NA     0.0000000
## 1225:       1225          0 NA     0.0000000

When comparing the 4th sentiment analysis done with sentimentR lexicon we can easily notice that it is similar to the pattern of the other three sentiment analysis of the “The Adventure of the Engineer’s Thumb” story.

Word Cloud of the “The Adventures of Sherlock Holmes”

Conclusion

The lexicon chosen as well as the token used to base the sentiment analysis on plays a big role on the results.