Analytics For Business

Wednesday 7 October 2015

Connecting to twitter using R

Social media is the biggest source of the data these days. For any research like understanding the customer expectations for a particular product, and customer behavior, it can provide the useful information. 

In this post, we will focus on connecting the twitter account through R and fetching the tweets with some simple steps.

Prerequisite:
         1-      Twitter Account
         2-      R installed in your PC

Step 1 – Create a twitter app to facilitate handshake with R for authentication


Now click on “Create New App” button. You will get the following window. Fill the details.


If you don’t have a website, put http://test.com/ or anything else. Accept the developer agreement.
And click on “Create your twitter application”. You will get the following window.
Here you can see the application details. Name of my app



Now go to “Keys and Access Tokens” tab. You can see the consumer keys and consumer secret.



And go to token access in the same page. Click on “Create my access token”. Then it will generate Access Token and Access Token Secret.



Copy the consumer key, consumer secret, access token, and access token secret. It will be used later.

Step 2 – Now it’s time to write some R code to perform handshake.
install.packages(“twitter”, dependencies=T)
install.packages(“RCurl”, dependencies=T)
Note – Please take care of capital letters.
Now load these packages in R.
library(twitteR)
library(RCurl)

Step 3- Use the copied consumer key, consumer secret, access token, and access token secret in following R code.
consumer_key <- '<put your consumer key here>'
consumer_secret <- '<put your consumer secret here>'
access_token <- "<put your access token here>"
access_secret <- "<put your access token secret here>"

Step 4- You need to execute this step, if you are working behind a proxy server. Otherwise skip.
library(httr)
set_config(use_proxy(url='proxy- address',port-number, username, password))

Step 5- Now setup the handshake using following command.
setup_twitter_oauth(consumer_key,consumer_secret, access_token , access_secret)
Here we are authorizing the twitter API to fetch the data into R. It will ask to choose wither 1 or 2.You can select 1 for Yes and 2 for No.

Step 6- Now you can search for tweets in twitter using following line of code.
searchTwitter("Modi")
By default it will give you 25 tweets. But you can choose more tweets and also choose tweets within a particular date range.
Check the information about the searchTwitter function in R documentation using the following command:
? searchTwitter
searchTwitter(searchString, n=25, lang=NULL, since=NULL, until=NULL,
              locale=NULL, geocode=NULL, sinceID=NULL, maxID=NULL,
              resultType=NULL, retryOnRateLimit=120, ...)



No comments:

Post a Comment