<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/analyzing-the-first-presidential-debate/"></div></div><div><a data-url="https://www.r-bloggers.com/analyzing-the-first-presidential-debate/" data-counturl="https://www.r-bloggers.com/analyzing-the-first-presidential-debate/" data-count="horizontal" data-text="Analyzing the first Presidential Debate" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://datascienceplus.com/analyzing-the-first-presidential-debate/"> DataScience+</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>A significant chunk of the data that we encounter on a daily basis is available in an unstructured, free text format. Hence, the ability to glean useful bits of information from this unstructured pile can be quite valuable.</p>
<p>In this post, we will attempt a basic analysis of the text from the first Presidential debate between Clinton and Trump. </p>
<p>A good part of this post involves data manipulation steps to convert the raw transcript text (of the debate) into a more structured/ ordered form, which you can then start analyzing – This initial data manipulation process to transform the raw text into a more structured form suitable for further analysis/modelling, is a key step in any text analytics effort, and hence a key focus point of this post.<br>
Post data transformation and structuring, we attempt to answer a few simple questions from the data (such as Who spoke more, Who interrupted more, Key discussion points etc). </p>
<p>You would not get any profound political insights from this analysis! But hopefully it will help showcase some of the most commonly used functions &amp; techniques for manipulating strings/ free text.</p>
<h2> Read the data in R </h2>
<p>A little googling gave me this <a target="_blank" rel="nofollow" href="https://www.washingtonpost.com/news/the-fix/wp/2016/09/26/the-first-trump-clinton-presidential-debate-transcript-annotated/">link</a> which has the entire transcript of the debate. You can either copy paste the content in a text file and read it into R or use web scraping to get the data in R. I will use the <a target="_blank" href="http://datascienceplus.com/goodreads-webscraping-and-text-analysis-with-r-part-1/">web scraping</a> approach here (without going into the scraping code in detail – since that’s a separate topic in itself)</p>
<pre>
library(rvest)
# Read the link
transcript_link &lt;- read_html(&quot;https://www.washingtonpost.com/news/the-fix/wp/2016/09/26/the-first-trump-clinton-presidential-debate-transcript-annotated/&quot;)

# I use a browser add in (Selector Gadget) to extract out the relevant html tag for the transcript 
# the tag is titled &quot;#main-content&quot; - I then extract out the content using the following functions from the rvest package
transcript &lt;- transcript_link %>% html_nodes(&quot;#main-content&quot;) %>% html_text()
</pre>
<h2> Structure the data </h2>
<p>Right now, the entire text is just one undifferentiated whole – As a prelude to any meaningful analysis, we would want to separate out the text corresponding to each of the 3 participants (i.e including the moderator)</p>
<h3>How do we do that?</h3>
<p>There are different ways in which you can attempt this problem – One possible approach is provided below (This need not be the most concise approach – In fact, I can think of at least one other solution which will result in more compact code. But since the objective of this post is to demonstrate some of the most useful string manipulation functions, we will go with this approach itself)</p>
<h3>So this is the approach:</h3>
<p>If you look at the transcript, the speaker name is highlighted in caps to indicate when a particular speaker starts talking (i.e. one of these 3 values – “CLINTON”, “TRUMP” or “HOLT”). We can think of these as markers in our text. And if we extract out the position of these markers, we can identify when a particular speaker starts talking. We use the <code>str_locate_all</code> function from <code>stringr</code> package for this.</p>
<pre>
# We have 3 different patterns to search for - which will include in our expression using the or operator '|'
# str_locate_all will give the index (start and end position) of all the matches
markers &lt;- str_locate_all(transcript, pattern = &quot;CLINTON|TRUMP|HOLT&quot;)

# This returns a list with one component - we extract out that component
markers &lt;- markers[[1]]

# Now markers is a matrix indicating the start and end positions
# We are only interested in the start positions, so we extract that out
markers &lt;- markers[,1]
</pre>
<p>Now markers has the starting index of when a particular speaker starts talking. As next step, we use the marker vector to separate out the conversation into chunks. As an example, look at the first 2 values of the markers vector: <code>markers[1:2]</code> which gives 1017 &amp; 2292</p>
<p>We can then use the base <code>substr</code> function to extract out these chunks. E.g.<br>
<code> substr(transcript, 1017, 2291)</code> will pull out the first chunk (spoken by Holt) from our text (You may have noticed that I have reduced the end index by 1 – Else, the code will also pick up the first letter of the next marker – C in this case (from CLINTON) )</p>
<p>Since we need to do this for the entire length of the markers vector, we put this code in a loop:</p>
<pre>
# Initialize a vector to store the results
res &lt;- vector(mode = &quot;character&quot;, length = length(markers) - 1)
for (i in 1:(length(markers)-1)) {
  res[i] &lt;- substr(transcript,markers[i],markers[i+1]-1)
  
}</pre>
<p>Ok. So now we have each chunk of the conversation as a separate value in a character vector.<br>
As final step, we need to separate out chunks related to Clinton and those related to Trump (Let’s exclude Holt for now). This is how we can do it:</p>
<p>Each element of our res vector starts off with the speaker name (i.e our marker). We can use the <code>grepl</code> function to search for these markers (grepl is logical grep and returns a True/False output)</p>
<p>So, for e.g. <code>grepl(&quot;CLINTON&quot;,res[[1]])</code> will return False, since it’s spoken by Holt whereas <code>grepl(&quot;CLINTON&quot;,res[[2]])</code> will return True since its spoken by Clinton.</p>
<p>Since we need to check this for each element in our res vector, we need a loop – But, rather than use an explicit for loop we will use the higher order function <code>sapply</code>. Finally, the output of sapply (which will return a logical vector) is used to subset the res vector. This is the final code:</p>
<pre>clinton &lt;- res[sapply(res,function(x) grepl(&quot;CLINTON&quot;,x))]
trump &lt;- res[sapply(res,function(x) grepl(&quot;TRUMP&quot;,x))]</pre>
<p>Great! So we finally have a more structured and ordered representation of our data. We now have separate vectors (represented by the variables “clinton” and “trump”) holding the text specific to each of these speakers.</p>
<h2> Analyzing the data </h2>
<p>Now that we have ordered the data as per the speaker, we can perform various different comparative analysis. I will showcase just a couple of basic analysis in this post.</p>
<h3>Who spoke more ? (i.e as per the number of words spoken)</h3>
<p>We can split the text into words using the <code>str_split</code> from the <code>stringr</code> package. As before, since we need to do this for each element in our vector, we would loop through the vector using <code>sapply</code> </p>
<pre>tot_words_clinton &lt;- unlist(sapply(clinton, function(x) str_split(x, &quot; &quot;)))

# This also returns some blank values which we exclude
tot_words_clinton &lt;- tot_words_clinton[tot_words_clinton != &quot;&quot;]
length(tot_words_clinton)</pre>
<p>The output is 6491 for Clinton vis-a-vis 8817 for Trump (Note: This may not be the exact number of words – For e.g. if we have some punctuation separated by spaces it may get extracted out as well. But this should still be fairly close. Also, I believe some of the word annotation functions (from the <code>openNLP</code> package for instance) should take care of this and give you a more precise number)</p>
<h3>What were the key topics discussed?</h3>
<p>A basic approach to this would be to generate a word frequency list and then review the list to get a sense of the discussion topics. We can do this as follows:</p>
<pre>
# We use the count function from the plyr package on the &quot;tot_words_clinton&quot; variable which has the &quot;bag-of-words&quot; 
# We then use the dplyr function arrange to sort the words as per descending frequency
word_freq = plyr::count(tot_words_clinton) %>% arrange(desc(freq))</pre>
<p>Quickly glancing through the list can help us identify relatively high frequency words such as “nuclear”, “jobs”, “police”, “economy”, “gun”, “debt” etc, which can help us get a sense of the key topics that got discussed.</p>
<p>However, there is a fair amount of manual effort involved in scrolling through the word list to identify words of interest. How can we more quickly pinpoint interesting words?</p>
<p>One slight improvement to the above code would be to filter out the “stop words” – i.e. common/high frequency words). The code for this would be as follows:</p>
<pre>
library(tm)
# Extract the list of common key words
stop_words &lt;- stopwords()

# Remove these words from our &quot;bag-of-words&quot; list
tot_words_clinton &lt;- tot_words_clinton[!(tot_words_clinton %in% stop_words)]</pre>
<p>Running a word frequency on this generates a list with around l00 lesser words making it a bit more easier to identify words of interest.</p>
<h3>Total number of interruptions</h3>
<p>As per this <a target="_blank" rel="nofollow" href="http://www.pbs.org/newshour/rundown/for-many-women-watching-trump-interrupt-clinton-51-times-was-unnerving-but-familiar/">article</a>, “Trump interrupted Clinton 51 times, while she interrupted him 17 times”. Can we get this from our data?</p>
<p>Well I tried an approach which gave me something close though not these exact numbers. The idea is as follows: If there were no interruptions, each conversation chunk ends with a complete sentence followed by an appropriate punctuation (a period or a question mark for example). Conversations which are incomplete is indicated with an ellipsis (…) in the transcript. For e.g. read the 11th element in the “clinton” vector <code>clinton[11]</code> which gives</p>
<pre><em>[1] &quot;CLINTON: And I have -- well, not quite that long. I think my husband did a pretty good job in the 1990s. I think a lot about what worked and how we can make it work again... &quot;</em></pre>
<p>So the number of incomplete conversations can be a rough indicator for the number of interruptions that a speaker encountered. We compute this as follows:</p>
<pre>
# Loop thru each element of our vector
# Use regular expr. to match the ellipsis pattern
sum(sapply(trump,function(x) grepl(&quot;[.]{3}&quot;,x)))
sum(sapply(clinton,function(x) grepl(&quot;[.]{3}&quot;,x)))
</pre>
<p>This gives a value of 40 for Clinton and 18 for Trump (which is, at least, a rough approximation of the actual values)</p>
<h2>What else can we do ?</h2>
<p>A lot more! For e.g. you may want to do a sentiment analysis and compare the scores for each speaker. What I find more interesting (and challenging) though, is to see how we can use Part of Speech (POS) tagging among other NLP techniques to glean more valuable information from the data.</p>
<p>For example, I came across this <a target="_blank" rel="nofollow" href="http://www.vox.com/2016/8/18/12423688/donald-trump-speech-style-explained-by-linguists">link</a> recently which talks about Trump’s “strange speaking style”. Can we use NLP to determine how well formed a sentence is, to analyze claims such as this? It will quite interesting to find out!</p>
<p>Hope you find this post useful. In case of any queries or inputs, please feel free to comment below. Thanks!</p>
<ul></ul>
<p><strong>
<p>Related Post</p>
<p>
<ol>
<li><a title="Permanent Link toGoodReads: Machine Learning (Part 3)" target="_blank" rel="bookmark" href="http://datascienceplus.com/goodreads-machine-learning-part-3/">GoodReads: Machine Learning (Part 3)</a></li>
<li><a title="Permanent Link toMachine Learning for Drug Adverse Event Discovery" target="_blank" rel="bookmark" href="http://datascienceplus.com/machine-learning-for-drug-adverse-event-discovery/">Machine Learning for Drug Adverse Event Discovery</a></li>
<li><a title="Permanent Link toGoodReads: Exploratory data analysis and sentiment analysis (Part 2)" target="_blank" rel="bookmark" href="http://datascienceplus.com/exploratory-data-analysis-and-sentiment-analysis/">GoodReads: Exploratory data analysis and sentiment analysis (Part 2)</a></li>
<li><a title="Permanent Link toGoodReads: Webscraping and Text Analysis with R (Part 1)" target="_blank" rel="bookmark" href="http://datascienceplus.com/goodreads-webscraping-and-text-analysis-with-r-part-1/">GoodReads: Webscraping and Text Analysis with R (Part 1)</a></li>
<li><a title="Permanent Link toEuro 2016 analytics: Who’s playing the toughest game?" target="_blank" rel="bookmark" href="http://datascienceplus.com/euro-2016-analytics-whos-playing-the-toughest-game/">Euro 2016 analytics: Who’s playing the toughest game?</a></li>
</ol></strong>
<div>
<a target="_blank" href="http://feeds.feedburner.com/~ff/datascienceplus?a=f-4lQjyf6IQ:zZJWBwvn9bk:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/datascienceplus?i=f-4lQjyf6IQ:zZJWBwvn9bk:D7DqB2pKExk" border="0"></a> <a target="_blank" href="http://feeds.feedburner.com/~ff/datascienceplus?a=f-4lQjyf6IQ:zZJWBwvn9bk:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/datascienceplus?d=qj6IDK7rITs" border="0"></a> <a target="_blank" href="http://feeds.feedburner.com/~ff/datascienceplus?a=f-4lQjyf6IQ:zZJWBwvn9bk:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/datascienceplus?d=yIl2AUoC8zA" border="0"></a>
</div>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="https://www.r-bloggers.com/analyzing-the-first-presidential-debate/"></div></div><div><a data-url="https://www.r-bloggers.com/analyzing-the-first-presidential-debate/" data-counturl="https://www.r-bloggers.com/analyzing-the-first-presidential-debate/" data-count="vertical" data-text="Analyzing the first Presidential Debate" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://datascienceplus.com/analyzing-the-first-presidential-debate/"> DataScience+</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/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/?s=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/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/coFSCOg_D34"></a></div>