library(tm)
library(qdap)We have two Federal Open Market Committee statements in .docx format: one from April 2017 and one from March 2020 (right after the coronavirus outbreak). qdap::read_docx() function can be used to read them into R:
FOMC_2017 <- read_docx("FOMC (04.2017).docx")
FOMC_2017## [1] "Information received since the Federal Open Market Committee met in February indicates that the labor market has continued to strengthen and that economic activity has continued to expand at a moderate pace. Job gains remained solid and the unemployment rate was little changed in recent months. Household spending has continued to rise moderately while business fixed investment appears to have firmed somewhat. Inflation has increased in recent quarters, moving close to the Committee’s 2 percent longer-run objective; excluding energy and food prices, inflation was little changed and continued to run somewhat below 2 percent."
## [2] "Market-based measures of inflation compensation remain low; survey-based measures of longer- term inflation expectations are little changed, on balance."
## [3] "Consistent with its statutory mandate, the Committee seeks to foster maximum employment and price stability. The Committee expects that, with gradual adjustments in the stance of monetary policy, economic activity will expand at a moderate pace, labor market conditions will strengthen somewhat further, and inflation will stabilize around 2 percent over the medium term. Near-term risks to the economic outlook appear roughly balanced. The Committee continues to closely monitor inflation indicators and global economic and financial developments."
## [4] "In view of realized and expected labor market conditions and inflation, the Committee decided to raise the target range for the federal funds rate to 3/4 to 1 percent. The stance of monetary policy remains accommodative, thereby supporting some further strengthening in labor market conditions and a sustained return to 2 percent inflation."
## [5] "In determining the timing and size of future adjustments to the target range for the federal funds rate, the Committee will assess realized and expected economic conditions relative to its objectives of maximum employment and 2 percent inflation. This assessment will take into account a wide range of information, including measures of labor market conditions, indicators"
## [6] "(more)"
## [7] " "
## [8] "- 2 -"
## [9] "of inflation pressures and inflation expectations, and readings on financial and international developments. The Committee will carefully monitor actual and expected inflation developments relative to its symmetric inflation goal. The Committee expects that economic conditions will evolve in a manner that will warrant gradual increases in the federal funds rate; the federal funds rate is likely to remain, for some time, below levels that are expected to prevail in the longer run. However, the actual path of the federal funds rate will depend on the economic outlook as informed by incoming data."
## [10] "The Committee is maintaining its existing policy of reinvesting principal payments from its holdings of agency debt and agency mortgage-backed securities in agency mortgage-backed securities and of rolling over maturing Treasury securities at auction, and it anticipates doing so until normalization of the level of the federal funds rate is well under way. This policy, by keeping the Committee’s holdings of longer-term securities at sizable levels, should help maintain accommodative financial conditions."
## [11] "Voting for the FOMC monetary policy action were: Janet L. Yellen, Chair; William C. Dudley, Vice Chairman; Lael Brainard; Charles L. Evans; Stanley Fischer; Patrick Harker; Robert S. Kaplan; Jerome H. Powell; and Daniel K. Tarullo. Voting against the action was Neel Kashkari, who preferred at this meeting to maintain the existing target range for the federal funds rate."
## [12] "- 0 -"
## [13] " "
## [14] "Decisions Regarding Monetary Policy Implementation"
## [15] "The Federal Reserve has made the following decisions to implement the monetary policy stance announced by the Federal Open Market Committee in its statement on March 15, 2017:"
## [16] "•The Board of Governors of the Federal Reserve System voted unanimously to raise the interest rate paid on required and excess reserve balances to 1.00 percent, effective March 16, 2017."
## [17] "•As part of its policy decision, the Federal Open Market Committee voted to authorize and direct the Open Market Desk at the Federal Reserve Bank of New York, until instructed otherwise, to execute transactions in the System Open Market Account in accordance with the following domestic policy directive:"
## [18] "\"Effective March 16, 2017, the Federal Open Market Committee directs the Desk to undertake open market operations as necessary to maintain the federal funds rate in a target range of 3/4 to 1 percent, including overnight reverse repurchase operations (and reverse repurchase operations with maturities of more than one day when necessary to accommodate weekend, holiday, or similar trading conventions) at an offering rate of 0.75 percent, in amounts limited only by the value of Treasury securities held outright in the System Open Market Account that are available for such operations and by a per-counterparty limit of"
## [19] "$30 billion per day."
## [20] "The Committee directs the Desk to continue rolling over maturing Treasury securities at auction and to continue reinvesting principal payments on all agency debt and agency mortgage-backed securities in agency mortgage-backed securities. The Committee also directs the Desk to engage in dollar roll and coupon swap transactions as necessary to facilitate settlement of the Federal Reserve’s agency mortgage-backed securities transactions.\""
## [21] "More information regarding open market operations may be found on the Federal Reserve Bank of New York’s website."
## [22] "•In a related action, the Board of Governors of the Federal Reserve System voted unanimously to approve a 1/4 percentage point increase in the primary credit rate to 1.50 percent, effective March 16, 2017. In taking this action, the Board approved requests to establish that rate submitted by the Boards of Directors of the Federal Reserve Banks of Boston, Philadelphia, Cleveland, Richmond, Atlanta, Chicago, Kansas City, Dallas, and San Francisco."
## [23] "This information will be updated as appropriate to reflect decisions of the Federal Open Market Committee or the Board of Governors regarding details of the Federal Reserve’s operational tools and approach used to implement monetary policy."
Notice that each paragraph in the document is a distinct element of the character vector FOMC_2017. It needs to be a character vector with a single element which contains the whole text:
FOMC_2017 <- paste(FOMC_2017, collapse = ' ')
FOMC_2017## [1] "Information received since the Federal Open Market Committee met in February indicates that the labor market has continued to strengthen and that economic activity has continued to expand at a moderate pace. Job gains remained solid and the unemployment rate was little changed in recent months. Household spending has continued to rise moderately while business fixed investment appears to have firmed somewhat. Inflation has increased in recent quarters, moving close to the Committee’s 2 percent longer-run objective; excluding energy and food prices, inflation was little changed and continued to run somewhat below 2 percent. Market-based measures of inflation compensation remain low; survey-based measures of longer- term inflation expectations are little changed, on balance. Consistent with its statutory mandate, the Committee seeks to foster maximum employment and price stability. The Committee expects that, with gradual adjustments in the stance of monetary policy, economic activity will expand at a moderate pace, labor market conditions will strengthen somewhat further, and inflation will stabilize around 2 percent over the medium term. Near-term risks to the economic outlook appear roughly balanced. The Committee continues to closely monitor inflation indicators and global economic and financial developments. In view of realized and expected labor market conditions and inflation, the Committee decided to raise the target range for the federal funds rate to 3/4 to 1 percent. The stance of monetary policy remains accommodative, thereby supporting some further strengthening in labor market conditions and a sustained return to 2 percent inflation. In determining the timing and size of future adjustments to the target range for the federal funds rate, the Committee will assess realized and expected economic conditions relative to its objectives of maximum employment and 2 percent inflation. This assessment will take into account a wide range of information, including measures of labor market conditions, indicators (more) - 2 - of inflation pressures and inflation expectations, and readings on financial and international developments. The Committee will carefully monitor actual and expected inflation developments relative to its symmetric inflation goal. The Committee expects that economic conditions will evolve in a manner that will warrant gradual increases in the federal funds rate; the federal funds rate is likely to remain, for some time, below levels that are expected to prevail in the longer run. However, the actual path of the federal funds rate will depend on the economic outlook as informed by incoming data. The Committee is maintaining its existing policy of reinvesting principal payments from its holdings of agency debt and agency mortgage-backed securities in agency mortgage-backed securities and of rolling over maturing Treasury securities at auction, and it anticipates doing so until normalization of the level of the federal funds rate is well under way. This policy, by keeping the Committee’s holdings of longer-term securities at sizable levels, should help maintain accommodative financial conditions. Voting for the FOMC monetary policy action were: Janet L. Yellen, Chair; William C. Dudley, Vice Chairman; Lael Brainard; Charles L. Evans; Stanley Fischer; Patrick Harker; Robert S. Kaplan; Jerome H. Powell; and Daniel K. Tarullo. Voting against the action was Neel Kashkari, who preferred at this meeting to maintain the existing target range for the federal funds rate. - 0 - Decisions Regarding Monetary Policy Implementation The Federal Reserve has made the following decisions to implement the monetary policy stance announced by the Federal Open Market Committee in its statement on March 15, 2017: •The Board of Governors of the Federal Reserve System voted unanimously to raise the interest rate paid on required and excess reserve balances to 1.00 percent, effective March 16, 2017. •As part of its policy decision, the Federal Open Market Committee voted to authorize and direct the Open Market Desk at the Federal Reserve Bank of New York, until instructed otherwise, to execute transactions in the System Open Market Account in accordance with the following domestic policy directive: \"Effective March 16, 2017, the Federal Open Market Committee directs the Desk to undertake open market operations as necessary to maintain the federal funds rate in a target range of 3/4 to 1 percent, including overnight reverse repurchase operations (and reverse repurchase operations with maturities of more than one day when necessary to accommodate weekend, holiday, or similar trading conventions) at an offering rate of 0.75 percent, in amounts limited only by the value of Treasury securities held outright in the System Open Market Account that are available for such operations and by a per-counterparty limit of $30 billion per day. The Committee directs the Desk to continue rolling over maturing Treasury securities at auction and to continue reinvesting principal payments on all agency debt and agency mortgage-backed securities in agency mortgage-backed securities. The Committee also directs the Desk to engage in dollar roll and coupon swap transactions as necessary to facilitate settlement of the Federal Reserve’s agency mortgage-backed securities transactions.\" More information regarding open market operations may be found on the Federal Reserve Bank of New York’s website. •In a related action, the Board of Governors of the Federal Reserve System voted unanimously to approve a 1/4 percentage point increase in the primary credit rate to 1.50 percent, effective March 16, 2017. In taking this action, the Board approved requests to establish that rate submitted by the Boards of Directors of the Federal Reserve Banks of Boston, Philadelphia, Cleveland, Richmond, Atlanta, Chicago, Kansas City, Dallas, and San Francisco. This information will be updated as appropriate to reflect decisions of the Federal Open Market Committee or the Board of Governors regarding details of the Federal Reserve’s operational tools and approach used to implement monetary policy."
Below we calculate the top 5 most frequent words with the qdap::freq_terms() function:
freq.terms <- freq_terms(FOMC_2017, 5)
freq.terms## WORD FREQ
## 1 the 66
## 2 to 37
## 3 of 36
## 4 and 31
## 5 in 22
Not surprisingly, the frequently used terms consist of prepositions, pronouns etc., which convey no useful information. When analyzing text data, we need to get rid of unnecessary words so that we are left with proper nouns and the like, which are of primary interest. To do that, we can use tm::stopwords().
freq.terms.2 <- freq_terms(FOMC_2017, 5, stopwords = stopwords("en"))
freq.terms.2## WORD FREQ
## 1 federal 21
## 2 committee 15
## 3 market 15
## 4 inflation 13
## 5 rate 13
Below are the English stopwords:
stopwords("en")## [1] "i" "me" "my" "myself" "we"
## [6] "our" "ours" "ourselves" "you" "your"
## [11] "yours" "yourself" "yourselves" "he" "him"
## [16] "his" "himself" "she" "her" "hers"
## [21] "herself" "it" "its" "itself" "they"
## [26] "them" "their" "theirs" "themselves" "what"
## [31] "which" "who" "whom" "this" "that"
## [36] "these" "those" "am" "is" "are"
## [41] "was" "were" "be" "been" "being"
## [46] "have" "has" "had" "having" "do"
## [51] "does" "did" "doing" "would" "should"
## [56] "could" "ought" "i'm" "you're" "he's"
## [61] "she's" "it's" "we're" "they're" "i've"
## [66] "you've" "we've" "they've" "i'd" "you'd"
## [71] "he'd" "she'd" "we'd" "they'd" "i'll"
## [76] "you'll" "he'll" "she'll" "we'll" "they'll"
## [81] "isn't" "aren't" "wasn't" "weren't" "hasn't"
## [86] "haven't" "hadn't" "doesn't" "don't" "didn't"
## [91] "won't" "wouldn't" "shan't" "shouldn't" "can't"
## [96] "cannot" "couldn't" "mustn't" "let's" "that's"
## [101] "who's" "what's" "here's" "there's" "when's"
## [106] "where's" "why's" "how's" "a" "an"
## [111] "the" "and" "but" "if" "or"
## [116] "because" "as" "until" "while" "of"
## [121] "at" "by" "for" "with" "about"
## [126] "against" "between" "into" "through" "during"
## [131] "before" "after" "above" "below" "to"
## [136] "from" "up" "down" "in" "out"
## [141] "on" "off" "over" "under" "again"
## [146] "further" "then" "once" "here" "there"
## [151] "when" "where" "why" "how" "all"
## [156] "any" "both" "each" "few" "more"
## [161] "most" "other" "some" "such" "no"
## [166] "nor" "not" "only" "own" "same"
## [171] "so" "than" "too" "very"
Now we can import FOMC_2020 and combine it with FOMC_2017:
FOMC_2020 <- read_docx("FOMC (03.2020).docx")
FOMC_2020 <- paste(FOMC_2020, collapse = ' ')
corpus <- c(FOMC_2017, FOMC_2020)
str(corpus)## chr [1:2] "Information received since the Federal Open Market Committee met in February indicates that the labor market ha"| __truncated__ ...
The corpus object is not a corpus yet, it is just a character vector with length 2.
There are two corpus types: permanent corpus, PCorpus and volatile corpus, VCorpus. The difference essentially lies in where the data is stored on the computer. VCorpus objects use the computer’s RAM, which makes them more efficient to work with. Before building a corpus, the source of our documents needs to be specified (in this case they are stored in a vector). tm::VectorSource() function can be used for that purpose:
source <- VectorSource(corpus) #specify the source
FOMC <- VCorpus(source) #create a VCorpus object
str(FOMC)## List of 2
## $ 1:List of 2
## ..$ content: chr "Information received since the Federal Open Market Committee met in February indicates that the labor market ha"| __truncated__
## ..$ meta :List of 7
## .. ..$ author : chr(0)
## .. ..$ datetimestamp: POSIXlt[1:1], format: "2022-05-24 12:50:27"
## .. ..$ description : chr(0)
## .. ..$ heading : chr(0)
## .. ..$ id : chr "1"
## .. ..$ language : chr "en"
## .. ..$ origin : chr(0)
## .. ..- attr(*, "class")= chr "TextDocumentMeta"
## ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"
## $ 2:List of 2
## ..$ content: chr "The Federal Reserve is committed to using its full range of tools to support the U.S. economy in this challengi"| __truncated__
## ..$ meta :List of 7
## .. ..$ author : chr(0)
## .. ..$ datetimestamp: POSIXlt[1:1], format: "2022-05-24 12:50:27"
## .. ..$ description : chr(0)
## .. ..$ heading : chr(0)
## .. ..$ id : chr "2"
## .. ..$ language : chr "en"
## .. ..$ origin : chr(0)
## .. ..- attr(*, "class")= chr "TextDocumentMeta"
## ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"
## - attr(*, "class")= chr [1:2] "VCorpus" "Corpus"
VectorSource() basically identifies the source of the documents, so that when we create a corpus object, the function VCorpus() treats each element in the corpus vector as separate documents. Thus, the resulting corpus has two documents. We can reach out to the content of a particular document:
FOMC[[2]]$content## [1] "The Federal Reserve is committed to using its full range of tools to support the U.S. economy in this challenging time, thereby promoting its maximum employment and price stability goals. The coronavirus outbreak is causing tremendous human and economic hardship across the United States and around the world. The virus and the measures taken to protect public health are inducing sharp declines in economic activity and a surge in job losses. Weaker demand and significantly lower oil prices are holding down consumer price inflation. The disruptions to economic activity here and abroad have significantly affected financial conditions and have impaired the flow of credit to U.S. households and businesses. The ongoing public health crisis will weigh heavily on economic activity, employment, and inflation in the near term, and poses considerable risks to the economic outlook over the medium term. In light of these developments, the Committee decided to maintain the target range for the federal funds rate at 0 to 1/4 percent. The Committee expects to maintain this target range until it is confident that the economy has weathered recent events and is on track to achieve its maximum employment and price stability goals. The Committee will continue to monitor the implications of incoming information for the economic outlook, including information related to public health, as well as global developments and muted inflation pressures, and will use its tools and act as appropriate to support the economy. In determining the timing and size of future adjustments to the stance of monetary policy, the Committee will assess realized and expected economic conditions relative to its maximum employment objective and its symmetric 2 percent - 2 - inflation objective. This assessment will take into account a wide range of information, including measures of labor market conditions, indicators of inflation pressures and inflation expectations, and readings on financial and international developments. To support the flow of credit to households and businesses, the Federal Reserve will continue to purchase Treasury securities and agency residential and commercial mortgage-backed securities in the amounts needed to support smooth market functioning, thereby fostering effective transmission of monetary policy to broader financial conditions. In addition, the Open Market Desk will continue to offer large-scale overnight and term repurchase agreement operations. The Committee will closely monitor market conditions and is prepared to adjust its plans as appropriate. Voting for the monetary policy action were Jerome H. Powell, Chair; John C. Williams, Vice Chair; Michelle W. Bowman; Lael Brainard; Richard H. Clarida; Patrick Harker; Robert S. Kaplan; Neel Kashkari; Loretta J. Mester; and Randal K. Quarles. - 0 - Decisions Regarding Monetary Policy Implementation The Federal Reserve has made the following decisions to implement the monetary policy stance announced by the Federal Open Market Committee in its statement on April 29, 2020: •The Board of Governors of the Federal Reserve System voted unanimously to maintain the interest rate paid on required and excess reserve balances at 0.10 percent, effective April 30, 2020. •As part of its policy decision, the Federal Open Market Committee voted to authorize and direct the Open Market Desk at the Federal Reserve Bank of New York, until instructed otherwise, to execute transactions in the System Open Market Account in accordance with the following domestic policy directive: “Effective April 30, 2020, the Federal Open Market Committee directs the Desk to: oUndertake open market operations as necessary to maintain the federal funds rate in a target range of 0 to 1/4 percent. oIncrease the System Open Market Account holdings of Treasury securities, agency mortgage-backed securities (MBS), and agency commercial mortgage-backed securities (CMBS) in the amounts needed to support the smooth functioning of markets for these securities. oConduct term and overnight repurchase agreement operations to support effective policy implementation and the smooth functioning of short-term U.S. dollar funding markets. oConduct overnight reverse repurchase agreement operations at an offering rate of 0.00 percent and with a per-counterparty limit of $30 billion per day; the per-counterparty limit can be temporarily increased at the discretion of the Chair. oRoll over at auction all principal payments from the Federal Reserve's holdings of Treasury securities and reinvest all principal payments from the Federal Reserve's holdings of agency debt and agency MBS in agency MBS and all principal payments from holdings of agency CMBS in agency CMBS. oEngage in dollar roll and coupon swap transactions as necessary to facilitate settlement of the Federal Reserve's agency MBS transactions.” •In a related action, the Board of Governors of the Federal Reserve System voted unanimously to approve the establishment of the primary credit rate at the existing level of 0.25 percent. - 2 - This information will be updated as appropriate to reflect decisions of the Federal Open Market Committee or the Board of Governors regarding details of the Federal Reserve’s operational tools and approach used to implement monetary policy. More information regarding open market operations and reinvestments may be found on the Federal Reserve Bank of New York’s website. - 0 -"
We can now create the Term-Document Matrix (TDM), which has words (terms) in its rows and documents in its columns. We can obtain the TDM using tm::TermDocumentMatrix():
tdm <- TermDocumentMatrix(FOMC)
tdm <- as.matrix(tdm)
colnames(tdm) <- c("2017", "2020")
head(tdm) ## Docs
## Terms 2017 2020
## "effective 1 0
## “effective 0 1
## (and 1 0
## (cmbs) 0 1
## (mbs), 0 1
## (more) 1 0
Notice that there are punctuations in some terms, which may cause problems. For example, if not preceded by a dash, “inflation” will not be treated the same as “-inflation”. The text should be cleaned and preprocessed before conducting any analysis.
The tm package provides several tools for cleaning, such as removeWords(), removeNumbers(), removePunctuation() and stripWhitespace(). Each performs what their names suggest: the first one removes words (based on some predefined rule), the second numbers, the third punctuations and the fourth excess white space. We can also use base::tolower() to make all characters lowercase. Let’s create a function that takes a corpus and implements some of these transformations. To apply them to each document in the corpus, we need the tm_map()function:
clean_corpus <- function(corpus){
corpus <- tm_map(corpus, content_transformer(tolower))
corpus <- tm_map(corpus, removeNumbers)
corpus <- tm_map(corpus, removePunctuation, ucp = T)
corpus <- tm_map(corpus, removeWords, c(stopwords("en"),
"federal", "open", "market", "committee"))
}
# tolower() is not a part of the tm library, has to be
## applied with tm::content_transformer()
# the order of transformations is important
# it makes sense to remove the words "federal", "open", "market" and "committee
## along with English stopwords
FOMC_clean <- clean_corpus(FOMC)
str(FOMC_clean)## List of 2
## $ 1:List of 2
## ..$ content: chr "information received since met february indicates labor continued strengthen economic activity co"| __truncated__
## ..$ meta :List of 7
## .. ..$ author : chr(0)
## .. ..$ datetimestamp: POSIXlt[1:1], format: "2022-05-24 12:50:27"
## .. ..$ description : chr(0)
## .. ..$ heading : chr(0)
## .. ..$ id : chr "1"
## .. ..$ language : chr "en"
## .. ..$ origin : chr(0)
## .. ..- attr(*, "class")= chr "TextDocumentMeta"
## ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"
## $ 2:List of 2
## ..$ content: chr " reserve committed using full range tools support us economy challenging time thereby promoting maxim"| __truncated__
## ..$ meta :List of 7
## .. ..$ author : chr(0)
## .. ..$ datetimestamp: POSIXlt[1:1], format: "2022-05-24 12:50:27"
## .. ..$ description : chr(0)
## .. ..$ heading : chr(0)
## .. ..$ id : chr "2"
## .. ..$ language : chr "en"
## .. ..$ origin : chr(0)
## .. ..- attr(*, "class")= chr "TextDocumentMeta"
## ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"
## - attr(*, "class")= chr [1:2] "VCorpus" "Corpus"
The content in each document has been transformed accordingly. Let’s create the TDM:
clean.tdm <- TermDocumentMatrix(FOMC_clean)
clean.tdm <- as.matrix(clean.tdm)
colnames(clean.tdm) <- c("2017", "2020")
head(clean.tdm)## Docs
## Terms 2017 2020
## abroad 0 1
## accommodate 1 0
## accommodative 2 0
## accordance 1 1
## account 3 3
## achieve 0 1
To inspect specific terms in the TDM:
clean.tdm["inflation", ]## 2017 2020
## 13 6
Another essential preprocessing step in text mining is word stemming and stem completion. Suppose we have the following words:
inc <- c("increased", "increasing", "increasingly")If we stem these words with tm::stemDocument():
inc <- stemDocument(inc)
inc## [1] "increas" "increas" "increas"
What word stemming does is that it unifies the words that share the same root. However, the resulting word is not meaningful. Clearly, we should replace all of them with “increase”. tm::stemCompletion does exactly that. It takes a character vector and a completion dictionary:
stemcomp <- "increase"
inc <- stemCompletion(inc, stemcomp)
inc## increas increas increas
## "increase" "increase" "increase"
dim(clean.tdm)## [1] 404 2
There are 407 distinct terms in the TDM. In practice, this number can be much larger, which will make it quite difficult to inspect the TDM term-by-term. Instead, we can create some informative visualizations. Let’s say we are interested in the most frequent words used in both documents. Recall that the TDM has in its rows all the terms and their corresponding frequencies in each document. All we have to do is to take the sum of the rows. We can then create a bar plot of the top 10 most frequent words:
highfreqterms <- rowSums(clean.tdm)
highfreqterms <- sort(highfreqterms, decreasing = TRUE)
barplot(highfreqterms[1:10], col ="blue", las = 2)A more popular visualization method is word cloud, which requires the wordcloud library. In a word cloud, the size of a word is relative to its frequency.
library(wordcloud)
term_vec <- names(highfreqterms)
wordcloud(term_vec, highfreqterms, colors = c("red","goldenrod"), scale = c(3,0.2))## Warning in wordcloud(term_vec, highfreqterms, colors = c("red", "goldenrod"), :
## monetary could not be fit on page. It will not be plotted.
We can also plot a comparison cloud, which is simply a word cloud that visualizes dissimilar words across documents:
comparison.cloud(clean.tdm, colors = c("orange", "blue"), scale = c(2, 0.2), title.size = 2)Notice how the focus shifts from “inflation” to “support”.
A commonality cloud visualizes shared terms across documents:
commonality.cloud(clean.tdm, scale = c(2.5, 0.2))Sometimes it would be better to focus on a group of words rather than one word. Words can have substantially different connotations when combined. For example, if our document involves something like “not beautiful”, then treating the words separately (as unigrams) may not be a good idea. We may not want to tokenize each term, but to make a bigram tokenization. This can be achieved by using the RWeka::NGramTokenizer() function:
library(RWeka)
tokenizer <- function(x) {
NGramTokenizer(x, Weka_control(min=2, max=2))
}
bigram_tdm <- TermDocumentMatrix(FOMC_clean, control = list(tokenize = tokenizer))
bigram_tdm <- as.matrix(bigram_tdm)
head(bigram_tdm)## Docs
## Terms 1 2
## $ billion 1 1
## abroad significantly 0 1
## accommodate weekend 1 0
## accommodative financial 1 0
## accommodative thereby 1 0
## accordance following 1 1
Suppose that we have a large corpus containing several documents, but a word appears in each document in a non-random fashion. For example, if we want to examine a set of tweets on US-China affairs, then it is highly likely that the most frequently used terms across the documents in our corpus would be “US” and “China”, which, by themselves, contain no information. This is where Tf-Idf, short for Term Frequency-Inverse Document Frequency, becomes useful. It is a weighting criterion to be implemented when creating TDMs, which basically imposes a penalty for terms that consistently appear in multiple documents. To implement a Tf-Idf weighting, we can add a control parameter just as we did for bigram tokenization:
tfidf <- TermDocumentMatrix(FOMC_clean, control = list(weighting=weightTfIdf))
tfidf <- as.matrix(tfidf)
head(tfidf)## Docs
## Terms 1 2
## abroad 0.000000000 0.002145923
## accommodate 0.001912046 0.000000000
## accommodative 0.003824092 0.000000000
## accordance 0.000000000 0.000000000
## account 0.000000000 0.000000000
## achieve 0.000000000 0.002145923
We can compare this to the initial TDM:
head(clean.tdm)## Docs
## Terms 2017 2020
## abroad 0 1
## accommodate 1 0
## accommodative 2 0
## accordance 1 1
## account 3 3
## achieve 0 1
highfreqterms2 <- rowSums(tfidf)
highfreqterms2 <- sort(highfreqterms2, decreasing = TRUE)
barplot(highfreqterms2[1:10], col ="blue", las = 2)term_vec2 <- names(highfreqterms2)
wordcloud(term_vec2, highfreqterms2, colors = c("red","goldenrod"), scale = c(2.5, 0.2))Although English versions of the CBRT Monetary Policy Committee statements are available, we will use the Turkish versions for illustrative purposes.
The FOMC statements were in .docx format, but CBRT Monetary Policy Committee statements are in .pdf format. We can also read pdf files into R. The code chunk below reads one of the MPC statements using tm::readPDF() and creates a VCorpus. Notice that there is another control parameter, language = "turkish", since the text is in Turkish.
PPK_2016 <- VCorpus(URISource("PPK (04.2016).pdf"), readerControl =
list(reader = readPDF, language = "turkish" ))
str(PPK_2016)## List of 1
## $ PPK (04.2016).pdf:List of 2
## ..$ content: chr [1:6] " Sayı: 2016-21\nBASIN DUYURUSU\n26"| __truncated__ "5. Özetle, enflasyon yakın dönemde belirgin bir düşüş sergilemiştir. Temelde işlenmemiş\n gıda kaynaklı gerç"| __truncated__ "10. 2016 yılı Ocak döneminde mevsimsellikten arındırılmış işsizlik oranları bir önceki\n döneme göre gerilem"| __truncated__ " Birliği ülkelerinin talebindeki artışın ihracatı olumlu yönde etkilemeye devam edeceği\n öngörülmektedir"| __truncated__ ...
## ..$ meta :List of 7
## .. ..$ author : chr ""
## .. ..$ datetimestamp: POSIXct[1:1], format: "2016-04-26 13:36:09"
## .. ..$ description : chr ""
## .. ..$ heading : chr "DUY2016-21"
## .. ..$ id : chr "PPK (04.2016).pdf"
## .. ..$ language : chr "turkish"
## .. ..$ origin : chr "PDFCreator Version 1.5.0"
## .. ..- attr(*, "class")= chr "TextDocumentMeta"
## ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"
## - attr(*, "class")= chr [1:2] "VCorpus" "Corpus"
Alternatively, we can use the tabulizer::extract_text() function:
library(tabulizer)
PPK_2016_2 <- extract_text("PPK (04.2016).pdf")
PPK_2016_2 <- VCorpus(VectorSource(PPK_2016),
readerControl = list (language = "turkish"))
str(PPK_2016_2)## List of 1
## $ 1:List of 2
## ..$ content: chr [1:6] " Sayı: 2016-21\nBASIN DUYURUSU\n26"| __truncated__ "5. Özetle, enflasyon yakın dönemde belirgin bir düşüş sergilemiştir. Temelde işlenmemiş\n gıda kaynaklı gerç"| __truncated__ "10. 2016 yılı Ocak döneminde mevsimsellikten arındırılmış işsizlik oranları bir önceki\n döneme göre gerilem"| __truncated__ " Birliği ülkelerinin talebindeki artışın ihracatı olumlu yönde etkilemeye devam edeceği\n öngörülmektedir"| __truncated__ ...
## ..$ meta :List of 7
## .. ..$ author : chr(0)
## .. ..$ datetimestamp: POSIXlt[1:1], format: "2022-05-24 12:50:37"
## .. ..$ description : chr(0)
## .. ..$ heading : chr(0)
## .. ..$ id : chr "1"
## .. ..$ language : chr "turkish"
## .. ..$ origin : chr(0)
## .. ..- attr(*, "class")= chr "TextDocumentMeta"
## ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"
## - attr(*, "class")= chr [1:2] "VCorpus" "Corpus"
We may also want to read multiple pdf documents into R at once. When the number of documents is very large, reading them one by one can be excruciating. We can simply use the list.files() function from base R and then specify the source of our documents with tm::URISource() (Uniform Resource Identifier). For example:
(files <- list.files(pattern = "pdf$"))## [1] "PPK (04.2016).pdf" "PPK (04.2020).pdf"
# It creates a list from the names of the files in the working directory
# $ specifies the end of the file nameThen we can create a corpus:
PPK <- VCorpus(URISource(files), readerControl =
list(reader = readPDF, language = "turkish" ))
str(PPK)## List of 2
## $ PPK (04.2016).pdf:List of 2
## ..$ content: chr [1:6] " Sayı: 2016-21\nBASIN DUYURUSU\n26"| __truncated__ "5. Özetle, enflasyon yakın dönemde belirgin bir düşüş sergilemiştir. Temelde işlenmemiş\n gıda kaynaklı gerç"| __truncated__ "10. 2016 yılı Ocak döneminde mevsimsellikten arındırılmış işsizlik oranları bir önceki\n döneme göre gerilem"| __truncated__ " Birliği ülkelerinin talebindeki artışın ihracatı olumlu yönde etkilemeye devam edeceği\n öngörülmektedir"| __truncated__ ...
## ..$ meta :List of 7
## .. ..$ author : chr ""
## .. ..$ datetimestamp: POSIXct[1:1], format: "2016-04-26 13:36:09"
## .. ..$ description : chr ""
## .. ..$ heading : chr "DUY2016-21"
## .. ..$ id : chr "PPK (04.2016).pdf"
## .. ..$ language : chr "turkish"
## .. ..$ origin : chr "PDFCreator Version 1.5.0"
## .. ..- attr(*, "class")= chr "TextDocumentMeta"
## ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"
## $ PPK (04.2020).pdf:List of 2
## ..$ content: chr [1:4] "" "" "" ""
## ..$ meta :List of 7
## .. ..$ author : NULL
## .. ..$ datetimestamp: POSIXct[1:1], format: "2106-02-07 09:28:15"
## .. ..$ description : NULL
## .. ..$ heading : chr "DUY2020-26"
## .. ..$ id : chr "PPK (04.2020).pdf"
## .. ..$ language : chr "turkish"
## .. ..$ origin : NULL
## .. ..- attr(*, "class")= chr "TextDocumentMeta"
## ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"
## - attr(*, "class")= chr [1:2] "VCorpus" "Corpus"
The steps for cleaning and preprocessing is as usual. However, stopwords for the Turkish language is not available in the tm library. We will need the stopwords package:
library(stopwords)
stopwords = stopwords("turkish", source = "stopwords-iso")
head(stopwords)## [1] "acaba" "acep" "açıkça" "açıkçası" "adamakıllı"
## [6] "adeta"
length(stopwords)## [1] 471
We can now apply the usual transformations:
clean.new.corpus <- function(corpus){
corpus <- tm_map(corpus, content_transformer(tolower))
corpus <- tm_map(corpus, removeWords, stopwords)
corpus <- tm_map(corpus, removeNumbers)
corpus <- tm_map(corpus, removePunctuation, ucp = TRUE)
#use unicode character properties to identify punctuations
corpus <- tm_map(corpus, stripWhitespace)
}
PPK_clean <- clean.new.corpus(PPK)
str(PPK_clean)## List of 2
## $ PPK (04.2016).pdf:List of 2
## ..$ content: chr [1:6] " sayı basin duyurusu nisan para politikasi kurulu toplanti özeti toplantı tarihi nisan enflasyon gelişmeleri ma"| __truncated__ " özetle enflasyon yakın dönemde belirgin düşüş sergilemiştir temelde işlenmemiş gıda kaynaklı gerçekleşen düşüş"| __truncated__ " yılı ocak döneminde mevsimsellikten arındırılmış işsizlik oranları önceki döneme gerilemiştir gelişmede tarım "| __truncated__ " birliği ülkelerinin talebindeki artışın ihracatı olumlu yönde etkilemeye devam edeceği öngörülmektedir yurt iç"| __truncated__ ...
## ..$ meta :List of 7
## .. ..$ author : chr ""
## .. ..$ datetimestamp: POSIXct[1:1], format: "2016-04-26 13:36:09"
## .. ..$ description : chr ""
## .. ..$ heading : chr "DUY2016-21"
## .. ..$ id : chr "PPK (04.2016).pdf"
## .. ..$ language : chr "turkish"
## .. ..$ origin : chr "PDFCreator Version 1.5.0"
## .. ..- attr(*, "class")= chr "TextDocumentMeta"
## ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"
## $ PPK (04.2020).pdf:List of 2
## ..$ content: chr [1:4] "" "" "" ""
## ..$ meta :List of 7
## .. ..$ author : NULL
## .. ..$ datetimestamp: POSIXct[1:1], format: "2106-02-07 09:28:15"
## .. ..$ description : NULL
## .. ..$ heading : chr "DUY2020-26"
## .. ..$ id : chr "PPK (04.2020).pdf"
## .. ..$ language : chr "turkish"
## .. ..$ origin : NULL
## .. ..- attr(*, "class")= chr "TextDocumentMeta"
## ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"
## - attr(*, "class")= chr [1:2] "VCorpus" "Corpus"
Take a closer look at the content of the second document. It seems that it does not contain any textual element. If you pull out the content:
PPK_clean[[2]]$content## [1] "" "" "" ""
This particular pdf document is a four-pages-long text but in the corpus it has 4 empty character strings. tm::readPDF() fails to read it is since the pdf document is nonsearchable (i.e., an image). Fortunately, there is a way to extract text from such files. We can use tesseract::ocr() for optical character recognition from images. We should first convert the pdf document to an image format (preferably .png) using pdftools::pdf_convert(). The function converts each page in a pdf file to a specified image format:
library(pdftools)
png <- pdf_convert("PPK (04.2020).pdf", format = "png", dpi = 300)## Converting page 1 to PPK (04.2020)_1.png... done!
## Converting page 2 to PPK (04.2020)_2.png... done!
## Converting page 3 to PPK (04.2020)_3.png... done!
## Converting page 4 to PPK (04.2020)_4.png... done!
Now that each page is converted to .png, we are ready to perform optical character recognition. Luckily, tesseract provides an engine that recognizes special Turkish characters.
library(tesseract)
PPK_2020 <- ocr(png, engine = tesseract("tur"))
str(PPK_2020)## chr [1:4] "ye\na Z / (UT TÜRKİYE CUMHURİYET\n1 777 ( B MERKEZ BANKASI\nSi\n\n30 Nisan 2020, Sayı: 2020-26\n\nToplantı Tari"| __truncated__ ...
Then simply replace the content of the document:
PPK_clean[[2]]$content <- PPK_2020
str(PPK_clean)## List of 2
## $ PPK (04.2016).pdf:List of 2
## ..$ content: chr [1:6] " sayı basin duyurusu nisan para politikasi kurulu toplanti özeti toplantı tarihi nisan enflasyon gelişmeleri ma"| __truncated__ " özetle enflasyon yakın dönemde belirgin düşüş sergilemiştir temelde işlenmemiş gıda kaynaklı gerçekleşen düşüş"| __truncated__ " yılı ocak döneminde mevsimsellikten arındırılmış işsizlik oranları önceki döneme gerilemiştir gelişmede tarım "| __truncated__ " birliği ülkelerinin talebindeki artışın ihracatı olumlu yönde etkilemeye devam edeceği öngörülmektedir yurt iç"| __truncated__ ...
## ..$ meta :List of 7
## .. ..$ author : chr ""
## .. ..$ datetimestamp: POSIXct[1:1], format: "2016-04-26 13:36:09"
## .. ..$ description : chr ""
## .. ..$ heading : chr "DUY2016-21"
## .. ..$ id : chr "PPK (04.2016).pdf"
## .. ..$ language : chr "turkish"
## .. ..$ origin : chr "PDFCreator Version 1.5.0"
## .. ..- attr(*, "class")= chr "TextDocumentMeta"
## ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"
## $ PPK (04.2020).pdf:List of 2
## ..$ content: chr [1:4] "ye\na Z / (UT TÜRKİYE CUMHURİYET\n1 777 ( B MERKEZ BANKASI\nSi\n\n30 Nisan 2020, Sayı: 2020-26\n\nToplantı Tari"| __truncated__ "İİ 4 6. Nisan ayında yılsonu enflasyon beklentilerindeki iyileşme sürmüştür. Ancak salgının seyri ile\nRİ Lİ il"| __truncated__ "ji t koşullardaki sıkılaşma, hanehalklarının gelir kaybı ve firmaların nakit akışındaki bozulma\nRİ / talepte d"| __truncated__ "ii / 16. Enflasyon beklentileri, iç talep koşulları ve üretici fiyatlarındaki gelişmelere bağlı olarak\nRİ « / "| __truncated__
## ..$ meta :List of 7
## .. ..$ author : NULL
## .. ..$ datetimestamp: POSIXct[1:1], format: "2106-02-07 09:28:15"
## .. ..$ description : NULL
## .. ..$ heading : chr "DUY2020-26"
## .. ..$ id : chr "PPK (04.2020).pdf"
## .. ..$ language : chr "turkish"
## .. ..$ origin : NULL
## .. ..- attr(*, "class")= chr "TextDocumentMeta"
## ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"
## - attr(*, "class")= chr [1:2] "VCorpus" "Corpus"
Notice that the content of each document consists of as many character strings as the number of pages in the original pdf document. The final step involves making the content a character vector with a single string which contains the whole text (as we did for FOMC statements). A simple loop will achieve this for each document:
for(i in 1: length(PPK_clean)){
PPK_clean[[i]]$content <- paste(PPK_clean[[i]]$content, collapse = ' ')
}
str(PPK_clean)## List of 2
## $ PPK (04.2016).pdf:List of 2
## ..$ content: chr " sayı basin duyurusu nisan para politikasi kurulu toplanti özeti toplantı tarihi nisan enflasyon gelişmeleri ma"| __truncated__
## ..$ meta :List of 7
## .. ..$ author : chr ""
## .. ..$ datetimestamp: POSIXct[1:1], format: "2016-04-26 13:36:09"
## .. ..$ description : chr ""
## .. ..$ heading : chr "DUY2016-21"
## .. ..$ id : chr "PPK (04.2016).pdf"
## .. ..$ language : chr "turkish"
## .. ..$ origin : chr "PDFCreator Version 1.5.0"
## .. ..- attr(*, "class")= chr "TextDocumentMeta"
## ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"
## $ PPK (04.2020).pdf:List of 2
## ..$ content: chr "ye\na Z / (UT TÜRKİYE CUMHURİYET\n1 777 ( B MERKEZ BANKASI\nSi\n\n30 Nisan 2020, Sayı: 2020-26\n\nToplantı Tari"| __truncated__
## ..$ meta :List of 7
## .. ..$ author : NULL
## .. ..$ datetimestamp: POSIXct[1:1], format: "2106-02-07 09:28:15"
## .. ..$ description : NULL
## .. ..$ heading : chr "DUY2020-26"
## .. ..$ id : chr "PPK (04.2020).pdf"
## .. ..$ language : chr "turkish"
## .. ..$ origin : NULL
## .. ..- attr(*, "class")= chr "TextDocumentMeta"
## ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"
## - attr(*, "class")= chr [1:2] "VCorpus" "Corpus"
Finally, reapply the cleaning function:
PPK_clean <- clean.new.corpus(PPK_clean)
str(PPK_clean)## List of 2
## $ PPK (04.2016).pdf:List of 2
## ..$ content: chr " sayı basin duyurusu nisan para politikasi kurulu toplanti özeti toplantı tarihi nisan enflasyon gelişmeleri ma"| __truncated__
## ..$ meta :List of 7
## .. ..$ author : chr ""
## .. ..$ datetimestamp: POSIXct[1:1], format: "2016-04-26 13:36:09"
## .. ..$ description : chr ""
## .. ..$ heading : chr "DUY2016-21"
## .. ..$ id : chr "PPK (04.2016).pdf"
## .. ..$ language : chr "turkish"
## .. ..$ origin : chr "PDFCreator Version 1.5.0"
## .. ..- attr(*, "class")= chr "TextDocumentMeta"
## ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"
## $ PPK (04.2020).pdf:List of 2
## ..$ content: chr "ye a z ut türkiye cumhuriyet b merkez bankasi si nisan sayı toplantı tarihi nisan enflasyon gelişmeleri martayı"| __truncated__
## ..$ meta :List of 7
## .. ..$ author : NULL
## .. ..$ datetimestamp: POSIXct[1:1], format: "2106-02-07 09:28:15"
## .. ..$ description : NULL
## .. ..$ heading : chr "DUY2020-26"
## .. ..$ id : chr "PPK (04.2020).pdf"
## .. ..$ language : chr "turkish"
## .. ..$ origin : NULL
## .. ..- attr(*, "class")= chr "TextDocumentMeta"
## ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"
## - attr(*, "class")= chr [1:2] "VCorpus" "Corpus"
OCR could not read the TCMB logo on the front page, thus some strange words appear in the first line which need to be removed.
#remove words with length 2 or less
PPK_clean[[2]]$content <- gsub('\\b\\w{1,2}\\b','',PPK_clean[[2]]$content)
str(PPK_clean)## List of 2
## $ PPK (04.2016).pdf:List of 2
## ..$ content: chr " sayı basin duyurusu nisan para politikasi kurulu toplanti özeti toplantı tarihi nisan enflasyon gelişmeleri ma"| __truncated__
## ..$ meta :List of 7
## .. ..$ author : chr ""
## .. ..$ datetimestamp: POSIXct[1:1], format: "2016-04-26 13:36:09"
## .. ..$ description : chr ""
## .. ..$ heading : chr "DUY2016-21"
## .. ..$ id : chr "PPK (04.2016).pdf"
## .. ..$ language : chr "turkish"
## .. ..$ origin : chr "PDFCreator Version 1.5.0"
## .. ..- attr(*, "class")= chr "TextDocumentMeta"
## ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"
## $ PPK (04.2020).pdf:List of 2
## ..$ content: chr " türkiye cumhuriyet merkez bankasi nisan sayı toplantı tarihi nisan enflasyon gelişmeleri martayında tüket"| __truncated__
## ..$ meta :List of 7
## .. ..$ author : NULL
## .. ..$ datetimestamp: POSIXct[1:1], format: "2106-02-07 09:28:15"
## .. ..$ description : NULL
## .. ..$ heading : chr "DUY2020-26"
## .. ..$ id : chr "PPK (04.2020).pdf"
## .. ..$ language : chr "turkish"
## .. ..$ origin : NULL
## .. ..- attr(*, "class")= chr "TextDocumentMeta"
## ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"
## - attr(*, "class")= chr [1:2] "VCorpus" "Corpus"
Let’s create the TDM and draw some visuals:
tdmppk <- TermDocumentMatrix(PPK_clean)
tdmppk <- as.matrix(tdmppk)
freqtermsppk <- rowSums(tdmppk)
freqtermsppk <- sort(freqtermsppk, decreasing = TRUE)
barplot(freqtermsppk[1:10], las = 2, col = "blue")term_vec_ppk <- names(freqtermsppk)
wordcloud(term_vec_ppk, freqtermsppk, colors = c("red","goldenrod"), scale = c(2.5, 0.3))comparison.cloud(tdmppk, colors = c("orange", "blue"), title.size = 0.4, scale = c(1.2,0.2))We can use SentimentAnalysis::analyzeSentiment() for sentiment analysis, which aims to assess whether the tone of a document is positive or negative with the help of a predefined dictionary of positive and negative words. The package SentimentAnalysiscomes with built-in dictionaries. analyzeSentiment() takes a string, corpus or a TDM and returns a matrix with calculated sentiment scores based on a set of rules:
library(SentimentAnalysis)
sentiments <- analyzeSentiment(FOMC_clean,
rules = list("Overall Score"=list(ruleSentiment,
loadDictionaryLM()),
"Positivity" = list(rulePositivity,
loadDictionaryLM()),
"Negativity" = list(ruleNegativity,
loadDictionaryLM()),
"Polarity" = list(ruleSentimentPolarity,
loadDictionaryLM())),
stemming = TRUE)
sentiments## Overall Score Positivity Negativity Polarity
## 1 -0.005736138 0.02868069 0.03441683 -0.09090909
## 2 -0.017167382 0.03648069 0.05364807 -0.19047619
Sentiment scores are obtained using the Loughran-McDonald dictionary (2011), which was specifically created for the analysis of financial texts. The overall sentiment score is calculated as the ratio of the difference between positive and negative word counts to the total number of words. Positivity is the proportion of words that are labeled as positive and negativity is the proportion of words that are labeled as negative. Finally, polarity is the difference between positive and negative words divided by their sum. All of these scores are calculated for each document. Alternatively, not specifying a rule list in the function will return sentiment scores based on all available dictionaries. For example:
sentimentsall <- analyzeSentiment(FOMC_clean, stemming = TRUE)
sentimentsall## WordCount SentimentGI NegativityGI PositivityGI SentimentHE NegativityHE
## 1 523 0.1357553 0.07456979 0.210325 0.015296367 0.003824092
## 2 466 0.1545064 0.06866953 0.223176 -0.004291845 0.008583691
## PositivityHE SentimentLM NegativityLM PositivityLM RatioUncertaintyLM
## 1 0.019120459 -0.005736138 0.03441683 0.02868069 0.03250478
## 2 0.004291845 -0.017167382 0.05364807 0.03648069 0.01716738
## SentimentQDAP NegativityQDAP PositivityQDAP
## 1 0.1051625 0.04588910 0.1510516
## 2 0.1223176 0.05364807 0.1759657
When the Harvard Dictionary (GI) is used, the FOMC statement in April 2016 turns out to be written in a more negative tone when compared to April 2017. However, the results change when Henry’s Financial Dictionary or the LM dictionary is used. This illustrates the context-sensitivity of dictionaries. As expected, when calculated with the other two dictionaries, sentiment scores imply a more negative tone in the March 2020 statement.
We can also examine the sentiment in the CBRT Monetary Policy Committee statements. However, we need a custom dictionary since there are no available Turkish dictionaries in the SentimentAnalysis package. We can use the Google Translated version of the LM dictionary as a first step.
library(readxl)
turkish_neg <- read_xlsx("LM-turkish.xlsx", sheet = 1, col_names = FALSE) ## New names:
turkish_pos <- read_xlsx("LM-turkish.xlsx", sheet = 2, col_names = FALSE) ## New names:
turkish_neg <- as.character(turkish_neg$...1)
turkish_pos <- as.character(turkish_pos$...1)
str(turkish_neg)## chr [1:2351] "terk etmek" "terk edilmiş" "terk edilmesi" "terk" ...
str(turkish_pos)## chr [1:347] "yapabilmek" "bolluk" "bol" "takip edildi" "başarmak" ...
We should create our custom dictionary with the SentimentAnalysis::SentimentDictionaryBinary() function, which creates a new object with two separate vectors of positive and negative words. The calculation rules require that the dictionary be this type of object, otherwise sentiment scores cannot be calculated.
dict <- SentimentDictionaryBinary(turkish_pos, turkish_neg)
str(dict)## List of 2
## $ positiveWords: chr [1:347] "yapabilmek" "bolluk" "bol" "takip edildi" ...
## $ negativeWords: chr [1:2351] "terk etmek" "terk edilmiş" "terk edilmesi" "terk" ...
## - attr(*, "class")= chr "SentimentDictionaryBinary"
Notice that there are bigrams among positive and negative words, which is the downside of working with a google-translated dictionary. As we will see, the number of words identified as positive or negative are going to be much lower.
Now we are ready to calculate sentiment scores:
sentiment_tr <- analyzeSentiment(PPK_clean,
rules = list("Words" = list(ruleWordCount),
"Positivity" = list(rulePositivity,
dict),
"Negativity" = list(ruleNegativity,
dict),
"Overall" = list(ruleSentiment,
dict),
"Polarity" = list(ruleSentimentPolarity,
dict)),
stemming = TRUE)
sentiment_tr## Words Positivity Negativity Overall Polarity
## 1 1489 0.01007388 0.04499664 -0.03492277 -0.6341463
## 2 1307 0.01683244 0.05508799 -0.03825555 -0.5319149
We can simply multiply the total number of words in each document with their respective positivity and negativity scores to find out how many words matched with those classified as positive or negative in the LM dictionary. For instance, there are 1489 total words in the 2016 statement, and \(1489 \times 0.01 \approx 15\) positive words are identified. Likewise, there are \(1489 \times 0.044 \approx 67\) negative words. For the 2020 statement, the number of positive words and negative words are \(1307 \times 0.016 \approx 22\) and \(1307 \times 0.055 \approx 72\), respectively.
Overall, a more negative tone is present in the 2020 MPC statement, although overall sentiment scores are quite close to each other. On the other hand, polarity scores, which are not sensitive to document length, imply a more negative tone in the 2016 statement. This is due to a slightly higher gap between the number of positive and negative words used in the 2016 statement: \(67 - 15 = 52\). For 2020, the difference is \(72 - 22 = 50\). Coupled with a lower number of total positive and negative words, the resulting polarity score is substantially larger for 2016.