There are several frameworks for text analysis in R. For a comprehensive list visit the CRAN task force on natural language processing: https://cran.r-project.org/web/views/NaturalLanguageProcessing.html.
Here are some of the widely used packages and frameworks:
tm package: uses DTM object (Term Document Matrix)
and provides a general framework for text mining in R. A DTM is a matrix
where each row represents a document, each column represents a term and
each value includes the number of times that term appears in that
document. For more details see the CRAN page: https://cran.r-project.org/web/packages/tm/index.html
and the article Text Mining
Infrastructure in R
quanteda package: uses dfm object
(document feature matrix), see the website https://quanteda.io/.
tidytext package: uses tidyverse principles in
analyzing text data. It provides tools for word processing and sentiment
analysis. The book Text Mining with R written by Julia Silge and David
Robinson uses tidytext package and introduces readers to
principles of text mining. See the electronic version of the book Text Mining with R.
Also visit Julia Silge’s github page: https://github.com/juliasilge/tidytext.
Also check out the tutorial by Julia Silge: Tutorial
on Tidytext
In the following, I will use {tidytext} package.
In a usual tidy data set, each variable is a column and each
observation is a row. Similarly, a tidy text data is a table or data
frame (tibble) where each row is a token. A token is a
meaningful unit of text, for example a word. Converting a text data set
into tokens is generally known as ‘tokenization’. We can use
the standart tidyverse tools ({dplyr},
{ggplot2}, etc.) to analyze tidy text data.
As an example, consider the following text data
# United Nations Universal Declaration of Human Rights 1948
article1 <- c("All human beings are born free and equal in dignity and rights.",
"They are endowed with reason and conscience and should act towards one another in a spirit of brotherhood.")
article1## [1] "All human beings are born free and equal in dignity and rights."
## [2] "They are endowed with reason and conscience and should act towards one another in a spirit of brotherhood."
It consists of two rows of characters. Let’s create a tibble using
article1:
## # A tibble: 2 × 2
## sentence text
## <int> <chr>
## 1 1 All human beings are born free and equal in dignity and rights.
## 2 2 They are endowed with reason and conscience and should act towards o…
Once we have a tibble containing our text data, we can tokenize it
based on single words using tidytext::unnest_tokens()
function.
# you need install and activate the tidytext package
library(tidytext)
#
text_data |>
unnest_tokens(word, text) # word is output; text is input## # A tibble: 30 × 2
## sentence word
## <int> <chr>
## 1 1 all
## 2 1 human
## 3 1 beings
## 4 1 are
## 5 1 born
## 6 1 free
## 7 1 and
## 8 1 equal
## 9 1 in
## 10 1 dignity
## # ℹ 20 more rows
Notice that 2-by-1 text data now has 30 rows each containing a single word in the text. The data set is still in tidy format. Sentence numbers (first column) are retained but punctuation is removed after tokenization.
A token can consist of more than one word. These are also known as n-grams. An n-gram is simply a consecutive sequence of n words. A bigram, for example, is a consecutive sequence of two words.
## # A tibble: 28 × 2
## sentence bigram
## <int> <chr>
## 1 1 all human
## 2 1 human beings
## 3 1 beings are
## 4 1 are born
## 5 1 born free
## 6 1 free and
## 7 1 and equal
## 8 1 equal in
## 9 1 in dignity
## 10 1 dignity and
## # ℹ 18 more rows
Representing a text as list or “bag” of its words without any regard to context and grammar is also known as “bag-of-words” approach.
Let’s count the words in the text data tibble
text_data:
text_data_tidy <- text_data |>
unnest_tokens(word, text)
# count
text_data_tidy |>
count(word, sort = TRUE)## # A tibble: 25 × 2
## word n
## <chr> <int>
## 1 and 4
## 2 are 2
## 3 in 2
## 4 a 1
## 5 act 1
## 6 all 1
## 7 another 1
## 8 beings 1
## 9 born 1
## 10 brotherhood 1
## # ℹ 15 more rows
Not surprisingly, the most frequent words are common words like “the,
a, and, are, is” which are not useful for analysis. These are known as
“stopwords”. We can easily remove them before the analysis. To do this,
we need a list of stopwords. Here is a list of stop words in the
{stopwords} package:
## # A tibble: 175 × 2
## word lexicon
## <chr> <chr>
## 1 i snowball
## 2 me snowball
## 3 my snowball
## 4 myself snowball
## 5 we snowball
## 6 our snowball
## 7 ours snowball
## 8 ourselves snowball
## 9 you snowball
## 10 your snowball
## # ℹ 165 more rows
Here is another stop words data set:
## # A tibble: 20 × 2
## word lexicon
## <chr> <chr>
## 1 'll stopwords-iso
## 2 'tis stopwords-iso
## 3 'twas stopwords-iso
## 4 've stopwords-iso
## 5 10 stopwords-iso
## 6 39 stopwords-iso
## 7 a stopwords-iso
## 8 a's stopwords-iso
## 9 able stopwords-iso
## 10 ableabout stopwords-iso
## 11 about stopwords-iso
## 12 above stopwords-iso
## 13 abroad stopwords-iso
## 14 abst stopwords-iso
## 15 accordance stopwords-iso
## 16 according stopwords-iso
## 17 accordingly stopwords-iso
## 18 across stopwords-iso
## 19 act stopwords-iso
## 20 actually stopwords-iso
An example of Turkish stop words:
## [1] "LC_COLLATE=Turkish_Türkiye.1254;LC_CTYPE=Turkish_Türkiye.1254;LC_MONETARY=Turkish_Türkiye.1254;LC_NUMERIC=C;LC_TIME=Turkish_Türkiye.1254"
## # A tibble: 471 x 2
## word lexicon
## <chr> <chr>
## 1 acaba stopwords-iso
## 2 acep stopwords-iso
## 3 açıkça stopwords-iso
## 4 açıkçası stopwords-iso
## 5 adamakıllı stopwords-iso
## 6 adeta stopwords-iso
## 7 ait stopwords-iso
## 8 altı stopwords-iso
## 9 altmış stopwords-iso
## 10 ama stopwords-iso
## # i 461 more rows
We can remove stop words using the dplyr::anti_join()
command:
## # A tibble: 16 x 2
## word n
## <chr> <int>
## 1 act 1
## 2 another 1
## 3 beings 1
## 4 born 1
## 5 brotherhood 1
## 6 conscience 1
## 7 dignity 1
## 8 endowed 1
## 9 equal 1
## 10 free 1
## 11 human 1
## 12 one 1
## 13 reason 1
## 14 rights 1
## 15 spirit 1
## 16 towards 1
Apparently, each word appears only once in the first article of the UN Universal Declaration of Human Rights.
We could remove the stop words using the stop_words data
set in the tidytext package.
data(stop_words) # in the tidytext package
# remove stopwords and count
text_data_tidy |>
anti_join(stop_words) |>
count(word, sort=TRUE)## # A tibble: 12 x 2
## word n
## <chr> <int>
## 1 act 1
## 2 born 1
## 3 brotherhood 1
## 4 conscience 1
## 5 dignity 1
## 6 endowed 1
## 7 equal 1
## 8 free 1
## 9 human 1
## 10 reason 1
## 11 rights 1
## 12 spirit 1
Exercise: The second article states that
# United Nations Universal Declaration of Human Rights 1948
article2 <- c("Everyone is entitled to all the rights and freedoms set forth in this Declaration, without distinction of any kind, such as race, colour, sex, language, religion, political or other opinion, national or social origin, property, birth or other status.",
"Furthermore, no distinction shall be made on the basis of the political, jurisdictional or international status of the country or territory to which a person belongs, whether it be independent, trust, non-self-governing or under any other limitation of sovereignty.")
article2## [1] "Everyone is entitled to all the rights and freedoms set forth in this Declaration, without distinction of any kind, such as race, colour, sex, language, religion, political or other opinion, national or social origin, property, birth or other status."
## [2] "Furthermore, no distinction shall be made on the basis of the political, jurisdictional or international status of the country or territory to which a person belongs, whether it be independent, trust, non-self-governing or under any other limitation of sovereignty."
Combine article1 and article2 and create a
tibble. Tokenize single words, eliminate stop words and count the number
of times each word is used.
A wordcloud is a simple graphical tool to summarize text data which displays frequently used words relatively larger, bolder, or in different colors.
There are several packages in R to draw wordclouds.
{ggwordcloud} provides a geom to be used with
ggplot. The geom_text_wordcloud_area() geom
accepts two inputs in the aesthetics, label (word) and size (frequency).
For example:
library(ggwordcloud)
wordcloud_df <-text_data_tidy |>
anti_join(stop_words) |>
count(word, sort = T)
wordcloud_df## # A tibble: 12 x 2
## word n
## <chr> <int>
## 1 act 1
## 2 born 1
## 3 brotherhood 1
## 4 conscience 1
## 5 dignity 1
## 6 endowed 1
## 7 equal 1
## 8 free 1
## 9 human 1
## 10 reason 1
## 11 rights 1
## 12 spirit 1
wordcloud_df |>
ggplot() +
geom_text_wordcloud_area(aes(label = word, size = n)) +
scale_size_area(max_size = 20) +
theme_minimal()Since each word appears only once their sizes in wordcloud are the same.
Example: H.G. Wells’ Time Machine
library(tidyverse)
library(tidytext)
# Download H.G. Wells' Time Machine using gutenbergr package
library(gutenbergr)
time_machine <- gutenberg_download(35)
tidy_time_machine <- time_machine |>
unnest_tokens(word, text) |>
anti_join(stop_words)
# word count
time_wordcloud_df <- tidy_time_machine |>
count(word, sort = TRUE)
time_wordcloud_df## # A tibble: 4,172 x 2
## word n
## <chr> <int>
## 1 time 207
## 2 machine 88
## 3 white 61
## 4 traveller 57
## 5 hand 49
## 6 morlocks 48
## 7 people 46
## 8 weena 46
## 9 found 44
## 10 light 43
## # i 4,162 more rows
library(ggwordcloud)
set.seed(11) # for reproducibility
time_wordcloud_df |> filter(n>10) |>
ggplot() +
geom_text_wordcloud_area(aes(label = word, size = n)) +
scale_size_area(max_size = 20) +
theme_minimal()See below for additional examples.
In sentiment analysis, we are interested in identifying emotional
content of a text. In particular, we aim to understand if a given text
or a section of a text can be characterized as positive or negative, or
can be classified into certain kinds of emotions. One way to achieve
this is to analyze the sentiment content of individual words. In order
to do this we need to employ a sentiment lexicon. There are three
general-purpose sentiment lexicons in tidytext package:
AFINN from Finn
Årup Nielsen: assigns words with a score that runs between -5 and 5,
with negative scores indicating negative sentiment and positive scores
indicating positive sentiment.## # A tibble: 2,477 x 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
## # i 2,467 more rows
bing from Bing Liu
and collaborators: categorizes words in a binary fashion into
positive and negative categories.## # A tibble: 6,786 x 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
## # i 6,776 more rows
nrc from Saif
Mohammad and Peter Turney: categorizes words in a binary fashion
(“yes”/“no”) into categories of positive, negative, anger, anticipation,
disgust, fear, joy, sadness, surprise, and trust.## # A tibble: 13,875 x 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
## # i 13,865 more rows
# sentiment types in nrc lexicon
get_sentiments("nrc") |>
group_by(sentiment) |>
summarise(n = n()) |>
arrange(desc(n))## # A tibble: 10 x 2
## sentiment n
## <chr> <int>
## 1 negative 3318
## 2 positive 2308
## 3 fear 1474
## 4 anger 1246
## 5 trust 1230
## 6 sadness 1187
## 7 disgust 1056
## 8 anticipation 837
## 9 joy 687
## 10 surprise 532
## # A tibble: 2,308 x 2
## word sentiment
## <chr> <chr>
## 1 abba positive
## 2 ability positive
## 3 abovementioned positive
## 4 absolute positive
## 5 absolution positive
## 6 absorbed positive
## 7 abundance positive
## 8 abundant positive
## 9 academic positive
## 10 academy positive
## # i 2,298 more rows
Example: Count the positive words in text_data_tidy
which was previously created above:
## # A tibble: 6 x 2
## word n
## <chr> <int>
## 1 brotherhood 1
## 2 conscience 1
## 3 dignity 1
## 4 endowed 1
## 5 reason 1
## 6 spirit 1
Example: Time Machine
time_machine_sentiment <- tidy_time_machine |>
# find a sentiment score for each word using bing lexicon
inner_join(get_sentiments("bing"))
# count sentiment
time_machine_sentiment |>
count(sentiment) ## # A tibble: 2 x 2
## sentiment n
## <chr> <int>
## 1 negative 1347
## 2 positive 638
# sentiment types in nrc lexicon
time_machine_sentiment_nrc <- tidy_time_machine |>
inner_join(get_sentiments("nrc"))
time_machine_sentiment_nrc## # A tibble: 6,787 x 3
## gutenberg_id word sentiment
## <int> <chr> <chr>
## 1 35 time anticipation
## 2 35 machine trust
## 3 35 machine trust
## 4 35 time anticipation
## 5 35 time anticipation
## 6 35 sunset anticipation
## 7 35 sunset positive
## 8 35 sudden surprise
## 9 35 shock anger
## 10 35 shock fear
## # i 6,777 more rows
## # A tibble: 10 x 2
## sentiment n
## <chr> <int>
## 1 positive 1257
## 2 negative 1129
## 3 trust 759
## 4 anticipation 743
## 5 fear 702
## 6 sadness 577
## 7 joy 543
## 8 anger 428
## 9 surprise 349
## 10 disgust 300
time_machine_sentiment_nrc |>
group_by(sentiment) |>
summarise(n = n()) |>
ggplot(aes(fct_reorder(sentiment, n),n)) +
geom_bar(stat="identity") +
coord_flip() +
xlab("")The frequency of a word or term frequency (tf) is a measure of how important a word is in a document. In English as well as in other languages there are several words that may not be important on their own (the, is, a, etc.). Removing these so-called stopwords from the document before the analysis is one way to measure the importance of words. Another way is to compute tf idf (term frequency inverse document frequency) statistic.
Inverse document frequency (idf) puts smaller weights on commonly used words in a document but increases the weight of less commonly used ones (so, the closer the idf to zero, the more common a word is). Multiplying tf (number of times a word appears in a document) by idf, we obtain the tf.idf statistic which measures how relevant a word is to a document in a collection of documents (for example, to one novel in a collection of novels or to one website in a collection of websites, see Silge, Text Mining with R).
idf can be computed using
\[idf(\text{term}) = \ln{\left(\frac{n_{\text{documents}}}{n_{\text{documents containing term}}}\right)}\]
where the numerator \(n_{\text{documents}}\) is the number of documents in the corpus and the denominator is the number of documents containing the term. For example, if there are 5 documents in the corpus and a given word is contained in all of them then \(idf\) will be \(0\). If a word is only contained in one of the documents then \(idf=\ln(5/1)\approx 1.61\).
This example is from Text Mining with R (by Julia Silge and David Robinson). For more details on the preprocessing please visit https://www.tidytextmining.com/tidytext.html#tidyausten.
# Jane Austin's books
# This is an example from Julia silge's book
# load data
load("../Data/j_austen_books_tidy.rda")Remove stop words:
Count word frequency:
## # A tibble: 13,914 x 2
## word n
## <chr> <int>
## 1 miss 1855
## 2 time 1337
## 3 fanny 862
## 4 dear 822
## 5 lady 817
## 6 sir 806
## 7 day 797
## 8 emma 787
## 9 sister 727
## 10 house 699
## # i 13,904 more rows
Bar graph using ggplot:
j_austen_books_tidy |>
count(word, sort = TRUE) |>
filter(n > 600) |>
mutate(word = reorder(word, n)) |>
ggplot(aes(n, word)) +
geom_col() +
labs(y = NULL)Display the most frequent words (n>300) over books:
j_austen_books_tidy |>
group_by(book) |>
count(word, sort = TRUE) |>
filter(n > 300) |>
mutate(word = reorder(word, n)) |>
ggplot(aes(n, word)) +
geom_col() + facet_wrap(~book) +
labs(y = NULL) +
theme(legend.position="none")Graph the most frequently used (n>100) words in Sense and Sensibility:
j_austen_books_tidy |>
filter(book == "Sense & Sensibility") |>
count(word, sort = TRUE) |>
filter(n > 100) |>
mutate(word = reorder(word, n)) |>
ggplot(aes(n, word)) +
geom_col() +
scale_x_continuous(breaks = seq(0,650,50)) +
labs(y = NULL,
title = "Most frequent words in Sense & Sensibility (n>100)")All 6 books together:
library(ggwordcloud)
wordcloud_df <-j_austen_books_tidy |>
count(word, sort = T) |>
top_n(100)
wordcloud_df |>
ggplot() +
geom_text_wordcloud_area(aes(label = word, size = n)) +
scale_size_area(max_size = 15)By books:
n <- 200
p1 <-j_austen_books_tidy |>
filter(book=="Sense & Sensibility") |>
count(word, sort = T) |>
slice_max(n, n=n) |>
ggplot() +
geom_text_wordcloud_area(aes(label = word, size = n)) +
scale_size_area(max_size = 15) +
labs(title = "Sense & Sensibility")
p1#
p2 <-j_austen_books_tidy |>
filter(book=="Pride & Prejudice") |>
count(word, sort = T) |>
slice_max(n, n=n) |>
ggplot() +
geom_text_wordcloud_area(aes(label = word, size = n)) +
scale_size_area(max_size = 15) +
labs(title = "Pride & Prejudice")
p2#
p3 <-j_austen_books_tidy |>
filter(book=="Mansfield Park") |>
count(word, sort = T) |>
slice_max(n, n=n) |>
ggplot() +
geom_text_wordcloud_area(aes(label = word, size = n)) +
scale_size_area(max_size = 15) +
labs(title = "Mansfield Park")
p3#
p4 <-j_austen_books_tidy |>
filter(book=="Emma") |>
count(word, sort = T) |>
slice_max(n, n=n) |>
ggplot() +
geom_text_wordcloud_area(aes(label = word, size = n)) +
scale_size_area(max_size = 15) +
labs(title = "Emma")
p4Examining how sentiment changes across J. Austen’s books (this example is from J. Silge’s text.)
jane_austen_sentiment <- j_austen_books_tidy |>
# find a sentiment score for each word using bing lexicon
inner_join(get_sentiments("bing")) |>
# count up how many positive and negative words there are
# in sections of 80 lines of text.
count(book, index = linenumber %/% 80, sentiment) |>
# convert to wide format
pivot_wider(names_from = sentiment, values_from = n, values_fill = 0) |>
# compute net sentiment score
mutate(sentiment = positive - negative)
head(jane_austen_sentiment)## # A tibble: 6 x 5
## book index negative positive sentiment
## <fct> <dbl> <int> <int> <int>
## 1 Sense & Sensibility 0 16 26 10
## 2 Sense & Sensibility 1 19 44 25
## 3 Sense & Sensibility 2 12 23 11
## 4 Sense & Sensibility 3 15 22 7
## 5 Sense & Sensibility 4 16 29 13
## 6 Sense & Sensibility 5 16 39 23
Note that there are 12620 lines in Sense & Sensibility which gives us about 157 sections of 80 lines. Here is the graph of emotional content per book:
ggplot(jane_austen_sentiment, aes(index, sentiment, fill = book)) +
geom_col(show.legend = FALSE) +
facet_wrap(~book, ncol = 2, scales = "free_x")Example: J. Austen’s books (from J. Silge’s text)
# Jane Austin's books
# This is an example from Julia silge's book
library(dplyr)
library(janeaustenr)
library(tidytext)
book_words <- austen_books() |>
unnest_tokens(word, text) |>
count(book, word, sort = TRUE)
total_words <- book_words |>
group_by(book) |>
summarize(total = sum(n))
book_words <- left_join(book_words, total_words)
book_words## # A tibble: 40,379 x 4
## book word n total
## <fct> <chr> <int> <int>
## 1 Mansfield Park the 6206 160460
## 2 Mansfield Park to 5475 160460
## 3 Mansfield Park and 5438 160460
## 4 Emma to 5239 160996
## 5 Emma the 5201 160996
## 6 Emma and 4896 160996
## 7 Mansfield Park of 4778 160460
## 8 Pride & Prejudice the 4331 122204
## 9 Emma of 4291 160996
## 10 Pride & Prejudice to 4162 122204
## # i 40,369 more rows
Plot term frequency (tf = n/total):
library(ggplot2)
ggplot(book_words, aes(n/total, fill = book)) +
geom_histogram(show.legend = FALSE) +
xlim(NA, 0.0009) +
facet_wrap(~book, ncol = 2, scales = "free_y")Compute tf-idf:
## # A tibble: 40,379 x 7
## book word n total tf idf tf_idf
## <fct> <chr> <int> <int> <dbl> <dbl> <dbl>
## 1 Mansfield Park the 6206 160460 0.0387 0 0
## 2 Mansfield Park to 5475 160460 0.0341 0 0
## 3 Mansfield Park and 5438 160460 0.0339 0 0
## 4 Emma to 5239 160996 0.0325 0 0
## 5 Emma the 5201 160996 0.0323 0 0
## 6 Emma and 4896 160996 0.0304 0 0
## 7 Mansfield Park of 4778 160460 0.0298 0 0
## 8 Pride & Prejudice the 4331 122204 0.0354 0 0
## 9 Emma of 4291 160996 0.0267 0 0
## 10 Pride & Prejudice to 4162 122204 0.0341 0 0
## # i 40,369 more rows
Common and unimportant words have zero tfidf values.
## # A tibble: 40,379 x 6
## book word n tf idf tf_idf
## <fct> <chr> <int> <dbl> <dbl> <dbl>
## 1 Sense & Sensibility elinor 623 0.00519 1.79 0.00931
## 2 Sense & Sensibility marianne 492 0.00410 1.79 0.00735
## 3 Mansfield Park crawford 493 0.00307 1.79 0.00551
## 4 Pride & Prejudice darcy 373 0.00305 1.79 0.00547
## 5 Persuasion elliot 254 0.00304 1.79 0.00544
## 6 Emma emma 786 0.00488 1.10 0.00536
## 7 Northanger Abbey tilney 196 0.00252 1.79 0.00452
## 8 Emma weston 389 0.00242 1.79 0.00433
## 9 Pride & Prejudice bennet 294 0.00241 1.79 0.00431
## 10 Persuasion wentworth 191 0.00228 1.79 0.00409
## # i 40,369 more rows
library(forcats)
book_tf_idf |>
group_by(book) |>
slice_max(tf_idf, n = 15) |>
ungroup() |>
ggplot(aes(tf_idf, fct_reorder(word, tf_idf), fill = book)) +
geom_col(show.legend = FALSE) +
facet_wrap(~book, ncol = 2, scales = "free") +
labs(x = "tf-idf", y = NULL)The most important terms in these novels are the names of people and places.
library(tidyverse)
library(tidytext)
library(stopwords)
library(textreadr)
fomc_2017 <- textreadr::read_docx("../Data/FOMC (04.2017).docx")
fomc_2020 <- textreadr::read_docx("../Data/FOMC (03.2020).docx")# single character
fomc_2017 <- paste(fomc_2017, collapse = ' ')
# put them in a tibble
fomc_2017 <- tibble(year=2017, text=fomc_2017)# tidy text: text data must be be one word in each row format
fomc_2017_tidy <- fomc_2017 |>
unnest_tokens(word, text) |>
filter(is.na(as.numeric(word))) # remove numbers# do the same for 2020
# single character
fomc_2020 <- paste(fomc_2020, collapse = ' ')
# put them in a tibble
fomc_2020 <- tibble(year=2020, text=fomc_2020)
# tidy text: text data must be be one word in each row format
fomc_2020_tidy <- fomc_2020 |>
unnest_tokens(word, text) |>
filter(is.na(as.numeric(word))) # remove numbersWe can also combine these two data set into single corpus:
## # A tibble: 355 x 2
## word n
## <chr> <int>
## 1 the 66
## 2 to 37
## 3 of 36
## 4 and 31
## 5 in 22
## 6 federal 21
## 7 market 16
## 8 committee 15
## 9 inflation 13
## 10 rate 13
## # i 345 more rows
## # A tibble: 309 x 2
## word n
## <chr> <int>
## 1 federal 21
## 2 market 16
## 3 committee 15
## 4 inflation 13
## 5 rate 13
## 6 open 10
## 7 percent 10
## 8 policy 10
## 9 securities 9
## 10 funds 8
## # i 299 more rows
# visualize top words in 2017
fomc_2017_tidy |>
# remove stop words
anti_join(get_stopwords()) |>
count(word, sort = TRUE) |>
slice_max(n, n = 20) |>
mutate(word = reorder(word, n)) |>
# put `n` on the x-axis and `word` on the y-axis
ggplot(aes(x = n, y = word)) +
geom_col()# visualize top words in 2020
fomc_2020_tidy |>
# remove stop words
anti_join(get_stopwords()) |>
count(word, sort = TRUE) |>
slice_max(n, n = 20) |>
mutate(word = reorder(word, n)) |>
# put `n` on the x-axis and `word` on the y-axis
ggplot(aes(x = n, y = word)) +
geom_col()# wordcloud
high_freq_terms <- fomc_2017_tidy |>
anti_join(get_stopwords()) |>
count(word, sort=TRUE)
library(wordcloud)
wordcloud(high_freq_terms$word,
high_freq_terms$n,
colors = c("red","goldenrod"),
scale = c(3,0.2))fomc_2017_tidy |>
anti_join(get_stopwords()) |>
count(word) |>
with(wordcloud(word, n, max.words = 500))# alternatively
library(ggwordcloud)
wordcloud_df <-fomc_2017_tidy |>
anti_join(get_stopwords()) |>
count(word, sort = T) |>
top_n(50)
wordcloud_df |>
ggplot() +
geom_text_wordcloud_area(aes(label = word, size = n)) +
scale_size_area(max_size = 15)Count the number of positive and negative words
library(ggwordcloud)
wordcloud_df_2017 <- fomc_2017_tidy |>
anti_join(get_stopwords()) |>
inner_join(get_sentiments("bing")) |>
count(sentiment, word, sort = T) |>
top_n(100)
wordcloud_df_2017## # A tibble: 19 x 3
## sentiment word n
## <chr> <chr> <int>
## 1 positive effective 3
## 2 negative debt 2
## 3 positive accommodative 2
## 4 negative limit 1
## 5 negative limited 1
## 6 negative risks 1
## 7 negative vice 1
## 8 positive appropriate 1
## 9 positive approve 1
## 10 positive available 1
## 11 positive balanced 1
## 12 positive consistent 1
## 13 positive facilitate 1
## 14 positive gains 1
## 15 positive solid 1
## 16 positive stability 1
## 17 positive stabilize 1
## 18 positive supporting 1
## 19 positive well 1
## # A tibble: 2 x 2
## sentiment n
## <chr> <int>
## 1 negative 5
## 2 positive 14
wordcloud_df_2017 |>
ggplot() +
geom_text_wordcloud_area(aes(label = word, size = n, color=sentiment)) +
scale_size_area(max_size = 15) +
labs(title = "2017")# 2020
wordcloud_df_2020 <-fomc_2020_tidy |>
anti_join(get_stopwords()) |>
inner_join(get_sentiments("bing")) |>
count(sentiment, word, sort = T) |>
top_n(100)
wordcloud_df_2020## # A tibble: 24 x 3
## sentiment word n
## <chr> <chr> <int>
## 1 positive support 6
## 2 positive effective 4
## 3 positive appropriate 3
## 4 positive smooth 3
## 5 negative limit 2
## 6 positive stability 2
## 7 negative challenging 1
## 8 negative crisis 1
## 9 negative debt 1
## 10 negative declines 1
## # i 14 more rows
wordcloud_df_2020 |>
ggplot() +
geom_text_wordcloud_area(aes(label = word, size = n, color=sentiment)) +
scale_size_area(max_size = 15) +
labs(title = "2020")Compared to 2017, we see new negative words in 2020 such as virus, hardship, crisis, and outbreak. The words support, effective, and stability are still important but support has the highest frequency.
Compare negative and positive words using comparison clouds:
library(wordcloud)
fomc_2017_tidy |>
inner_join(get_sentiments("bing")) |>
count(word, sentiment, sort = TRUE) |>
reshape2::acast(word ~ sentiment, value.var = "n", fill = 0) |>
comparison.cloud(colors = c("gray20", "gray80"),
max.words = 100)fomc_2020_tidy |>
inner_join(get_sentiments("bing")) |>
count(word, sentiment, sort = TRUE) |>
reshape2::acast(word ~ sentiment, value.var = "n", fill = 0) |>
comparison.cloud(colors = c("gray20", "gray80"),
max.words = 100)tf-idf analysis:
# count the frequency of each word
# and add total words in each document (year)
fomc_words <- fomc_tidy |>
add_count(year, name = "total_words") |>
group_by(year, total_words) |>
count(word, sort = TRUE) |>
ungroup()
#
fomc_words## # A tibble: 663 x 4
## year total_words word n
## <dbl> <int> <chr> <int>
## 1 2017 908 the 66
## 2 2020 804 the 65
## 3 2020 804 and 40
## 4 2017 908 to 37
## 5 2017 908 of 36
## 6 2020 804 to 35
## 7 2020 804 of 34
## 8 2017 908 and 31
## 9 2017 908 in 22
## 10 2017 908 federal 21
## # i 653 more rows
Inspect the distribution of n/total in
fomc_words:
ggplot(fomc_words) +
geom_histogram(aes(n / total_words, fill = year), show.legend = FALSE) +
facet_wrap(~ year, nrow = 1, scales = "free_y")Use tidytext::bind_tf_idf() function:
fomc_words_idf <- fomc_words |>
select(-total_words) |>
bind_tf_idf(term = word, document = year, n = n)
fomc_words_idf## # A tibble: 663 x 6
## year word n tf idf tf_idf
## <dbl> <chr> <int> <dbl> <dbl> <dbl>
## 1 2017 the 66 0.0727 0 0
## 2 2020 the 65 0.0808 0 0
## 3 2020 and 40 0.0498 0 0
## 4 2017 to 37 0.0407 0 0
## 5 2017 of 36 0.0396 0 0
## 6 2020 to 35 0.0435 0 0
## 7 2020 of 34 0.0423 0 0
## 8 2017 and 31 0.0341 0 0
## 9 2017 in 22 0.0242 0 0
## 10 2017 federal 21 0.0231 0 0
## # i 653 more rows
Notice that tf_idf is practically zero for the most
common words (such as the, and, to, of, etc.). We could remove these
stopwords before the analysis but here we kept them to demonstrate that
these will be essentially zero.
## # A tibble: 663 x 6
## year word n tf idf tf_idf
## <dbl> <chr> <int> <dbl> <dbl> <dbl>
## 1 2020 support 6 0.00746 0.693 0.00517
## 2 2020 mbs 4 0.00498 0.693 0.00345
## 3 2017 continued 4 0.00441 0.693 0.00305
## 4 2017 longer 4 0.00441 0.693 0.00305
## 5 2017 march 4 0.00441 0.693 0.00305
## 6 2020 agreement 3 0.00373 0.693 0.00259
## 7 2020 april 3 0.00373 0.693 0.00259
## 8 2020 cmbs 3 0.00373 0.693 0.00259
## 9 2020 economy 3 0.00373 0.693 0.00259
## 10 2020 functioning 3 0.00373 0.693 0.00259
## # i 653 more rows
library(forcats)
fomc_words_idf |>
group_by(year) |>
slice_max(tf_idf, n = 15) |>
ungroup() |>
ggplot(aes(tf_idf, fct_reorder(word, tf_idf), fill = year)) +
geom_col(show.legend = FALSE) +
facet_wrap(~ year, ncol = 2, scales = "free") +
labs(x = "tf-idf", y = NULL)