Analyzing Twitter Trends with TwitteR
[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.
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.
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.
You will receive an authorization code to enter into the R console.
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:
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:
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: