<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/comparing-trump-and-clintons-facebook-pages-during-the-us-presidential-election-2016/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://datascienceplus.com/comparing-trump-and-clintons-facebook-pages-during-the-us-presidential-election-2016/"> R Programming – DataScience+</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>R has a lot of packages for users to analyse posts on social media. As an experiment in this field, I decided to start with the biggest one: Facebook.</p>
<p>I decided to look at the Facebook activity of <a rel="nofollow" href="https://www.facebook.com/DonaldTrump/" target="_blank">Donald Trump</a> and <a rel="nofollow" href="https://www.facebook.com/hillaryclinton/" target="_blank">Hillary Clinton</a> during the 2016 presidential election in the United States.</p>
<p>The winner may be more famous for his <a rel="nofollow" href="https://twitter.com/realDonaldTrump" target="_blank">Twitter account</a> than his Facebook one, but he still used it to great effect to help pick off his Republican rivals in the primaries and to attack Hillary Clinton in the general election.</p>
<p>For this work we’re going to be using the <a rel="nofollow" href="https://cran.r-project.org/web/packages/Rfacebook/index.html" target="_blank">Rfacebook</a> package developed by Pablo Barbera, plus his excellent <a rel="nofollow" href="https://github.com/pablobarbera/Rfacebook" target="_blank">how-to guide</a>.</p>
<p>The first thing to do is to generate an access token from <a rel="nofollow" href="https://developers.facebook.com/tools/explorer" target="_blank">Facebook’s developer portal</a>. Keep it anonymous (otherwise you’re gifting the world access to your account) and save it in your environment.</p>
<pre>
library(Rfacebook)
options(scipen = 999)
token &lt;- &quot;Your token goes here&quot;</pre>
<p>The next thing to do is to use the <code>getPage()</code> function to retrieve all the posts from each candidate.</p>
<p>I’m going to start the clock on January 1, 2016 and end it the day after the election on November 9, 2016 (which means it will stop on election day, the day before)</p>
<pre>
trump &lt;- getPage(&quot;donaldtrump&quot;, token, n = 5000, since='2016/01/01', until='2016/11/09')
clinton &lt;- getPage(&quot;hillaryclinton&quot;, token, n = 5000, since='2016/01/01', until='2016/11/09')</pre>
<h3>Caveat: The data doesn’t seem to contain all Trump and Clinton’s Facebook posts</h3>
<p>I <a rel="nofollow" href="https://www.reddit.com/r/rstats/comments/6zlijv/missing_posts_using_rfacebook/" target="_blank">ran the commands several times</a> and got 545 posts for Trump and 692 posts for Clinton. However, I think I may have got more results the first time I ran the commands. I also searched their pages via Facebook and came up with some posts that don’t appear in the R datasets. If you have a solution for this, please let me know!</p>
<p>In the meantime, we will work with what we have</p>
<p>We want to calculate the average number of likes, comments and shares for each month for both candidates. Again, we will be using Pablo’s code for a while here.</p>
<p>First up, we will format the date:</p>
<pre>format.facebook.date &lt;- function(datestring) {
 date &lt;- as.POSIXct(datestring, format = &quot;%Y-%m-%dT%H:%M:%S+0000&quot;, tz = &quot;GMT&quot;)
 }</pre>
<p>Then we will use his formula to calculate the average likes, comments and shares (metrics) per month:</p>
<pre>
aggregate.metric &lt;- function(metric) {
 m &lt;- aggregate(page[[paste0(metric, &quot;_count&quot;)]], list(month = page$month),
 mean)
 m$month &lt;- as.Date(paste0(m$month, &quot;-15&quot;))
 m$metric &lt;- metric
 return(m)
 }</pre>
<p>Now we run this data for both candidates:</p>
<pre>#trump
 page &lt;- trump
 page$datetime &lt;- format.facebook.date(page$created_time)
 page$month &lt;- format(page$datetime, &quot;%Y-%m&quot;)
 df.list &lt;- lapply(c(&quot;likes&quot;, &quot;comments&quot;, &quot;shares&quot;), aggregate.metric)
 trump_months  head(trump_months)
 <em>month x metric
1 2016-01-15 17199.93 likes
2 2016-02-15 15239.63 likes
3 2016-03-15 22616.28 likes
4 2016-04-15 19364.17 likes
5 2016-05-15 14598.30 likes
6 2016-06-15 32760.68 likes</em></pre>
<pre>#clinton
 page &lt;- clinton
 page$datetime &lt;- format.facebook.date(page$created_time)
 page$month &lt;- format(page$datetime, &quot;%Y-%m&quot;)
 df.list &lt;- lapply(c(&quot;likes&quot;, &quot;comments&quot;, &quot;shares&quot;), aggregate.metric)
 clinton_months &lt;- do.call(rbind, df.list)</pre>
<p>Before we combine them together, let’s label them so we know who’s who:</p>
<pre>
trump_months$candidate &lt;- &quot;Donald Trump&quot;
clinton_months$candidate &lt;- &quot;Hillary Clinton&quot;
both &lt;- rbind(trump_months, clinton_months)</pre>
<p>Now we have the data, we can visualise it. This is a neat opportunity to have a go at <a rel="nofollow" href="http://ggplot2.tidyverse.org/reference/facet_grid.html" target="_blank">faceting</a> using ggplot2.</p>
<p>Faceting is when you display two or more plots side-by-side for easy at-a-glance comparison.</p>
<pre>library(ggplot2)
library(scales)

p &lt;- ggplot(both, aes(x = month, y = x, group = metric)) + geom_line(aes(color = metric)) +
 scale_x_date(date_breaks = &quot;months&quot;, labels = date_format(&quot;%m&quot;)) + ggtitle(&quot;Facebook engagement during the 2016 election&quot;) + labs(y = &quot;Count&quot;, x = &quot;Month (2016)&quot;, aesthetic='Metric') + theme(text=element_text(family=&quot;Browallia New&quot;, color = &quot;#2f2f2d&quot;)) + scale_colour_discrete(name = &quot;Metric&quot;)

#add in a facet
p &lt;- p + facet_grid(. ~ candidate)
p</pre>
<h2>Analysis</h2>
<p>Clearly Trump’s Facebook engagement got far better results than Clinton’s. Even during his ‘off months’ he received more likes per page on average than Clinton managed at the height of the general election.</p>
<p>Trump’s comments per page also skyrocketed during October and November as the election neared.</p>
<p>Hillary Clinton enjoyed a spike in engagement around June. It was a good month for her: she was confirmed as the Democratic nominee and received the endorsement of President Obama.</p>
<h3>Themes</h3>
<p>Trump is famous for using <a rel="nofollow" href="http://blog.dilbert.com/post/160986020961/goodbye-isis-hello-losers" target="_blank">nicknames</a> for his political opponents. We had low-energy Jeb, Little Marco, Lyin’ Ted and then Crooked Hillary.</p>
<p>The first usage of <a rel="nofollow" href="https://www.facebook.com/DonaldTrump/videos/10156970395965725/" target="_blank">Crooked Hillary in the data</a> came on April 26. A look through his Twitter feed shows he seems to have decided on Crooked Hillary around this time as well.</p>
<p>#DrainTheSwamp was one of his later hashtags, making the <a rel="nofollow" href="https://www.facebook.com/DonaldTrump/videos/10157933794000725/?comment_id=10157933829495725&comment_tracking=%7B%22tn%22%3A%22R%22%7D" target="_blank">first appearance in the data</a> on October 20, just a few weeks shy of the election on November 8.</p>
<p>Clinton meanwhile mentioned her rival’s surname in about a quarter of her posts. Her most popular ones were almost all on the eve of the election exhorting her followers to vote.</p>
<p>Of her earlier ones, only her New Year message and <a rel="nofollow" href="https://www.facebook.com/hillaryclinton/videos/1158234167566444/" target="_blank">one from March appealing to Trump’s temperament</a> resonated as strongly.</p>
<h2>Conclusion</h2>
<p>It’s frustrating that the API doesn’t seem to retrieve all the data.<br>
Nonetheless, it’s a decent sample size and shows that the Trump campaign was far more effective than the Clinton one on Facebook during the 2016 election.</p>
<ul></ul>
<p><strong>
<p>Related Post</p>
<p>
<ol>
<li><a rel="nofollow" href="https://datascienceplus.com/analyzing-obesity-across-usa/" title="Permanent Link toAnalyzing Obesity across USA" target="_blank">Analyzing Obesity across USA</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/can-we-predict-flu-deaths-with-machine-learning-and-r/" title="Permanent Link toCan we predict flu deaths with Machine Learning and R?" target="_blank">Can we predict flu deaths with Machine Learning and R?</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/graphical-presentation-of-missing-data-vim-package/" title="Permanent Link toGraphical Presentation of Missing Data; VIM Package" target="_blank">Graphical Presentation of Missing Data; VIM Package</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/creating-graphs-with-python-and-goopycharts/" title="Permanent Link toCreating Graphs with Python and GooPyCharts" target="_blank">Creating Graphs with Python and GooPyCharts</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/visualizing-tennis-grand-slam-winners-performances/" title="Permanent Link toVisualizing Tennis Grand Slam Winners Performances" target="_blank">Visualizing Tennis Grand Slam Winners Performances</a></li>
</ol></strong>
	<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://datascienceplus.com/comparing-trump-and-clintons-facebook-pages-during-the-us-presidential-election-2016/"> R Programming – 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 rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/vm5u8UbUJdA" height="1"></a></div>