<p>This post was originally published on <a href="https://www.smartcat.io/blog/2017/asknasa-whats-the-optimal-time-for-aliens-to-invade-earth/">SmartCat</a>, 22 Feb 2017.</p><p>My inaugural blog as a Data Science Consultant for <a href="https://www.smartcat.io/">SmartCat</a>. The code that accompanies the analyses presented here is available at <a href="https://github.com/smartcat-labs/NASATwitterAnalytics">the respective GitHub repository</a>. On how to use R to estimate the optimal time during the day for aliens to invade Earth and a few more interesting things.<br></p><p>A few days ago, NASA has announced <a href="https://www.nasa.gov/press-release/nasa-to-host-news-conference-on-discovery-beyond-our-solar-system/">a press conference</a> citing a “… Discovery Beyond Our Solar System”, and I always tend to get excited about such news. I have learned about the #askNASA hashtag used for public and media to approach NASA with their questions on Twitter. And when I hear the word “hashtag”, social media analytics is what first comes to mind. The I thought, what could I find out by studying tweets on #askNASA? Nothing much, unfortunately, because the number of such tweets doesn’t exactly skyrocket (many questions are posted there, of course, but the volume of tweets is far below what one needs for a serious social media analytics study). Ok, then: I will study the whole twitterverse of NASA and NASA related accounts, in order to discover what is the relative position of #AskNASA in the semantic space of what’s being tweeted from NASA. I have used <a href="https://cran.r-project.org/web/packages/twitteR/">{TwitteR}</a> to access the <a href="https://dev.twitter.com/rest/public/search">Twitter Search API</a> for retrospective tweets from almost all of the NASA Twitter accounts listed on <a href="https://www.nasa.gov/socialmedia/">https://www.nasa.gov/socialmedia/</a> (I haven’t included the personal accounts of NASA astronauts; only the main account, and then everything found under the following categories: NASA Centers &amp; Facilities, Organizations &amp; Programs, Missions &amp; Topics, plus NASAAstronauts and NASAPeople; 141 Twitter account in total). I have also accessed the Twitter Search API to collect all recent tweets with the #askNASA hashtag there. In total, I have produced a collection of 1575 tweets with the #askNASA hashtag; these were cleaned from all tweets posted on behalf of NASA and NASA related accounts. From the NASA accounts alone, I was able to get to 255,241 tweets - following a several hours long exercise of the userTimeline() {TwitteR} function.<br></p><p>While scraping with {TwitteR} mindlessly, I was planning the analysis, and my thoughts started wondering around all the cool work that people at NASA do… What will they announce today? A new exoplanet, I can bet. People are crazy about exoplanets, and the aliens, and the SETI program, and Astrobiology, and all that stuff. A Twin Earth! However, nobody realizes, I thought, that the potential discovery of this Earth on behalf of some technologically advanced alien civilization could pose a real existential treat for us humans: a true global catastrophic risk. And with all their antennas, golden plates with pictographs and Bach on their interstellar probes… nobody seems to worry about Sir Stephen Hawking’s well-reasoned warning on how intelligent aliens could destroy humanity (even not he himself, c.f. <a href="http://www.space.com/29999-stephen-hawking-intelligent-alien-life-danger.html">“Stephen Hawking: Intelligent Aliens Could Destroy Humanity, But Let’s Search Anyway”</a> - says Hawking)! Anyways, it was probably around the third or fourth glass of wine in the Belgrade Cafe from where I’ve left {TwitteR} do the job from my netbook when I’ve realized what I want to do this time with R: I will estimate the optimal time during the day for Aliens to invade our planet by analyzing the daily oscillation in the sentiment and volume of tweets from NASA accounts. Assumption: if aliens somehow figure out where we live, that will be because of these guys with big radio-antennas. Next: given that whatever alien civilization decides to invade Earth, they will certainly be so technologically advanced to immediately discover the very source of our quest for them. Finally, given their technological supremacy, they will be available to analyze all the necessary information to ensure the success of their mission: including our (precious!) tweets.<br></p><p>And here it is, with a little help from {tm.plugin.sentiment}, {dplyr} and {ggplot2}:<br></p><pre>emoHours &lt;- tweetsDF %>% <br>group_by(Hour) %>%<br>summarise(tweets = n(),<br>  positive = length(which(Polarity > 0)),<br>  neutral = length(which(Polarity == 0)),<br>  negative = length(which(Polarity &lt; 0))<br>)<br>emoHours$positive &lt;- emoHours$positive/emoHours$tweets<br>emoHours$neutral &lt;- emoHours$neutral/emoHours$tweets<br>emoHours$negative &lt;- emoHours$negative/emoHours$tweets<br>emoHours$Hour &lt;- as.numeric(emoHours$Hour)<br>emoHours$Volume &lt;- emoHours$tweets/max(emoHours$tweets)<br>emoHours &lt;- emoHours %>%<br>gather(key = Measure,<br>  value = Value,<br>  positive:Volume<br>)<br>ggplot(emoHours, aes(x = Hour, y = Value, color = Measure)) +<br>geom_path(size = .25) +<br>geom_point(size = 1.5) +<br>geom_point(size = 1, color = &quot;White&quot;) +<br>ggtitle(&quot;Optimal Time to Invade Earth&quot;) +<br>scale_x_continuous(breaks = 0:23, labels = as.character(0:23)) +<br>theme_bw() +<br>theme(plot.title = element_text(size = 12)) +<br>theme(axis.text.x = element_text(size = 8, angle = 90))</pre><p>Figure 1. Optimal time to invade Earth w. {tm.plugin.sentiment}, {dplyr}, and {ggplot2}</p><p>The tweetsDF data frame becomes available after running the previous chunks of code that you will find in the <a href="https://github.com/smartcat-labs/NASATwitterAnalytics/blob/master/SC_TwitteR.R">GitHub repo</a> for this blog post. The Polarity column comes from the application of {tm.plugin.sentiment} functions over a {tm} pre-processed corpus of all 255,241 tweets that were collected from NASA’s accounts:</p><pre>### --- Sentiment Analysis<br># - as {tm} VCorpus<br>nasaCorpus &lt;- VCorpus(VectorSource(tweetsDF$text))<br># - {tm.plugin.sentiment} sentiment scores<br># - Term-Document Matrix<br>nasaTDM &lt;- TermDocumentMatrix(nasaCorpus,<br>                          control = list(tolower = TRUE,<br>                          removePunctuation = TRUE,<br>                          removeNumbers = TRUE,<br>                          removeWords = list(stopwords(&quot;english&quot;)), <br>                          stripWhitespace = TRUE,<br>                          stemDocument = TRUE,<br>                          minWordLength = 3,<br>                          weighting = weightTf))<br><br># - {tm.plugin.sentiment} polarity score<br># - NOTE: that would be (n-p)/(n+p)<br>nasaPolarity &lt;- polarity(nasaTDM)<br>sum(nasaPolarity != 0)<br>tweetsDF$Polarity &lt;- nasaPolarity</pre><p>The optimal time for Alien invasion is obviously somewhere between 7:00 and 9:00 in the morning (NOTE for the aliens: all times are GMT). All tweets were categorized as neutral, positive,  or negative in respect to their polarity, which is given as (n-p)/(n+p), n being the count of negative and p of positive words in the respective tweets. Then, instead of going for a time series analyses, I have simply grouped all tweets per hour of the day in which they have occurred, recalculating the counts of positive, negative, and neutral tweets into proportions of total tweets per hour. Thus, the vertical axis presents proportion of tweets per hour. The Volume variable is simply a rescaling of the plain simple counts of number of tweets per hour by the maximum count found in the data set, so that this can be conveniently presented on a 0 to 1 scale in the chart. And what we see is that between 7:00 and 9:00, approximately, an anomaly in the hourly distribution of tweets from NASA’s accounts takes place: a sudden increase in the proportion of neutral and negative tweets, accompanied by the drop in the volume of tweets occurring. So that’s when we’re moody and not relaxed, and probably tweeting less given the pressure of the daily work routine before lunch: the ideal time for an Alien civilization to invade.</p><p>Of course, technologically advanced aliens, who know statistics very well, could as well ask whether the described phenomenon is simply a by product of the increased measurement error related to the quite obvious drop in the sample sizes for the respective, invasion-critical hours…</p><p>Putting aside the question of alien invasion, I am really very interested to learn from NASA today what is that was discovered beyond the limits of the Solar system. To prove how the discoveries of potentially habitable exoplanets are popular, the following analysis was conducted. In the first step, we simply concatenate all tweets originating from the same account, while treating the tweets with the #askNASA hashtag as a separate group (i.e. as it was a Twitter account in itself). Given that I was interested in the account level of analysis here, and provided that individual tweets offer too little information for typical BoW approaches in text mining, this step is really justified. Then, I have produced a typical Term-Document Matrix from all available tweets, preserving all terms beginning with “@” or “#” there, and then cleaned the matrix from everything else. Finally, the term counts were turned into binary (present/absent) information in order to compute the Jaccard similarity coefficients across the accounts:</p><pre>tweetTexts &lt;- tweetsDF %>%<br>group_by(screeName) %>%<br>summarise(text = paste(text, collapse = &quot; &quot;))<br># - accNames is to be used later:<br>accNames &lt;- tweetTexts$screeName<br>accNames &lt;- append(accNames, &quot;askNASA&quot;)<br>tweetTexts &lt;- tweetTexts$text<br>askNasaText &lt;- paste(dT$text, collapse = &quot;&quot;)<br>tweetTexts &lt;- append(tweetTexts, askNasaText)<br>tweetTexts &lt;- enc2utf8(tweetTexts)<br>tweetTexts &lt;- VCorpus(VectorSource(tweetTexts))<br><br># - Term-Doc Matrix for this:<br>removePunctuationSpecial &lt;- function(x) {<br> x &lt;- gsub(&quot;#&quot;, &quot;HASHCHAR&quot;, x)<br> x&lt;- gsub(&quot;@&quot;, &quot;MONKEYCHAR&quot;, x)<br> x &lt;- gsub(&quot;[[:punct:]]+&quot;, &quot;&quot;, x)<br> x &lt;- gsub(&quot;HASHCHAR&quot;, &quot;#&quot;, x)<br> x &lt;- gsub(&quot;MONKEYCHAR&quot;, &quot;@&quot;, x)<br> return(x)<br>}<br><br>tweetTexts &lt;- tm_map(tweetTexts,<br>            content_transformer(removePunctuationSpecial),<br>            lazy = TRUE)<br><br>tweetsTDM &lt;- TermDocumentMatrix(tweetTexts,<br>                   control = list(tolower = FALSE,<br>                           removePunctuation = FALSE,<br>                           removeNumbers = TRUE,<br>                           removeWords = list(stopwords(&quot;english&quot;)),<br>                           stripWhitespace = TRUE,<br>                           stemDocument = FALSE,<br>                           minWordLength = 3,<br>                           weighting = weightTf))<br># - store TDM object:<br>saveRDS(tweetsTDM, &quot;tweetsTDM.Rds&quot;)<br><br># - extract only mention and hashtag features:<br>tweetsTDM &lt;- t(as.matrix(tweetsTDM))<br>w &lt;- which(grepl(&quot;^@|^#&quot;, colnames(tweetsTDM)))<br>tweetsTDM &lt;- tweetsTDM[, -w]<br># - keep only mention and hashtag features w. Freq > 50<br>wK &lt;- which(colSums(tweetsTDM) > 10)<br>tweetsTDM &lt;- tweetsTDM[, wK]<br># - transform to binary for Jaccard distance<br>wPos &lt;- which(tweetsTDM > 0, arr.ind = T)<br>tweetsTDM[wPos] &lt;- 1<br># - Jaccard distances for accounts and #asknasa:<br>simAccounts &lt;- dist(tweetsTDM, method = &quot;Jaccard&quot;, by_rows = T)<br>simAccounts &lt;- as.matrix(simAccounts)</pre><p> The following {igraph} works this way: each account - of which one, be reminded, #askNASA is not really an account but represents information on all tweets with the respective hashtag- points to the account which is most similar to it in respect to the Jaccard distance computed from the presence and absence of mentions and hashtags used. So this is more some proxy of a “social distance” between accounts than a true distributional semantics measure. It can be readily observed that #askNASA points to @PlanetQuest as its nearest neighbor in this analysis. The Jaccard distance was used since I am not really into using typical Term-Document Count Matrices in analyzing tweets; they simply convey too sparse an information for a typical approach to make any sense.<br></p><p>Figure 2.Social Network of NASA Twitter accounts + #askNASA. {igraph}</p><br><p>Goran S. Milovanović, PhD<br><a href="http://smartcat/">Data Science Consultant, SmartCat</a></p>