<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/inauguration-speeches/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://randomjohn.github.io/tidy-text-inauguration-speeches/"> Upstate Data Analysis</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<h2>Acquiring inauguration speeches</h2>
<p>Though not about Greenville especially, it might be interesting to quantitatively analyze inauguration speeches. This analysis will be done using two paradigms: the <code>tm</code> package and the <code>tidytext</code> package. We will read the speeches in such a way that we use the <code>tidytext</code> package; later on we will use some tools from that package to make analyses traditionally done by <code>tm</code>.</p>
<p>I looked around for inauguration speeches, and finally found them at <code>www.bartelby.com</code>. They are in a format more for human consumption, but with the use of the <code>rvest</code> (harvest?) package, we can read them in relatively easily. However, we need to do a mapping from speech IDs to speakers (newly inaugurated presidents), which is a little ugly and tedious.</p>
<figure>
<pre><code data-lang="r"><span>library</span><span>(</span><span>rvest</span><span>)</span><span>
</span><span>library</span><span>(</span><span>magrittr</span><span>)</span><span>
</span><span>library</span><span>(</span><span>dplyr</span><span>)</span><span>
</span><span>library</span><span>(</span><span>readr</span><span>)</span><span>
</span><span>library</span><span>(</span><span>tidytext</span><span>)</span><span>
</span><span>library</span><span>(</span><span>tm</span><span>)</span><span>
</span><span>library</span><span>(</span><span>ggplot2</span><span>)</span><span>
</span><span># download and format data ------------------------------------------------
</span><span> </span><span>fmt_string</span><span> </span><span>&lt;-</span><span> </span><span>&quot;http://www.bartleby.com/124/pres%d.html&quot;</span><span>
</span><span>speakers</span><span> </span><span>&lt;-</span><span> </span><span>read.csv</span><span>(</span><span>textConnection</span><span>(</span><span>&quot;Number,Speaker
13,George Washington
14,George Washington
15,John Adams
16,Thomas Jefferson
17,Thomas Jefferson
18,James Madison
19,James Madison
20,James Monroe
21,James Monroe
22,John Quincy Adams
23,Andrew Jackson
24,Andrew Jackson
25,Martin Van Buren
26,William Henry Harrison
27,James Knox Polk
28,Zachary Taylor
29,Franklin Pierce
30,James Buchanon
31,Abraham Lincoln
32,Abraham Lincoln
33,Ulysses S. Grant
34,Ulysses S. Grant
35,Rutherford B. Hayes
36,James A. Garfield
37,Grover Cleveland
38,Benjamin Harrison
39,Grover Cleveland
40,William McKinley
41,William McKinley
42,Theodore Roosevelt
43,William Howard Taft
44,Woodrow Wilson
45,Woodrow Wilson
46,Warren G. Harding
47,Calvin Coolidge
48,Herbert Hoover
49,Franklin D. Roosevelt
50,Franklin D. Roosevelt
51,Franklin D. Roosevelt
52,Franklin D. Roosevelt
53,Harry S. Truman
54,Dwight D. Eisenhower
55,Dwight D. Eisenhower
56,John F. Kennedy
57,Lyndon Baines Johnson
58,Richard Milhaus Nixon
59,Richard Milhaus Nixon
60,Jimmy Carter
61,Ronald Reagan
62,Ronald Reagan
63,George H. W. Bush
64,Bill Clinton
65,Bill Clinton
66,George W. Bush
67,George W. Bush
68,Barack Obama
69,Barack Obama
70,Donald Trump&quot;</span><span>))</span><span>
</span><span># read the speeches into a list of data.frames, append ID number in a new column </span><span>speeches</span><span> </span><span>&lt;-</span><span> </span><span>list</span><span>()</span><span>
</span><span>for</span><span> </span><span>(</span><span>id</span><span> </span><span>in</span><span> </span><span>13</span><span>:</span><span>70</span><span>)</span><span> </span><span>{</span><span>
</span><span>speech_html</span><span> </span><span>&lt;-</span><span> </span><span>read_html</span><span>(</span><span>sprintf</span><span>(</span><span>fmt_string</span><span>,</span><span>id</span><span>))</span><span>
</span><span>speech_lines</span><span> </span><span>&lt;-</span><span> </span><span>speech_html</span><span> </span><span>%>%</span><span> </span><span>html_nodes</span><span>(</span><span>&quot;table&quot;</span><span>)</span><span> </span><span>%>%</span><span> </span><span>extract</span><span>(</span><span>9</span><span>)</span><span> </span><span>%>%</span><span> </span><span>html_table</span><span>()</span><span> </span><span>%>%</span><span> </span><span>as.data.frame</span><span>()</span><span> </span><span>%>%</span><span> </span><span>rename</span><span>(</span><span>text</span><span>=</span><span>X</span><span>1</span><span>,</span><span>line</span><span>=</span><span>X</span><span>2</span><span>)</span><span> </span><span>%>%</span><span> </span><span>mutate</span><span>(</span><span>id</span><span>=</span><span>rep</span><span>(</span><span>id</span><span>,</span><span>nrow</span><span>(</span><span>.</span><span>)))</span><span>
</span><span>speeches</span><span>[[</span><span>id</span><span>-12</span><span>]]</span><span> </span><span>&lt;-</span><span> </span><span>speech_lines</span><span>
</span><span>}</span><span>
</span><span># concatenate all the speeches and add speaker names
</span><span>speech_df</span><span> </span><span>&lt;-</span><span> </span><span>do.call</span><span>(</span><span>rbind</span><span>,</span><span>speeches</span><span>)</span><span>
</span><span>speech_df</span><span> </span><span>&lt;-</span><span> </span><span>speech_df</span><span> </span><span>%>%</span><span> </span><span>left_join</span><span>(</span><span>speakers</span><span>,</span><span>by</span><span>=</span><span>c</span><span>(</span><span>&quot;id&quot;</span><span>=</span><span>&quot;Number&quot;</span><span>))</span></code></pre>
</figure>
<h2>First analysis</h2>
<p>Now that we have the speeches as a one-record-per-speech data frame, we can start to analyze them. This post will consist really of a basic analysis based on the “bag of words” paradigm. There are more sophisticated analyses that can be done, but even the basics can be interesting. First, we do a bit of data munging to create a one-record-per-word-per-speech dataset. The strategy is based on the <a target="_blank" rel="nofollow" href="http://juliasilge.com/blog/RStudio-Conf/">tidy text paradigm described here</a>. Once we have the dataset in the format we want, we can easily eliminate “uninteresting” words by using a filtering <code>anti-join</code> from the <code>dplyr</code> package. (Note: there may be analyses where you would want to keep these so-called “stop-words”, e.g. “a” and “the”, but for purposes here we just get rid of them.)</p>
<figure>
<pre><code data-lang="r"><span>speech_words</span><span> </span><span>&lt;-</span><span> </span><span>speech_df</span><span> </span><span>%>%</span><span> </span><span>mutate</span><span>(</span><span>id</span><span>=</span><span>factor</span><span>(</span><span>id</span><span>))</span><span> </span><span>%>%</span><span> </span><span>unnest_tokens</span><span>(</span><span>word</span><span>,</span><span>text</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>count</span><span>(</span><span>id</span><span>,</span><span> </span><span>word</span><span>,</span><span> </span><span>sort</span><span> </span><span>=</span><span> </span><span>TRUE</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>ungroup</span><span>()</span><span>
</span><span>total_words</span><span> </span><span>&lt;-</span><span> </span><span>speech_words</span><span> </span><span>%>%</span><span> </span><span>group_by</span><span>(</span><span>id</span><span>)</span><span> </span><span>%>%</span><span> </span><span>summarize</span><span>(</span><span>total</span><span> </span><span>=</span><span> </span><span>sum</span><span>(</span><span>n</span><span>))</span><span>
</span><span>speech_words</span><span> </span><span>&lt;-</span><span> </span><span>left_join</span><span>(</span><span>speech_words</span><span>,</span><span> </span><span>total_words</span><span>)</span><span> </span><span>%>%</span><span> </span><span>anti_join</span><span>(</span><span>stop_words</span><span> </span><span>%>%</span><span> </span><span>filter</span><span>(</span><span>lexicon</span><span>==</span><span>&quot;onix&quot;</span><span>)</span><span> </span><span>%>%</span><span> </span><span>select</span><span>(</span><span>-</span><span>lexicon</span><span>)</span><span> </span><span>%>%</span><span> </span><span>union</span><span>(</span><span>data.frame</span><span>(</span><span>word</span><span>=</span><span>c</span><span>(</span><span>&quot;s&quot;</span><span>,</span><span>&quot;so&quot;</span><span>))),</span><span>by</span><span>=</span><span>&quot;word&quot;</span><span>)</span></code></pre>
</figure>
<figure>
<pre><code data-lang="text">## Joining, by = &quot;id&quot;</code></pre>
</figure>
<figure>
<pre><code data-lang="text">## Warning in union_data_frame(x, y): joining character vector and factor,
## coercing into character vector</code></pre>
</figure>
<figure>
<pre><code data-lang="r"><span>speech_words</span><span> </span><span>%>%</span><span> </span><span>head</span><span>()</span></code></pre>
</figure>
<figure>
<pre><code data-lang="text">## # A tibble: 6 Ã— 4
##       id  word     n total
##   &lt;fctr> &lt;chr> &lt;int> &lt;int>
## 1     26 power    47  8463
## 2     21 power    11  4476
## 3     29 power    11  3341
## 4     27 power     9  4813
## 5     36 power     9  2990
## 6     25 power     8  3902</code></pre>
</figure>
<p>We can now plot the most common words in inauguration speech, just to dig into what that dataset looks like. Note that I polished this graph up a bit (changing axis labels to something pretty, rotating x-axis labels, etc.), but the first past through this graph was a bit ugly. To me, the two most important elements of this graph are selecting the 20 most common words and re-ordering from most to fewest.</p>
<figure>
<pre><code data-lang="r"><span># find frequencies of words used in speeches
# we do this so we can reorder in ggplot2 (there may be a way to do directly in ggplot2 without this step)
</span><span>speech_freq</span><span> </span><span>&lt;-</span><span> </span><span>speech_words</span><span> </span><span>%>%</span><span> </span><span>group_by</span><span>(</span><span>word</span><span>)</span><span> </span><span>%>%</span><span> </span><span>summarize</span><span>(</span><span>frequency</span><span>=</span><span>n</span><span>())</span><span> </span><span>%>%</span><span> </span><span>arrange</span><span>(</span><span>desc</span><span>(</span><span>frequency</span><span>))</span><span>
</span><span># plot frequencies of words over all speeches, top 20 only, in order of frequency most to fewest
</span><span>ggplot</span><span>(</span><span>speech_freq</span><span> </span><span>%>%</span><span> </span><span>ungroup</span><span>()</span><span> </span><span>%>%</span><span> </span><span>slice</span><span>(</span><span>1</span><span>:</span><span>20</span><span>),</span><span> </span><span>aes</span><span>(</span><span>reorder</span><span>(</span><span>word</span><span>,</span><span>desc</span><span>(</span><span>frequency</span><span>))))</span><span> </span><span>+</span><span>
</span><span>geom_bar</span><span>(</span><span>aes</span><span>(</span><span>y</span><span>=</span><span>frequency</span><span>),</span><span>stat</span><span>=</span><span>&quot;identity&quot;</span><span>,</span><span>alpha</span><span> </span><span>=</span><span> </span><span>0.8</span><span>,</span><span> </span><span>show.legend</span><span> </span><span>=</span><span> </span><span>FALSE</span><span>)</span><span> </span><span>+</span><span>
</span><span>labs</span><span>(</span><span>title</span><span> </span><span>=</span><span> </span><span>&quot;Term Frequency Distribution in Presidential Inaugural Addresses&quot;</span><span>)</span><span> </span><span>+</span><span>
</span><span>xlab</span><span>(</span><span>&quot;Word&quot;</span><span>)</span><span> </span><span>+</span><span> </span><span>ylab</span><span>(</span><span>&quot;Frequency&quot;</span><span>)</span><span> </span><span>+</span><span> </span><span>theme</span><span>(</span><span>axis.text.x</span><span> </span><span>=</span><span> </span><span>element_text</span><span>(</span><span>angle</span><span> </span><span>=</span><span> </span><span>45</span><span>,</span><span> </span><span>hjust</span><span> </span><span>=</span><span> </span><span>1</span><span>))</span></code></pre>
</figure>
<p><img alt="plot of chunk unnamed-chunk-3" src="https://i1.wp.com/randomjohn.github.io/figures//2017-01-27-tidy-text-inauguration-speeches.Rmdunnamed-chunk-3-1.png?w=456&ssl=1" data-recalc-dims="1"></p>
<h2>What makes speeches unique</h2>
<p>At least using the bag-of-words paradigm, the term-frequency * inverse-document-frequency (TF-IDF) analysis is used to determine what words set speeches (or other documents) apart from each other. A word in a given document has a high TF-IDF score if it appears very often in that speech, but rarely in others. If a word appears less frequently in a speech, or appears more often in other speeches, that will lower the TF-IDF score. Thus, a word with a high TF-IDF score can be considered a signature word for a speech Using this strategy for all interesting words, we can compare styles of speeches, and even cluster them into groups.</p>
<p>First, we use the <code>bind_tf_idf</code> function from <code>tidytext</code> to calculate the TF-IDF score. Then we can find the words with the highest TF-IDF score – the words that do the most to distinguish one inauguration speech from another.</p>
<figure>
<pre><code data-lang="r"><span>speech_words2</span><span> </span><span>&lt;-</span><span> </span><span>speech_words</span><span> </span><span>%>%</span><span>
</span><span>bind_tf_idf</span><span>(</span><span>word</span><span>,</span><span> </span><span>id</span><span>,</span><span> </span><span>n</span><span>)</span><span>
</span><span>speech_words2</span></code></pre>
</figure>
<figure>
<pre><code data-lang="text">## # A tibble: 34,734 Ã— 7
##        id  word     n total          tf       idf       tf_idf
##    &lt;fctr> &lt;chr> &lt;int> &lt;int>       &lt;dbl>     &lt;dbl>        &lt;dbl>
## 1      26 power    47  8463 0.015254787 0.2102954 0.0032080118
## 2      21 power    11  4476 0.006654567 0.2102954 0.0013994250
## 3      29 power    11  3341 0.008403361 0.2102954 0.0017671883
## 4      27 power     9  4813 0.004729375 0.2102954 0.0009945658
## 5      36 power     9  2990 0.007419621 0.2102954 0.0015603122
## 6      25 power     8  3902 0.004839685 0.2102954 0.0010177636
## 7      30 power     7  2834 0.006178288 0.2102954 0.0012992655
## 8      50 power     7  1823 0.009681881 0.2102954 0.0020360551
## 9      38 power     6  4397 0.003472222 0.2102954 0.0007301924
##  [ reached getOption(&quot;max.print&quot;) -- omitted 1 row ]
## # ... with 34,724 more rows</code></pre>
</figure>
<figure>
<pre><code data-lang="r"><span>speech_words2</span><span> </span><span>%>%</span><span>
</span><span>select</span><span>(</span><span>-</span><span>total</span><span>)</span><span> </span><span>%>%</span><span>
</span><span>arrange</span><span>(</span><span>desc</span><span>(</span><span>tf_idf</span><span>))</span></code></pre>
</figure>
<figure>
<pre><code data-lang="text">## # A tibble: 34,734 Ã— 6
##        id        word     n         tf      idf     tf_idf
##    &lt;fctr>       &lt;chr> &lt;int>      &lt;dbl>    &lt;dbl>      &lt;dbl>
## 1      14      arrive     1 0.01851852 4.060443 0.07519339
## 2      14 upbraidings     1 0.01851852 4.060443 0.07519339
## 3      14   incurring     1 0.01851852 3.367296 0.06235733
## 4      14    violated     1 0.01851852 3.367296 0.06235733
## 5      14   willingly     1 0.01851852 3.367296 0.06235733
## 6      14 injunctions     1 0.01851852 2.961831 0.05484872
## 7      14   knowingly     1 0.01851852 2.961831 0.05484872
## 8      14    previous     1 0.01851852 2.961831 0.05484872
## 9      14   witnesses     1 0.01851852 2.961831 0.05484872
## 10     14     besides     1 0.01851852 2.674149 0.04952127
## # ... with 34,724 more rows</code></pre>
</figure>
<figure>
<pre><code data-lang="r"><span>plot_inaug</span><span> </span><span>&lt;-</span><span> </span><span>speech_words2</span><span> </span><span>%>%</span><span>
</span><span>arrange</span><span>(</span><span>desc</span><span>(</span><span>tf_idf</span><span>))</span><span> </span><span>%>%</span><span>
</span><span>mutate</span><span>(</span><span>word</span><span> </span><span>=</span><span> </span><span>factor</span><span>(</span><span>word</span><span>,</span><span> </span><span>levels</span><span> </span><span>=</span><span> </span><span>rev</span><span>(</span><span>unique</span><span>(</span><span>word</span><span>))))</span><span> </span><span>%>%</span><span> </span><span>left_join</span><span>(</span><span>speakers</span><span> </span><span>%>%</span><span> </span><span>mutate</span><span>(</span><span>id</span><span>=</span><span>factor</span><span>(</span><span>Number</span><span>)),</span><span>by</span><span>=</span><span>&quot;id&quot;</span><span>)</span><span>
</span><span>ggplot</span><span>(</span><span>plot_inaug</span><span> </span><span>%>%</span><span> </span><span>filter</span><span>(</span><span>tf_idf</span><span> </span><span>></span><span> </span><span>0.025</span><span>),</span><span> </span><span>aes</span><span>(</span><span>word</span><span>,</span><span> </span><span>tf_idf</span><span>,</span><span> </span><span>fill</span><span> </span><span>=</span><span> </span><span>Speaker</span><span>))</span><span> </span><span>+</span><span>
</span><span>geom_bar</span><span>(</span><span>alpha</span><span> </span><span>=</span><span> </span><span>0.8</span><span>,</span><span> </span><span>stat</span><span> </span><span>=</span><span> </span><span>&quot;identity&quot;</span><span>)</span><span> </span><span>+</span><span>
</span><span>labs</span><span>(</span><span>title</span><span> </span><span>=</span><span> </span><span>&quot;Highest tf-idf words in Presidential Inauguration Speeches&quot;</span><span>,</span><span>
</span><span>x</span><span> </span><span>=</span><span> </span><span>NULL</span><span>,</span><span> </span><span>y</span><span> </span><span>=</span><span> </span><span>&quot;tf-idf&quot;</span><span>)</span><span> </span><span>+</span><span>
</span><span>coord_flip</span><span>()</span></code></pre>
</figure>
<p><img alt="plot of chunk unnamed-chunk-4" src="https://i1.wp.com/randomjohn.github.io/figures//2017-01-27-tidy-text-inauguration-speeches.Rmdunnamed-chunk-4-1.png?w=456&ssl=1" data-recalc-dims="1"></p>
<p>Then we can do this analysis within each speech to find out what distinguishes them from other speeches. The <code>for</code> loop below can be used to print multiple pages of faceted graphs, good for when you are using RStudio or the R gui to explore.</p>
<figure>
<pre><code data-lang="r"><span>plot_words</span><span> </span><span>&lt;-</span><span> </span><span>speech_words2</span><span> </span><span>%>%</span><span> </span><span>left_join</span><span>(</span><span>speakers</span><span> </span><span>%>%</span><span> </span><span>mutate</span><span>(</span><span>id</span><span>=</span><span>factor</span><span>(</span><span>Number</span><span>)),</span><span>by</span><span>=</span><span>&quot;id&quot;</span><span>)</span><span> </span><span>%>%</span><span> </span><span>group_by</span><span>(</span><span>Speaker</span><span>)</span><span> </span><span>%>%</span><span> </span><span>top_n</span><span>(</span><span>15</span><span>,</span><span>tf_idf</span><span>)</span><span>
</span><span>speakers_vec</span><span> </span><span>&lt;-</span><span> </span><span>unique</span><span>(</span><span>plot_words</span><span>$</span><span>Speaker</span><span>)</span><span> </span><span>n_panel</span><span> </span><span>&lt;-</span><span> </span><span>4</span><span>
</span><span>for</span><span> </span><span>(</span><span>i</span><span> </span><span>in</span><span> </span><span>1</span><span>:</span><span>floor</span><span>(</span><span>length</span><span>(</span><span>speakers_vec</span><span>)</span><span>/</span><span>n_panel</span><span>))</span><span> </span><span>{</span><span>
</span><span>these_speakers</span><span> </span><span>&lt;-</span><span> </span><span>speakers_vec</span><span>[((</span><span>i</span><span>-1</span><span>)</span><span>*</span><span>n_panel</span><span>+1</span><span>)</span><span>:</span><span>min</span><span>(</span><span>i</span><span>*</span><span>n_panel</span><span>,</span><span>length</span><span>(</span><span>speakers_vec</span><span>))]</span><span>
</span><span>this_plot</span><span> </span><span>&lt;-</span><span> </span><span>ggplot</span><span>(</span><span>plot_words</span><span> </span><span>%>%</span><span> </span><span>filter</span><span>(</span><span>Speaker</span><span> </span><span>%in%</span><span> </span><span>these_speakers</span><span>),</span><span> </span><span>aes</span><span>(</span><span>word</span><span>,</span><span> </span><span>tf_idf</span><span>,</span><span> </span><span>fill</span><span> </span><span>=</span><span> </span><span>Speaker</span><span>))</span><span> </span><span>+</span><span>
</span><span>geom_bar</span><span>(</span><span>alpha</span><span> </span><span>=</span><span> </span><span>0.8</span><span>,</span><span> </span><span>stat</span><span> </span><span>=</span><span> </span><span>&quot;identity&quot;</span><span>,</span><span> </span><span>show.legend</span><span> </span><span>=</span><span> </span><span>FALSE</span><span>)</span><span> </span><span>+</span><span>
</span><span>labs</span><span>(</span><span>title</span><span> </span><span>=</span><span> </span><span>&quot;Highest tf-idf words in Inaugural Speeches&quot;</span><span>,</span><span>
</span><span>x</span><span> </span><span>=</span><span> </span><span>NULL</span><span>,</span><span> </span><span>y</span><span> </span><span>=</span><span> </span><span>&quot;tf-idf&quot;</span><span>)</span><span> </span><span>+</span><span>
</span><span>facet_wrap</span><span>(</span><span>~</span><span>Speaker</span><span>,</span><span> </span><span>ncol</span><span> </span><span>=</span><span> </span><span>2</span><span>,</span><span> </span><span>scales</span><span> </span><span>=</span><span> </span><span>&quot;free&quot;</span><span>)</span><span> </span><span>+</span><span>
</span><span>coord_flip</span><span>()</span><span> </span><span>print</span><span>(</span><span>this_plot</span><span>)</span><span>
</span><span>}</span></code></pre>
</figure>
<p><img alt="plot of chunk unnamed-chunk-5" src="https://i0.wp.com/randomjohn.github.io/figures//2017-01-27-tidy-text-inauguration-speeches.Rmdunnamed-chunk-5-1.png?w=456&ssl=1" data-recalc-dims="1"><img alt="plot of chunk unnamed-chunk-5" src="https://i0.wp.com/randomjohn.github.io/figures//2017-01-27-tidy-text-inauguration-speeches.Rmdunnamed-chunk-5-2.png?w=456&ssl=1" data-recalc-dims="1"><img alt="plot of chunk unnamed-chunk-5" src="https://i2.wp.com/randomjohn.github.io/figures//2017-01-27-tidy-text-inauguration-speeches.Rmdunnamed-chunk-5-3.png?w=456&ssl=1" data-recalc-dims="1"><img alt="plot of chunk unnamed-chunk-5" src="https://i0.wp.com/randomjohn.github.io/figures//2017-01-27-tidy-text-inauguration-speeches.Rmdunnamed-chunk-5-4.png?w=456&ssl=1" data-recalc-dims="1"><img alt="plot of chunk unnamed-chunk-5" src="https://i0.wp.com/randomjohn.github.io/figures//2017-01-27-tidy-text-inauguration-speeches.Rmdunnamed-chunk-5-5.png?w=456&ssl=1" data-recalc-dims="1"><img alt="plot of chunk unnamed-chunk-5" src="https://i2.wp.com/randomjohn.github.io/figures//2017-01-27-tidy-text-inauguration-speeches.Rmdunnamed-chunk-5-6.png?w=456&ssl=1" data-recalc-dims="1"><img alt="plot of chunk unnamed-chunk-5" src="https://i2.wp.com/randomjohn.github.io/figures//2017-01-27-tidy-text-inauguration-speeches.Rmdunnamed-chunk-5-7.png?w=456&ssl=1" data-recalc-dims="1"><img alt="plot of chunk unnamed-chunk-5" src="https://i1.wp.com/randomjohn.github.io/figures//2017-01-27-tidy-text-inauguration-speeches.Rmdunnamed-chunk-5-8.png?w=456&ssl=1" data-recalc-dims="1"><img alt="plot of chunk unnamed-chunk-5" src="https://i0.wp.com/randomjohn.github.io/figures//2017-01-27-tidy-text-inauguration-speeches.Rmdunnamed-chunk-5-9.png?w=456&ssl=1" data-recalc-dims="1"></p>
<h2>Which speeches are most like each other?</h2>
<p>There’s a lot more that can be done here, but we’ll move on to clustering these inauguration speeches. This will require the use of the document-term matrix, which is a matrix that has documents in the rows, words in the columns, and entries that represent the frequency within the row’s document of the column’s term. The <code>tidytext</code> packages uses the <code>cast_dtm</code> function to create the document-term matrix, and the output can then be used by the <code>tm</code> package and other R commands for analysis.</p>
<figure>
<pre><code data-lang="r"><span>plot_words_dtm</span><span> </span><span>&lt;-</span><span> </span><span>speech_words</span><span> </span><span>%>%</span><span> </span><span>left_join</span><span>(</span><span>speakers</span><span> </span><span>%>%</span><span> </span><span>mutate</span><span>(</span><span>id</span><span>=</span><span>factor</span><span>(</span><span>Number</span><span>)),</span><span>by</span><span>=</span><span>&quot;id&quot;</span><span>)</span><span> </span><span>%>%</span><span> </span><span>cast_dtm</span><span>(</span><span>id</span><span>,</span><span>word</span><span>,</span><span>n</span><span>)</span><span>
</span><span>plot_words_dtm</span><span> </span><span>&lt;-</span><span> </span><span>removeSparseTerms</span><span>(</span><span>plot_words_dtm</span><span>,</span><span>0.1</span><span>)</span><span>
</span><span>plot_words_matrix</span><span> </span><span>&lt;-</span><span> </span><span>as.matrix</span><span>(</span><span>plot_words_dtm</span><span>)</span></code></pre>
</figure>
<p>To show the hierarchical clustering analysis, we can simply compute a distance matrix, which can be fed into <code>hclust</code>:</p>
<figure>
<pre><code data-lang="r"><span>dist_matrix</span><span> </span><span>&lt;-</span><span> </span><span>dist</span><span>(</span><span>scale</span><span>(</span><span>plot_words_matrix</span><span>),</span><span>method</span><span>=</span><span>&quot;euclidean&quot;</span><span>)</span><span>
</span><span>inaug_clust</span><span> </span><span>&lt;-</span><span> </span><span>hclust</span><span>(</span><span>dist_matrix</span><span>,</span><span>method</span><span>=</span><span>&quot;ward.D&quot;</span><span>)</span><span>
</span><span>plot</span><span>(</span><span>inaug_clust</span><span>)</span></code></pre>
</figure>
<p><img alt="plot of chunk unnamed-chunk-7" src="https://i1.wp.com/randomjohn.github.io/figures//2017-01-27-tidy-text-inauguration-speeches.Rmdunnamed-chunk-7-1.png?w=456&ssl=1" data-recalc-dims="1"></p>
<p>It’s pretty interesting that Speech 26 is unlike nearly all the others. This was William Henry Harrison discussing something about the Roman aristocracy, something other presidents have not felt the need to do very much.</p>
<p>Let’s say we want to break these speeches into a given number of clusters. We can use the k-means approach.</p>
<figure>
<pre><code data-lang="r"><span>inaug_km</span><span> </span><span>&lt;-</span><span> </span><span>kmeans</span><span>(</span><span>plot_words_matrix</span><span>,</span><span>centers</span><span> </span><span>=</span><span> </span><span>5</span><span>,</span><span>nstart</span><span> </span><span>=</span><span> </span><span>25</span><span>)</span><span>
</span><span>for</span><span> </span><span>(</span><span>i</span><span> </span><span>in</span><span> </span><span>1</span><span>:</span><span>length</span><span>(</span><span>inaug_km</span><span>$</span><span>withinss</span><span>))</span><span> </span><span>{</span><span> </span><span>#For each cluster, this defines the documents in that cluster </span><span> </span><span>inGroup</span><span> </span><span>&lt;-</span><span> </span><span>which</span><span>(</span><span>inaug_km</span><span>$</span><span>cluster</span><span>==</span><span>i</span><span>)</span><span> </span><span>within</span><span> </span><span>&lt;-</span><span> </span><span>plot_words_dtm</span><span>[</span><span>inGroup</span><span>,]</span><span> </span><span>if</span><span>(</span><span>length</span><span>(</span><span>inGroup</span><span>)</span><span>==</span><span>1</span><span>)</span><span> </span><span>within</span><span> </span><span>&lt;-</span><span> </span><span>t</span><span>(</span><span>as.matrix</span><span>(</span><span>within</span><span>))</span><span> </span><span>out</span><span> </span><span>&lt;-</span><span> </span><span>plot_words_dtm</span><span>[</span><span>-</span><span>inGroup</span><span>,]</span><span> </span><span>words</span><span> </span><span>&lt;-</span><span> </span><span>apply</span><span>(</span><span>within</span><span>,</span><span>2</span><span>,</span><span>mean</span><span>)</span><span> </span><span>-</span><span> </span><span>apply</span><span>(</span><span>out</span><span>,</span><span>2</span><span>,</span><span>mean</span><span>)</span><span> </span><span>#Take the difference in means for each term </span><span> </span><span>print</span><span>(</span><span>c</span><span>(</span><span>&quot;Cluster&quot;</span><span>,</span><span> </span><span>i</span><span>),</span><span> </span><span>quote</span><span>=</span><span>F</span><span>)</span><span> </span><span>labels</span><span> </span><span>&lt;-</span><span> </span><span>order</span><span>(</span><span>words</span><span>,</span><span> </span><span>decreasing</span><span>=</span><span>T</span><span>)[</span><span>1</span><span>:</span><span>20</span><span>]</span><span> </span><span>#Take the top 20 Labels
</span><span> </span><span>print</span><span>(</span><span>names</span><span>(</span><span>words</span><span>)[</span><span>labels</span><span>],</span><span> </span><span>quote</span><span>=</span><span>F</span><span>)</span><span> </span><span>#From here down just labels </span><span> </span><span>if</span><span>(</span><span>i</span><span>==</span><span>length</span><span>(</span><span>inaug_km</span><span>$</span><span>withinss</span><span>))</span><span> </span><span>{</span><span> </span><span>print</span><span>(</span><span>&quot;Cluster Membership&quot;</span><span>)</span><span> </span><span>print</span><span>(</span><span>table</span><span>(</span><span>inaug_km</span><span>$</span><span>cluster</span><span>))</span><span> </span><span>print</span><span>(</span><span>&quot;Within cluster sum of squares by cluster&quot;</span><span>)</span><span> </span><span>print</span><span>(</span><span>inaug_km</span><span>$</span><span>withinss</span><span>)</span><span> </span><span>}</span><span> </span><span>}</span></code></pre>
</figure>
<figure>
<pre><code data-lang="text">## [1] Cluster 1      
##  [1] people     government country    own        citizens   time      
##  [7] nation     &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>      
## [13] &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>      
## [19] &lt;NA>       &lt;NA>      
## [1] Cluster 2      
##  [1] government people     citizens   time       country    nation    
##  [7] own        &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>      
## [13] &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>      
## [19] &lt;NA>       &lt;NA>      
## [1] Cluster 3      
##  [1] nation     time       own        people     citizens   country   
##  [7] government &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>      
## [13] &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>      
## [19] &lt;NA>       &lt;NA>      
## [1] Cluster 4      
##  [1] citizens   country    own        nation     time       government
##  [7] people     &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>      
## [13] &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>      
## [19] &lt;NA>       &lt;NA>      
## [1] Cluster 5      
##  [1] government people     citizens   country    own        nation    
##  [7] time       &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>      
## [13] &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>       &lt;NA>      
## [19] &lt;NA>       &lt;NA>      
## [1] &quot;Cluster Membership&quot;
## 
##  1  2  3  4  5 
##  8 12 19 16  3 
## [1] &quot;Within cluster sum of squares by cluster&quot;
## [1]  760.3750  954.5833 1147.1579  733.8125  797.3333</code></pre>
</figure>
<p>Membership of speeches in clusters is here:</p>
<figure>
<pre><code data-lang="r"><span>inaug_km</span><span>$</span><span>cluster</span></code></pre>
</figure>
<figure>
<pre><code data-lang="text">## 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 
##  4  4  1  4  4  4  4  2  2  2  4  2  1  5  5  4  3  2  1  4  4  4  2  1  2 
## 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 
##  1  1  1  2  4  2  4  3  3  1  5  3  2  3  4  3  3  3  4  3  3  3  3  2  2 
## 63 64 65 66 67 68 69 70 
##  3  3  3  4  3  3  3  3</code></pre>
</figure>
<p>It’s interesting to note that all of the speeches since Hoover (i.e. 49 through 70) have either been either in category 1 or 5, with the latest ones being in Cluster 1 (this includes Reagan, Bush, Clinton, Bush, Obama, and Trump). Nearly all speeches discuss the relationship between government and its people (as you would expect from an inauguration speech), but Cluster 5 seems to put more emphasis on people, and Cluster 1 on government. Hmmm…</p>
<p>Of course, you can probably get something different with fewer clusters, and you can use the hierarchical clustering analysis above to justify a different number of clusters.</p>
<h2>Sentiment analysis</h2>
<p>We return to the bag-of-words <code>tidytext</code> paradigm to do a sentiment analysis. The sentiment analysis we do here is very simple (perhaps oversimplified), and <code>tidytext</code> supports more sophisticated analysis. But this is a start. We start by going back to the one-record-per-speech data frame, and scoring words based on sentiment. We don’t worry about stop words at this point, because they will likely be scored as 0 anyway. We use the Bing sentiment list, which basically scores words as positive or negative (or nothing). We assign a score that basically gives a +1 to positive and -1 to negative. Then we add up the score column, and divide by the number of words in the speech. (Which is why we did not eliminate stop words here.) This gives a sort of average positivity/negativity score per word in the speech. If the score is negative, there are more negative words in the speech than positive. If the score is positive, there are more positive words. The higher the absolute value of the score, the higher the imbalance in positive/negative words. Similarly, we just count the number of sentiment words (whether positive or negative) to get an idea of the emotional content of the speech. (Note: this is a preliminary analysis. This does not distinguish between, say, “good” and “not good”. So take any individual results with a grain of salt and dig deeper.)</p>
<figure>
<pre><code data-lang="r"><span>sw_sent</span><span> </span><span>&lt;-</span><span> </span><span>speech_df</span><span> </span><span>%>%</span><span> </span><span>mutate</span><span>(</span><span>id</span><span>=</span><span>factor</span><span>(</span><span>id</span><span>))</span><span> </span><span>%>%</span><span> </span><span>unnest_tokens</span><span>(</span><span>word</span><span>,</span><span>text</span><span>)</span><span> </span><span>%>%</span><span> </span><span>inner_join</span><span>(</span><span>get_sentiments</span><span>(</span><span>&quot;bing&quot;</span><span>))</span><span> </span><span>%>%</span><span> </span><span>mutate</span><span>(</span><span>score</span><span>=</span><span>(</span><span>sentiment</span><span>==</span><span>&quot;positive&quot;</span><span>)</span><span>-</span><span>(</span><span>sentiment</span><span>==</span><span>&quot;negative&quot;</span><span>),</span><span>is_scored</span><span>=</span><span>ifelse</span><span>(</span><span>sentiment</span><span> </span><span>%in%</span><span> </span><span>c</span><span>(</span><span>&quot;positive&quot;</span><span>,</span><span>&quot;negative&quot;</span><span>),</span><span>1</span><span>,</span><span>0</span><span>))</span></code></pre>
</figure>
<figure>
<pre><code data-lang="text">## Joining, by = &quot;word&quot;</code></pre>
</figure>
<figure>
<pre><code data-lang="r"><span>sw_sent</span><span> </span><span>%>%</span><span> </span><span>group_by</span><span>(</span><span>Speaker</span><span>,</span><span>id</span><span>)</span><span> </span><span>%>%</span><span> </span><span>summarize</span><span>(</span><span>speech_score</span><span>=</span><span>sum</span><span>(</span><span>score</span><span>),</span><span>speech_sent_words</span><span>=</span><span>sum</span><span>(</span><span>is_scored</span><span>))</span><span> </span><span>%>%</span><span> </span><span>left_join</span><span>(</span><span>total_words</span><span>,</span><span>by</span><span>=</span><span>&quot;id&quot;</span><span>)</span><span> </span><span>%>%</span><span> </span><span>mutate</span><span>(</span><span>speech_score</span><span>=</span><span>speech_score</span><span>/</span><span>total</span><span>,</span><span>speech_sent_words</span><span>=</span><span>speech_sent_words</span><span>/</span><span>total</span><span>)</span><span> </span><span>%>%</span><span> </span><span>arrange</span><span>(</span><span>speech_score</span><span>)</span><span> </span><span>%>%</span><span> </span><span>print</span><span>(</span><span>n</span><span>=</span><span>nrow</span><span>(</span><span>.</span><span>))</span></code></pre>
</figure>
<figure>
<pre><code data-lang="text">## Source: local data frame [58 x 5]
## Groups: Speaker [39]
## 
##                   Speaker     id speech_score speech_sent_words total
##                    &lt;fctr> &lt;fctr>        &lt;dbl>             &lt;dbl> &lt;int>
## 1         Abraham Lincoln     32  0.001426534        0.07275321   701
## 2         Abraham Lincoln     31  0.002199615        0.06983778  3637
## 3           James Madison     19  0.010734930        0.09331131  1211
## 4         John F. Kennedy     56  0.010989011        0.10036630  1365
## 5   Franklin D. Roosevelt     50  0.011519473        0.08831596  1823
## 6          Woodrow Wilson     44  0.011716462        0.08787346  1707
## 7   Franklin D. Roosevelt     49  0.012227539        0.09409888  1881
## 8  William Henry Harrison     26  0.013115916        0.06865178  8463
## 9   Franklin D. Roosevelt     51  0.015613383        0.06022305  1345
## 10         Andrew Jackson     24  0.016992353        0.07306712  1177
## 11           Barack Obama     68  0.017827529        0.08499171  2412
## 12       Martin Van Buren     25  0.018452076        0.08867248  3902
## 13          Ronald Reagan     61  0.018457752        0.07752256  2438
## 14       Thomas Jefferson     17  0.019852262        0.07710065  2166
##  [ reached getOption(&quot;max.print&quot;) -- omitted 44 rows ]</code></pre>
</figure>
<p>Grover Cleveland and James Madison had the speeches with the highest emotional content, followed by Jimmy Carter and George W. Bush. Wilson, Franklin D. Roosevelt, and George Washington had the lowest emotional content. Abraham Lincoln (in 1860) had the speech with the least positive content (all speeches were positive on balance). William Henry Harrison’s odd speech about the Romans had near the least emotional content, and was one of the least positive speeches.</p>
<h2>Conclusion</h2>
<p>This analysis of inauguration speeches comes at a time where the change of US presidential power has a different feel, even the inauguration speech. The preliminary analysis above shows that Trump’s speech was similar in topics to speeches for the last 40 or so years, and nothing notable in its emotional content.</p>
<p>This first start revealed a few interesting patterns, but a more sophisticated analysis might reveal something further.</p>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://randomjohn.github.io/tidy-text-inauguration-speeches/"> Upstate Data Analysis</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/MhLt96qFpjE"></a></div>