Chapter 80 Sentiment analysis by word

We examine the total positive and negative contributions of each word.We display the words with the greatest contributions to positive/negative sentiment scores in the Violations text.

contributions = FoodInspectionsReduced %>%
  unnest_tokens(word, Violations) %>%
  filter(!word %in% stop_words$word) %>%
  dplyr::count(word, sort = TRUE) %>%
  ungroup() %>%
  inner_join(get_sentiments("afinn"), by = "word") %>%
  group_by(word) %>%
  dplyr::summarize(occurences = n(),
            contribution = sum(score))


contributions %>%
  top_n(10, abs(contribution)) %>%
  mutate(word = reorder(word, contribution)) %>%
  ggplot(aes(word, contribution, fill = contribution > 0)) +
  geom_col(show.legend = FALSE) +
  coord_flip() + theme_bw()