Emoji data science in R: A tutorial

Over the past few months, PRISMOJI has diligently blazed new trails in the emerging field of emoji data science. Today, in a commitment to open data science and open data journalism, we’re proud to present our first tutorial on emoji data science in R. This tutorial is meant to complement our latest article on Emojipedia: “The resistance will be emojified ✊🏽.” (You can find raw code and data to accompany this tutorial in the accompanying Github repository here.)

Part 1 💻: Downloading Twitter data using R

Downloading Twitter data using R has been fairly well documented. Here, we’ll access the Twitter Search API using the twitteR package. First, log into your twitter account, then head to https://apps.twitter.com/, click “Create New App”, fill in the details, and click “Create your Twitter application.” Now click “Keys and Access Tokens”, and click “Create my access token.”

The resulting screen should provide you four strings that you’ll need to access Twitter data: “Consumer Key (API Key)”, “Consumer Secret (API Secret)”, “Access Token”, and “Access Token Secret.” These are all uniquely associated with your Twitter account and you should not share these with anyone else. Now, we can download Twitter data using just a few lines of code.

This code snippet will get you authenticated with Twitter (just replace XXX with the value of each string from above):

Now, we’re ready to pull tweets. We use the searchTwitter function which requires us to specify a search term; here, we’ll use #nobannowall. Bogdan Rau has a good overview of other types of valid search terms, but in general, anything that works at twitter.com/search should work here. The n parameter is important. Generally, we’ve found that you can request n=100,000 tweets which will usually lead to rate-limiting but will still give you results within about 30-60 minutes. (For sparse hashtags, it will return fewer tweets.)

In terms of date range, the Search API in general only goes back 7-10 days at most, and is often delayed by a day or so for current tweets, so keep this in mind. An important note: for a highly popular hashtag, the Search API does not return a representative distribution of tweets (i.e. if you request tweets from Feb. 1 – Feb 5, it’s likely you’ll only get tweets from Feb. 5). One workaround is to pull tweets from different days separately. Also, we remove retweets because this helps us get cleaner emoji data but you can toggle this parameter. df here returns a dataset with many variables, most of which are unnecessary for our work; you can choose to retain them if you wish.

Part 2 ✍🏼: Using Unicode pattern matching to extract emojis from tweets

Using the methodology described in Part 1, we read in tweets, separately for Jan. 28 and Jan. 29, for five different hashtags: #NoBanNoWall, #NoMuslimBan, #NotMyPresident, #TheResistance, and #WomensMarch. (Here is a good resource for hashtag brainstorming which will give you a network of related hashtags for a given seed hashtag.)

Within each of the five resulting datasets, we deduplicated tweets by both URL and user name. (For example, there are often Twitter bot accounts that tweet multiple times, using identical text and/or emojis, which can distort results.) We then combined these into one dataset which you can find on Github called “tutorial_tweets_raw.csv.”

We then download two emoji dictionaries – one provided by Lauren Ancona and Chris Tufts whose earlier work on emojis in Philadelphia was an invaluable starting point in our own work, and the other by Jessica Peterka-Bonetta who built a powerful emoji decoder specifically for R. We combine these dictionaries into a new dataset called emojis.

⁎ As a caveat, both of these dictionaries contain only 842 emojis and are slightly out of date with the latest and greatest emojis. Updating these to be current would be really cool! Please drop us a line if you get a chance to work on this 🙂

[UPDATE (10/5/2017): The linguist Kate Lyons of the University of Illinois – who has done great work producing emoji maps of San Francisco – has created an updated emoji dictionary covering 2,204 emojis, including skin tone emojis! This is a tremendous contribution to emoji research and we look forward to using her dictionary going forward.]

Using our new emoji dictionary – which has a column named rencoding to represent
how R represents each emoji – we compare our dataset of 57,522 tweets with our dataset of 842 emojis and create a full matrix (57,522 x 842) to assess the presence of each emoji in each tweet. This is the most time-consuming part but using sapply and vectorization, it runs in less than 3 minutes here. We save the resultant matrix as tweets.emojis.matrix and then run colSums across each column to compute an initial emoji count.

Part 3 📊: Visualizing emojis

The table above is nice to look at it, but is there a prettier way we can visualize the data in emojis.count? A simple approach is to make a bar chart of top emojis where we insert the appropriate emoji image on top of each of the bars using the annotation_custom function in ggplot. (If you’re trying to replicate this in other languages, i.e. Python, try searching for custom plot annotations.) In order to do this, we first read in all 842 emoji images using grid::rasterGrob.

⁎ We can tweak the tweets assignment in Part 2 above, right before we run create tweets.emojis.matrix, to replicate the above analysis for a given subset of the dataset instead of running it on all tweets.

Part 4 🤓: Visualizing emojis (Advanced)

The next step after visualizing the top emojis in the overall dataset is to compare emoji frequency between two different subsets of the data. In order to do this efficiently, we first create a reduced representation of the tweets.emojis.matrix that has the original tweet appended with a string of all the unique emojis in that tweet.

Now, we define two different subsets of the data, then count the emojis in those subsets based on tweets.emojis. For example, let’s compare emoji usage between tweets mentioning #womensmarch and tweets mentioning #theresistance. First, we create the two subsets, count emojis in each subset, and create a combined dataset to facilitate comparisons:

The key parameter here is k, which sets a threshold for how many emojis we want in the final comparison dataset, and df.b more broadly defines that dataset. (Here, the comparison dataset contains emojis that rank in the top 50 in either subset, have a frequency of at least 5 in either dataset, and are greater than zero in both datasets. Another useful parameter option could be to threshold on abs(logor) being greater than 0.5 or 1 which will yield only the most polarized emojis. Regardless, we print nrow(df.b) to give us a sense of how many emojis the thresholding criteria yield.

Here’s a snippet of the first and last 5 observations from the resulting emoji comparison dataset, emojis.comp.p:

The results are interesting and seem intuitive. Pink hearts and celebratory emojis over-index on #womensmarch while more activist emojis and New York-specific ones overindex on #theresistance. (Emojis more associated with the first dataset we defined, df.1, end up with a positive odds ratio, and vice-versa. Odds ratios close to 0 indicate emojis that are used equally frequently with both hashtags.)

Now, visualizing the two-way spread of emojis across both datasets is trivial given our earlier foundations; namely, we can use custom annotations to plot log odds ratios and overall densities on an x-y plane.

Part 5 🚀: Next Steps

In our next tutorial, we’ll dig a little deeper into text analysis of datasets with emojis. Meanwhile, given this foundation of emoji data science, there are a few next steps we can imagine:

emoji network visualizations to understand emoji-emoji cooccurrence (i.e. Mailchimp published a great analysis in 2015)

interactive emoji dashboards (i.e. we’re big fans of the University of Virginia’s Twitter Visualization Project and their time series plot of emoji usage during the presidential debates.)

updating the above protocol to include the latest batch of 1,851 emoji characters in Unicode 9.0

using machine learning and natural language processing to better leverage the text data in tweets to understand what emojis mean

replicating the above protocol for Instagram and other social media platforms

If you’re interested in working with us on any of the above – or have your own ideas – email us at hello@prismoji.com! We’re happy to chat with prospective interns, especially people with data science or engineering backgrounds who are natural storytellers and can see the forest from the trees.

Hi,
Firstly, thank you for open sourcing this code. I just wanted to point out that there needs to be some quality check done on this code, as it contains a lot of bugs. More specifically, I am stuck in the code for Part 2, under the ‘create emoji count dataset’ comment. There seem to be quite a few syntax errors. Is it possible for you to take another look at the code and provide a more correct version?