<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/twitter-analysis-using-r-semantic-analysis-of-french-elections/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://enhancedatascience.com/2017/07/17/twitter-analysis-using-r/"> Enhance Data Science</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Last month the <a rel="nofollow" href="http://enhancedatascience.com/2017/05/17/french-election-viewed-through-twitter-a-semantic-analysis/" target="_blank">French elections viewed through Twitter: a semantic analysis </a>post showed how the two contenders were perceived on Twitter during three key events of the campaign (Macron leaks, presidential debate and election day). The goal of the post is to show how to perform this twitter analysis using R.</p>
<h2>Collecting tweets in real time with streamR (Twitter streaming API)</h2>
<p>To perform the analysis, I needed an important number of tweets and I wanted to use all of the tweets concerning the election. The Twitter search API is limited since you only have access to a sample of tweets. On the other hand, the streaming API allows you to collect the data in real-time and to collect almost all tweets. Hence, I used the streamR package.</p>
<p>So, I collected tweets on 60 seconds batch and saved them on .json files. The use of batches instead of one large file is to improve RAM consumption (Instead of reading and then subsetting one large file, you can do the subset on each of the batches and then merge them). Here is the code to collect the data with streamR.</p>
<pre>
###Loading my twitter credentials
load(&quot;oauth.Rdata&quot;)
##Collecting data
require('streamR')
i=1
while(TRUE)
{
 i=i+1
 filterStream( file=paste0(&quot;tweet_macronleaks/tweets_rstats&quot;,i,&quot;.json&quot;),
 track=c(&quot;#MacronLeaks&quot;), timeout=60, oauth=my_oauth,language = 'fr')
}
</pre>
<p>The code is doing an infinite loop (stopped manually), the filterStream function filters the Twitter stream according to the defined filter. Here, we only take the tweets containing #MacronLeaks which are in French.</p>
<h2>Tweets cleaning and pre-processing</h2>
<p>Now that the tweets are collected, they need to be cleaned and pre-processed. A raw tweet will contain links, tabulation, @, #, double spaces,  … that will influence the analysis. It will also contain stop words (stop words are very frequent words in the language such as ‘and’, ‘or, ‘with’, …).<br>
In addition to this, some tweets are retweeted (sometimes a lot) and may change the words and text distribution. Enough of the RT are kept to show that some tweets are more popular than others but most of them are removed to avoid them standing too much out of the crowd.</p>
<p>First, the saved tweets need to be read and merged:</p>
<pre>
require(data.table)
data.tweet=NULL
i=1
while(TRUE)
{
 i=i+1
 print(i)
 print(paste0(&quot;tweet_macronleaks/tweets_rstats&quot;,i,&quot;.json&quot;))

if (is.null(data.tweet))
 data.tweet=data.table(parseTweets(paste0(&quot;tweet_macronleaks/tweets_rstats&quot;,i,&quot;.json&quot;)))
 else
 data.tweet=rbind(data.tweet,data.table(parseTweets(paste0(&quot;tweet_macronleaks/tweets_rstats&quot;,i,&quot;.json&quot;))))
}
</pre>
<p>Then we only keep some of the RT. The retweet count is the indices of a given retweet, hence we only keep log(1+n) of the RT.</p>
<pre>
data.tweet[,min_RT:=min(retweet_count),by=text]
data.tweet[,max_RT:=max(retweet_count),by=text]
data.tweet=data.tweet[lang=='fr',]
data.tweet=data.tweet[retweet_count&amp;lt;=min_RT+log(max_RT-min_RT+1),]
</pre>
<p>Then, the text can be cleaned using function from the tm package</p>
<pre>
###Unaccent and clean the text
Unaccent &lt;- function(x) {
 x=tolower(x)
 x = gsub(&quot;@\\w+&quot;, &quot;&quot;, x) 
 x = gsub(&quot;[[:punct:]]&quot;, &quot; &quot;, x)
 x = gsub(&quot;[ |\t]{2,}&quot;, &quot; &quot;, x) 
 x = gsub(&quot;^ &quot;, &quot; &quot;, x) 
 x = gsub(&quot;http\\w+&quot;, &quot; &quot;, x) 
 x=tolower(x)
 x=gsub('_',' ',x,fixed=T)
 x
 
}
require(tm)
###Remove accents
data.tweet$text=Unaccent(iconv(data.tweet$text,from=&quot;UTF-8&quot;,to=&quot;ASCII//TRANSLIT&quot;))
##Remove top words
data.tweet$text=removeWords(data.tweet$text,c('rt','a',stopwords('fr'),'e','co','pr'))
##Remove double whitespaces
data.tweet$text=stripWhitespace(data.tweet$text)
</pre>
<h2>Tokenization and creation of the vocabulary</h2>
<p>Now that the tweets have been cleaned, they can be <a rel="nofollow" href="https://en.wikipedia.org/wiki/Tokenization_(lexical_analysis)" target="_blank">tokenized</a>. During this step, each tweet will be split into tokens of its different words, here each word corresponds to a token.</p>
<pre>
# Create iterator over tokens
tokens &lt;- space_tokenizer(data.tweet$text)
it = itoken(tokens, progressbar = FALSE)
</pre>
<p>Now a vocabulary can be created (it is a “summary” of the words distribution) based on the corpus. Then the vocabulary is pruned (very common and rare words are removed).</p>
<pre>
vocab = create_vocabulary(it)

vocab = prune_vocabulary(vocab,
 term_count_min = 5, 
 doc_proportion_max = 0.4,
 doc_proportion_min = 0.0005)
vectorizer = vocab_vectorizer(vocab, 
 grow_dtm = FALSE, 
 skip_grams_window = 5L)

tcm = create_tcm(it, vectorizer)
</pre>
<p>Now, we can create the word embedding, in this example, I used a <a rel="nofollow" href="https://nlp.stanford.edu/pubs/glove.pdf" target="_blank">glove embedding</a> to learn vectors representations of the words. The new vector space has around 200 dimensions.</p>
<pre>
glove = GlobalVectors$new(word_vectors_size = 200, vocabulary = vocab, x_max = 100)
glove$fit(tcm, n_iter = 200)
word_vectors &lt;- glove$get_word_vectors()
</pre>
<h2>How to finish our twitter analysis with Tsne</h2>
<p>Now that the words are vectors, we would like to plot them in two dimensions to show the meaning of the words in an appealing (and understandable) way. The number of dimension needs to be reduced to two, to do so, we will use T-sne. <a rel="nofollow" href="https://lvdmaaten.github.io/tsne/" target="_blank">T-sne</a> is a non-parametric dimensionality reduction algorithm and tends to perform well on word embedding. R has a package (actually two) to perform Tsne, we will use the most recent one  <a rel="nofollow" href="https://cran.r-project.org/web/packages/Rtsne/Rtsne.pdf" target="_blank">Rtsne.</a><br>
To avoid overcrowding in our plot and reduce computing time, only words with more than 50 appearances will be used.</p>
<pre>
require('Rtsne')
set.seed(123)
word_vectors_sne=word_vectors[which(vocab$vocab$doc_counts>50&amp;!rownames(word_vectors)%in%stopwords('fr')),]
tsne_out=Rtsne(word_vectors_sne,perplexity =2,initial_dims = 200,dims = 2)
DF_proj=data.frame(x=tsne_out$Y[,1],y=tsne_out$Y[,2],word=rownames(word_vectors_sne))
</pre>
<p>Now that the projection in 2 dimensions has been done, to color the plot we’d like to know which contenders is assigned to each word. To do so, a dictionary is created with the names and pseudo of each of the contenders and the distance from every word to each of these pseudos is computed.<br>
For instance, to assign a candidate to the word ‘democracy’, the minimum distance between ‘democracy’ and ‘mlp’, ‘marine’, ‘fn will be computed. The same thing will be done between ‘democracy’ and ‘macron’, ’em’, ’emmarche’. If the first distance is the smallest then ‘democracy’ will be assigned to Marine Le Pen, otherwise, it will be assigned to Emmanuel Macron.</p>
<pre>
require(ggplot2)
require(ggrepel)
DF_proj=data.table(DF_proj)
DF_proj$count=vocab$vocab$doc_counts[which(vocab$vocab$doc_counts>500&amp; !(rownames(word_vectors)%in%stopwords('fr')))]
DF_proj=DF_proj[word!='NA']

distance_to_candidat=function(word_vectors,words_list,word_in)
{
 max(sim2(word_vectors[words_list,,drop=F],word_vectors[word_in,,drop=F]))
}
closest_candidat=function(word_vectors,mot_in)
{
 mot_le_pen=c('marine','pen','lepen','fn','mlp')
 mot_macron=c('macron','emmanuel','em','enmarche','emmanuelmacron')
 dist_le_pen=distance_to_candidat(word_vectors,mot_le_pen,mot_in)
 dist_macron=distance_to_candidat(word_vectors,mot_macron,mot_in)
 if (dist_le_pen>dist_macron)
 'Le Pen'
 else
 'Macron'
}
DF_proj[,word:=as.character(word)]
DF_proj=DF_proj[word!=&quot;&quot;]
DF_proj[,Candidat:=closest_candidat(word_vectors,word),by=word]

require(plotly)
gg=ggplot(DF_proj,aes(x,y,label=word,color=Candidat))+geom_text(aes(size=sqrt(count+1)))
ggplotly(gg)
</pre>
<p>You can get our latest news on Twitter:</p>
<p> </p>
<p> </p>
<p>The post <a rel="nofollow" href="http://enhancedatascience.com/2017/07/17/twitter-analysis-using-r/" target="_blank">Twitter analysis using R (Semantic analysis of French elections)</a> appeared first on <a rel="nofollow" href="http://enhancedatascience.com/" target="_blank">Enhance Data Science</a>.</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="http://enhancedatascience.com/2017/07/17/twitter-analysis-using-r/"> Enhance Data Science</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/hgMmkMnhfBQ" height="1"></a></div>