Analyzing Twitter Trends with TwitteR

Avatar
Posted on Apr 22, 2014

[Best_Wordpress_Gallery gallery_type="thumbnails" theme_id="1" gallery_id="13" sort_by="order" order_by="asc" show_search_box="0" search_box_width="180" image_column_number="5" images_per_page="30" image_title="none" image_enable_page="1" thumb_width="200" thumb_height="150" thumb_click_action="undefined" thumb_link_target="undefined" popup_fullscreen="0" popup_autoplay="0" popup_width="800" popup_height="500" popup_effect="fade" popup_interval="5" popup_enable_filmstrip="1" popup_filmstrip_height="70" popup_enable_ctrl_btn="1" popup_enable_fullscreen="1" popup_enable_info="1" popup_info_always_show="0" popup_enable_rate="0" popup_enable_comment="1" popup_hit_counter="0" popup_enable_facebook="1" popup_enable_twitter="1" popup_enable_google="1" popup_enable_pinterest="0" popup_enable_tumblr="0" watermark_type="none" watermark_link="http://web-dorado.com"]

Contributed by Kim Johnson. Kim took R002 class with Vivian Zhang(Data Science by R, Intensive beginner level) in Feb-Mar, 2014 and earned "Extraordinary standing" certificate(the highest honor you can earn in the class).The post was based on her final project submission and demostration.


This post will show you how to access Twitter's API using the TwitteR package, find trending topics and create a word cloud. You will need a Twitter account to do this.

Accessing Twitter's API

Create a developer account with Twitter, and create a new app. The application page will ask you to name your app, add a description and a website. I just used my Twitter profile as the website.

Create New App

Once you created your application, go to the "API Keys" tab. You will need the "API key" and "API Secret" to access the Twitter API in R.

API Tab

Using the TwitteR package to access Twitter

Packages needed: twitteR, ROAuth, RCurl.

##Create a Twitter handshake to access data##
#Load libraries
 library(twitteR)
 library(ROAuth)
 library(RCurl)
#Download SSL certification
 download.file(url="http://curl.haxx.se/ca/cacert.pem", destfile="cacert.pem")
# Set SSL certs globally
 options(RCurlOptions = list(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl")))
#Set constant request URL
 requestURL<-"https://api.twitter.com/oauth/request_token"
 #Set constant accessURL
 accessURL<-"https://api.twitter.com/oauth/access_token"
 #set constant authURL
 authURL<-"https://api.twitter.com/oauth/authorize"
consumerKey<-"YourTwitterAPIKeyhere"
 consumerSecret<-YourTwitterAPISecrethere"
twitCred <- OAuthFactory$new(consumerKey=consumerKey,
 consumerSecret=consumerSecret,
 requestURL=requestURL,
 accessURL=accessURL,
 authURL=authURL)
#asking for access
 twitCred
twitCred$handshake(cainfo = system.file("CurlSSL", "cacert.pem",package = "RCurl"))

After you create the twitCred$handshake, a web URL will appear in the R console. You will need to copy and paste the URL into a browser, and "authorize" the app.

Twit Handshake

You will receive an authorization code to enter into the R console.

Authorize App

To check and see if the handshake worked :

registerTwitterOAuth(twitCred)

To save the handshake:

save(list="twitCred", file="twitteR_credentials")

See what's trending on Twitter

trend<-getTrends(cainfo="cacert.pem", woeid=2459115)
head(trend,20)
dim(trend)

Find location IDs (woeid) here. Woeid 2459115 is for New York City. Woeid 1 is for the world.

Creating a word cloud using trending topics

Packages needed: wordcloud, tm, RColorBrewer.

library(wordcloud)
library(tm)

Today, the New York Police Department encouraged Twitter users to use the hashtag #myNYPD to relate their stories and opinions of the the NYPD. It backfired horribly. Do the actual tweets, apart from the photos, also cast the NYPD in a bad light?

mynypd<-searchTwitter("#mynypd", n=200, cainfo="cacert.pem")
mynypd_text<-sapply(mynypd, function(x) x$getText())
mynypd_corpus<-Corpus(VectorSource(mynypd_text))
mynypd_corpus<-tm_map(mynypd_corpus, tolower, mc.cores=1)
mynypd_corpus<-tm_map(mynypd_corpus, removePunctuation, mc.cores=1)
mynypd_corpus<-tm_map(mynypd_corpus, function(x) removeWords(x,stopwords()))
wordcloud(mynypd_corpus)

The above code creates this word cloud, in black:
MYNYPD2

We can tweak it a little and add some color to show word frequency by using the RColorBrewer Package.

library(RColorBrewer)
display.brewer.all()
mynypd_pal<-brewer.pal(9,"Set1")
wordcloud(mynypd_corpus,colors=mynypd_pal)

This creates a word cloud that looks a little bit more interesting:

MYNYPD3

We can see some words stand out: brutality, abuse, systematic, overlords. It's unfortunately jumbled in with some "nonsense" words, like http. The tm package in R is really great for parsing language that does not have complications like emojis, @ reply, accents, or web addresses. It can strip out out unwanted words and non-ASCII characters; however, for this blog post, I am trying to keep things simple.

One can also throw out words under or over a certain frequency.

wordcloud(mynypd_corpus,min.freq=10,max.words=100, random.order=T, colors=mynypd_pal)

We get a much simpler and perhaps more informative word cloud:

mynypd4

About Author

Related Articles

Leave a Comment

Avatar
R Workshop XIII: Facebook, Twitter, LinkedIn data analytics (hands-on) | NYC Data Science Academy April 25, 2014
[…] Huang: call Facebook API, FB likes for Personalization/Merch/Marketing –Kim Johnson: call Twitter API, wordCloud, interaction among friends –David Russo: call Linkedin API, company info and update, connections, find the best job for […]

View Posts by Categories


Our Recent Popular Posts


View Posts by Tags

#python #trainwithnycdsa 2019 airbnb Alex Baransky alumni Alumni Interview Alumni Reviews Alumni Spotlight alumni story Alumnus API Application artist aws beautiful soup Best Bootcamp Best Data Science 2019 Best Data Science Bootcamp Best Data Science Bootcamp 2020 Best Ranked Big Data Book Launch Book-Signing bootcamp Bootcamp Alumni Bootcamp Prep Bundles California Cancer Research capstone Career Career Day citibike clustering Coding Course Demo Course Report D3.js data Data Analyst data science Data Science Academy Data Science Bootcamp Data science jobs Data Science Reviews Data Scientist Data Scientist Jobs data visualization Deep Learning Demo Day Discount dplyr employer networking feature engineering Finance Financial Data Science Flask gbm Get Hired ggplot2 googleVis Hadoop higgs boson Hiring hiring partner events Hiring Partners Industry Experts Instructor Blog Instructor Interview Job Job Placement Jobs Jon Krohn JP Morgan Chase Kaggle Kickstarter lasso regression Lead Data Scienctist Lead Data Scientist leaflet linear regression Logistic Regression machine learning Maps matplotlib Medical Research Meet the team meetup Networking neural network Neural networks New Courses nlp NYC NYC Data Science nyc data science academy NYC Open Data NYCDSA NYCDSA Alumni Online Online Bootcamp Open Data painter pandas Part-time Portfolio Development prediction Prework Programming PwC python python machine learning python scrapy python web scraping python webscraping Python Workshop R R language R Programming R Shiny r studio R Visualization R Workshop R-bloggers random forest Ranking recommendation recommendation system regression Remote remote data science bootcamp Scrapy scrapy visualization seaborn Selenium sentiment analysis Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Switchup Tableau team TensorFlow Testimonial tf-idf Top Data Science Bootcamp twitter visualization web scraping Weekend Course What to expect word cloud word2vec XGBoost yelp