This tutorial introduces sentiment analysis (SA) and shows how to perform a SA in R.

This tutorial is aimed at beginners and intermediate users of R with the aim of showcasing how to perform SA on textual data using R. The aim is not to provide a fully-fledged analysis but rather to show and exemplify selected useful methods associated with sentiment detection, analysis, and visualization.

The entire R Notebook for the tutorial can be downloaded here. If you want to render the R Notebook on your machine, i.e. knitting the document to html or a pdf, you need to make sure that you have R and RStudio installed and you also need to download the bibliography file and store it in the same folder where you store the Rmd file.

Here is a link to an interactive version of this tutorial on Google Colab. The interactive tutorial is based on a Jupyter notebook of this tutorial. This interactive Jupyter notebook allows you to execute code yourself and - if you copy the Jupyter notebook - you can also change and edit the notebook, e.g. you can change code and upload your own data.

SA is a cover term for approaches which extract information on emotion or opinion from natural language (Silge and Robinson 2017). SA have been successfully applied to analysis of language data in a wide range of disciplines such as psychology, economics, education, as well as political and social sciences. Commonly SA are used to determine the stance of a larger group of speakers towards a given phenomenon such as political candidates or parties, product lines or situations. Crucially, SA are employed in these domains because they have advantages compared to alternative methods investigating the verbal expression of emotion. One advantage of SA is that the emotion coding of SA is fully replicable.

Preparation and session set up

This tutorial is based on R. If you have not installed R or are new to it, you will find an introduction to and more information how to use R here. For this tutorials, we need to install certain packages from an R library so that the scripts shown below are executed without errors. Before turning to the code below, please install the packages by running the code below this paragraph. If you have already installed the packages mentioned below, then you can skip ahead and ignore this section. To install the necessary packages, simply run the following code - it may take some time (between 1 and 5 minutes to install all of the packages so you do not need to worry if it takes some time).

# install packages
# install klippy for copy-to-clipboard button in code chunks

Now that we have installed the packages, we activate them as shown below.

# set options
options(stringsAsFactors = F)          # no automatic data transformation
options("scipen" = 100, "digits" = 12) # suppress math annotation
# activate packages
# activate klippy for copy-to-clipboard button

Once you have installed R and RStudio and initiated the session by executing the code shown above, you are good to go.

What is Sentiment Analysis?

Sentiment Analysis (SA) extracts information on emotion or opinion from natural language (Silge and Robinson 2017). Most forms of SA provides information about positive or negative polarity, e.g. whether a tweet is positive or negative. As such, SA represents a type of classifier that assigns values to texts. As most SA only provide information about polarity, SA is often regarded as rather coarse-grained and, thus, rather irrelevant for the types of research questions in linguistics.

In the language sciences, SA can also be a very helpful tool if the type of SA provides more fine-grained information. In the following, we will perform such a information-rich SA. The SA used here does not only provide information about polarity but it will also provide association values for eight core emotions.

The more fine-grained output is made possible by relying on the Word-Emotion Association Lexicon (Mohammad and Turney 2013), which comprises 10,170 terms, and in which lexical elements are assigned scores based on ratings gathered through the crowd-sourced Amazon Mechanical Turk service. For the Word-Emotion Association Lexicon raters were asked whether a given word was associated with one of eight emotions. The resulting associations between terms and emotions are based on 38,726 ratings from 2,216 raters who answered a sequence of questions for each word which were then fed into the emotion association rating (cf. Mohammad and Turney 2013). Each term was rated 5 times. For 85 percent of words, at least 4 raters provided identical ratings. For instance, the word cry or tragedy are more readily associated with SADNESS while words such as happy or beautiful are indicative of JOY and words like fit or burst may indicate ANGER. This means that the SA here allows us to investigate the expression of certain core emotions rather than merely classifying statements along the lines of a crude positive-negative distinction.

Getting started

In the following, we will perform a SA to investigate the emotionality of five different novels. We will start with the first example and load five pieces of literature.

darwin <- base::readRDS(url("", "rb"))
twain <- base::readRDS(url("", "rb"))
orwell <- base::readRDS(url("", "rb"))
lovecraft <- base::readRDS(url("", "rb"))

Write function to clean data

txtclean <- function(x, title){
  x <- x %>%
    iconv(to = "UTF-8") %>%
    base::tolower() %>%
    paste0(collapse = " ") %>%
    stringr::str_split(" ") %>%
    unlist() %>%
    tibble() %>%
    dplyr::select(word = 1, everything()) %>%
    dplyr::mutate(novel = title) %>%
    dplyr::anti_join(stop_words) %>%
    dplyr::mutate(word = str_remove_all(word, "\\W")) %>%
    dplyr::filter(word != "")

Process and clean texts.

# process text data
darwin_clean <- txtclean(darwin, "darwin")
lovecraft_clean <- txtclean(lovecraft, "lovecraft")
orwell_clean <- txtclean(orwell, "orwell")
twain_clean <- txtclean(twain, "twain")

Basic Sentiment Analysis

In a next step, we clean the data, convert it to lower case, and split it into individual words.

textdata:::download_functions$nrc(file.path(rappdirs::user_cache_dir("textdata"), "nrc"))

novels_anno <- rbind(darwin_clean, twain_clean, orwell_clean, lovecraft_clean) %>%
  dplyr::group_by(novel) %>%
  dplyr::mutate(words = n()) %>%
  dplyr::left_join(textdata::lexicon_nrc(manual_download = TRUE)) %>%
  dplyr::mutate(novel = factor(novel),
         sentiment = factor(sentiment))

We will now summarize the results of the SA and calculate the percentages of the prevalence of emotions across the books.

novels <- novels_anno %>%
  dplyr::group_by(novel) %>%
  dplyr::group_by(novel, sentiment) %>%
  dplyr::summarise(sentiment = unique(sentiment),
                   sentiment_freq = n(),
                   words = unique(words)) %>%
  dplyr::filter( == F) %>%
  dplyr::mutate(percentage = round(sentiment_freq/words*100, 1))

After performing the SA, visualize the results and show the scores fro each core emotion by book.

novels %>%
  dplyr::filter(sentiment != "positive",
         sentiment != "negative") %>%
  ggplot(aes(sentiment, percentage, fill = novel)) +    
           position=position_dodge()) + 
  scale_fill_manual(name = "", values=c("orange", "gray70", "red", "grey30")) +
  theme_bw() +
  theme(legend.position = "top")

We can also display the emotions by book and re-level sentiment so that the different core emotions are ordered from more negative (red) to more positive (blue).

novels %>%
  dplyr::filter(sentiment != "positive",
         sentiment != "negative") %>%
  dplyr::mutate(sentiment = factor(sentiment, 
                            levels = c("anger", "fear", "disgust", "sadness",
                                   "surprise", "anticipation", "trust", "joy"))) %>%
  ggplot(aes(novel, percentage, fill = sentiment)) +    
  geom_bar(stat="identity", position=position_dodge()) + 
  scale_fill_brewer(palette = "RdBu") +
  theme_bw() +
  theme(legend.position = "right") +

Identifying important emotives

We now check, which words have contributed to the emotionality scores. In other words, we investigate, which words are most important for the emotion scores within each novel. For the sake of interpretability, we will remove several core emotion categories and also the polarity.

novels_impw <- novels_anno %>%
         sentiment != "anticipation",
         sentiment != "surprise",
         sentiment != "disgust",
         sentiment != "negative",
         sentiment != "sadness",
         sentiment != "positive") %>%
  dplyr::mutate(sentiment = factor(sentiment, levels = c("anger", "fear",  "trust", "joy"))) %>%
  dplyr::group_by(novel) %>%
  dplyr::count(word, sentiment, sort = TRUE) %>%
  dplyr::group_by(novel, sentiment) %>%
  dplyr::top_n(3) %>%
  dplyr::mutate(score = n/sum(n))

We can now visualize the top three words for the remaining core emotion categories.

novels_impw %>%
  dplyr::group_by(novel) %>%
  slice_max(score, n = 20) %>%
  dplyr::arrange(desc(score)) %>%
  dplyr::ungroup() %>%
  ggplot(aes(x = reorder(word, score), y = score, fill = word)) +
  facet_wrap(novel~sentiment, ncol = 4, scales = "free_y") +
  geom_col(show.legend = FALSE) +
  coord_flip() +
  labs(x = "Words")

Calculating and dispalying polarity

Now, we visualize the polarity of each book, i.e. the ratio of the number of positive emotion words divided by the number of negative words.

novels %>%
  dplyr::filter(sentiment == "positive" | sentiment == "negative") %>%
  dplyr::select(-percentage, -words) %>%
  dplyr::mutate(sentiment_sum = sum(sentiment_freq),
         positive = sentiment_sum-sentiment_freq) %>%
  dplyr::filter(sentiment != "positive") %>%
  dplyr::rename(negative = sentiment_freq) %>%
  dplyr::select(novel, positive, negative) %>%
  dplyr::group_by(novel) %>%
  dplyr::summarise(polarity = positive/negative) %>%
  ggplot(aes(reorder(novel, polarity, mean), polarity)) +    
  geom_point(size = 3) + 
  theme_bw() +
  labs(y = "polarity\n\nmore negative                                more positive\n",
       x = "novel")

Overall, all books are in the positive range (the polarity score is not negative) and we see that lovecraft is the book with the most negative emotion words while darwin is the most positive book as it has the highest average polarity ratio.

Calculating and dispalying changes in polarity

There are two main methods for tracking changes in polarity: binning and moving averages. binning splits the data up into sections and calculates the polarity ration within each bin. Moving averages calculate the mean within windows that are then shifted forward. We begin with an exemplification of binning and then move on to calculating moving averages.


The following code chunk uses binning to determine the polarity and subsequently displaying changes in polarity across the development of the novels’ plots.

novels_bin <- novels_anno %>%
  dplyr::group_by(novel) %>%
  dplyr::filter( | sentiment == "negative" | sentiment == "positive") %>%
  dplyr::mutate(sentiment = as.character(sentiment),
         sentiment = case_when( ~ "0", 
                               TRUE ~ sentiment),
         sentiment= case_when(sentiment == "0" ~ 0,
                              sentiment == "positive" ~ 1,
                              TRUE ~ -1),
         id = 1:n(),
         index = as.numeric(cut2(id, m=100))) %>%
  dplyr::group_by(novel, index) %>%
  dplyr::summarize(index = unique(index),
            polarity = mean(sentiment))

We now have an average polarity for each bin and can plot this polarity over the development of the story.

ggplot(novels_bin, aes(index, polarity)) + 
  facet_wrap(vars(novel), scales="free_x") +
  geom_smooth(se = F, col = "black") + 
  theme_bw() +
  labs(y = "polarity ratio (mean by bin)",
       x = "index (bin)")

Moving average

Another method for tracking changes in polarity over time is to calculate rolling or moving means. It should be noted thought that rolling means are not an optimal method for tracking changes over time and rather represent a method for smoothing chaotic time-series data. However, they can be used to complement the analysis of changes that are detected by binning.

To calculate moving averages, we will assign words with positive polarity a value +1 and words with negative polarity a value of -1 (neutral words are coded as 0). A rolling mean calculates the mean over a fixed window span. Once the initial mean is calculated, the window is shifted to the next position and the mean is calculated for that window of values, and so on. We set the window size to 100 words which represents an arbitrary value.

novels_change <- novels_anno %>%
  dplyr::filter( | sentiment == "negative" | sentiment == "positive") %>%
  dplyr::group_by(novel) %>%
  dplyr::mutate(sentiment = as.character(sentiment),
         sentiment = case_when( ~ "0", 
                               TRUE ~ sentiment),
         sentiment= case_when(sentiment == "0" ~ 0,
                              sentiment == "positive" ~ 1,
                              TRUE ~ -1),
         id = 1:n()) %>%
  dplyr::summarise(id = id,
                 rmean=rollapply(sentiment, 100, mean, align='right', fill=NA)) %>%

We will now display the values of the rolling mean to check if three are notable trends in how the polarity shifts over the course of the unfolding of the story within George Orwell’s Nineteen Eighty-Four.

ggplot(novels_change, aes(id, rmean)) +    
  facet_wrap(vars(novel), scales="free_x") +
  geom_smooth(se = F, col = "black") + 
  theme_bw() +
  labs(y = "polarity ratio (rolling mean, k = 100)",
       x = "index (word in monograph)")

The difference between the rolling mean and the binning is quite notable and results from the fact, that rolling means represent a smoothing method rather than a method to track changes over time.

Neutralizing negation

So far we have ignored that negation affects the meaning and also the sentiment that is expressed by words. In practice, this means that the sentence you are a good boy and You are not a good boy would receive the same scores as we strictly focused on the use of emotive but ignored how words interact and how the context affects word meaning.

In fact, we removed not and other such negators (e.g. none, never, or neither) when we removed stop words. In this section, we want to discover how we can incorporate context in our SA. Unfortunately, we have to restrict this example to an analysis of polarity as performing a context-sensitive sentiment analysis that would extend the Word-Emotion Association Lexicon would be quite complex and require generating our own sentiment dictionary.

We begin by cleaning George Orwell’s Nineteen Eighty-Four, then splitting it into sentences, and selecting the first 50 sentences as the sample that we will be working with.

# split text into sentences
orwell_sent <- orwell %>%
  iconv(to = "latin1") %>%
  paste0(collapse = " ") %>%
  stringr::str_replace_all(., "([a-z])- ([a-z])", "\\1\\2") %>%
  stringr::str_squish() %>%
  tibble() %>%
  dplyr::select(text = 1, everything()) %>%
  tidytext::unnest_tokens(sentence, text, token = "sentences") %>%

In a next step, we load the sentimentr package which allows us to extract negation-sensitive polarity scores for each sentences. In addition, we apply the sentimentr function to each sentence and extract their polarity scores.

orwell_sent_class <- orwell_sent %>%
  dplyr::mutate(ressent = sentiment(sentence)$sentiment)

If you are interested in learning more about SA in R, Silge and Robinson (2017) is highly recommended as it goes more into detail and offers additional information.

Citation & Session Info

Schweinberger, Martin. 2022. Sentiment Analysis in R. Brisbane: The University of Queensland. url: (Version 2022.05.21).

  author = {Schweinberger, Martin},
  title = {Sentiment Analysis in R},
  note = {},
  year = {2022},
  organization = {The University of Queensland, School of Languages and Cultures},
  address = {Brisbane},
  edition = {2022.05.21}
## R version 4.2.0 (2022-04-22 ucrt)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 19043)
## Matrix products: default
## locale:
## [1] LC_COLLATE=German_Germany.utf8  LC_CTYPE=German_Germany.utf8   
## [3] LC_MONETARY=German_Germany.utf8 LC_NUMERIC=C                   
## [5] LC_TIME=German_Germany.utf8    
## attached base packages:
## [1] stats     graphics  grDevices datasets  utils     methods   base     
## other attached packages:
##  [1] flextable_0.7.0  sentimentr_2.9.0 Hmisc_4.7-0      ggplot2_3.3.6   
##  [5] Formula_1.2-4    survival_3.3-1   lattice_0.20-45  zoo_1.8-10      
##  [9] textdata_0.4.2   tidytext_0.3.3   readr_2.1.2      stringr_1.4.0   
## [13] dplyr_1.0.9     
## loaded via a namespace (and not attached):
##  [1] nlme_3.1-157        fs_1.5.2            bit64_4.0.5        
##  [4] RColorBrewer_1.1-3  SnowballC_0.7.0     tools_4.2.0        
##  [7] backports_1.4.1     bslib_0.3.1         utf8_1.2.2         
## [10] R6_2.5.1            rpart_4.1.16        mgcv_1.8-40        
## [13] DBI_1.1.2           colorspace_2.0-3    nnet_7.3-17        
## [16] withr_2.5.0         tidyselect_1.1.2    gridExtra_2.3      
## [19] bit_4.0.4           compiler_4.2.0      cli_3.3.0          
## [22] htmlTable_2.4.0     textshape_1.7.3     xml2_1.3.3         
## [25] officer_0.4.2       labeling_0.4.2      sass_0.4.1         
## [28] scales_1.2.0        checkmate_2.1.0     rappdirs_0.3.3     
## [31] systemfonts_1.0.4   digest_0.6.29       foreign_0.8-82     
## [34] rmarkdown_2.14      base64enc_0.1-3     jpeg_0.1-9         
## [37] pkgconfig_2.0.3     htmltools_0.5.2     fastmap_1.1.0      
## [40] highr_0.9           htmlwidgets_1.5.4   rlang_1.0.2        
## [43] rstudioapi_0.13     farver_2.1.0        jquerylib_0.1.4    
## [46] generics_0.1.2      jsonlite_1.8.0      qdapRegex_0.7.5    
## [49] vroom_1.5.7         zip_2.2.0           tokenizers_0.2.1   
## [52] magrittr_2.0.3      textclean_0.9.3     Matrix_1.4-1       
## [55] Rcpp_1.0.8.3        munsell_0.5.0       fansi_1.0.3        
## [58] gdtools_0.2.4       lifecycle_1.0.1     stringi_1.7.6      
## [61] yaml_2.3.5          grid_4.2.0          parallel_4.2.0     
## [64] crayon_1.5.1        splines_4.2.0       hms_1.1.1          
## [67] knitr_1.39          klippy_0.0.0.9500   pillar_1.7.0       
## [70] uuid_1.1-0          glue_1.6.2          evaluate_0.15      
## [73] latticeExtra_0.6-29 data.table_1.14.2   renv_0.15.4        
## [76] png_0.1-7           vctrs_0.4.1         lexicon_1.2.1      
## [79] tzdb_0.3.0          gtable_0.3.0        purrr_0.3.4        
## [82] assertthat_0.2.1    xfun_0.30           syuzhet_1.0.6      
## [85] janeaustenr_0.1.5   tibble_3.1.7        cluster_2.1.3      
## [88] ellipsis_0.3.2

Back to top

Back to HOME


Mohammad, Saif M, and Peter D Turney. 2013. “Crowdsourcing a Word-Emotion Association Lexicon.” Computational Intelligence 29 (3): 436–65.
Silge, Julia, and David Robinson. 2017. Text Mining with r: A Tidy Approach. " O’Reilly Media, Inc.".