opencodez

Sentiment Analysis of Tweets – Connecting to Twitter API +Fetching Tweets using R

Sentiment Analysis of Tweets:

Twitter is a popular source to extract text data related to any product, company, individual or event. Let us consider an example of the Cricket World Cup which just ended. Twitter has been a hot platform for discussion. Thousands of comments were posted from viewers and cricket fans across the world over the past few weeks. Several hashtags were used for the same viz. #CWC, #CWC19, #CWC2019.

It would be interesting to do a Sentiment Analysis of Tweets related to a hashtag by pulling and working on a collection of tweets.

In this article, we will learn how to Connect to a Twitter API and fetch tweets using R.

A snapshot below shows some of the tweets for #CWC19

Things you will learn from this topic:

You will have to create an account on twitter (if you are a new twitter user) and then create an individual or a team developer account to create an app. So, let us begin.

Follow the below steps:

Let us now see how to establish a connection between our app and R with the information of API Key and API Secret Key. The code for that is as follows:

install.packages("rtweet")

library(rtweet)

## whatever name you assigned to your created app

appname x- "Enter your app name"

## api key

key x- " Enter API Key value here"

## api secret

secret x- "Enter API Secret here"

## create token named "twitter_token"

twitter_token x- create_token(

app = appname,

consumer_key = key,

consumer_secret = secret)

Now let’s extract tweets from Twitter. If you would have noticed, we installed a package named rtweet while setting up the connection. That is the package we will use for this task. There is another package named twitteR which can be used as well. We will stick to the prior one. (We are assuming here that the reader has got some prior understanding of R.)

search_tweets is a function in rtweet package allowing us to search and extract tweets on a search string. You can learn all the features and options about this package here https://cran.r-project.org/web/packages/rtweet/rtweet.pdf

Code to extract tweets for hast tag #wimbledon2019

wimbledon_tweets = search_tweets("#wimbledon2019", n=2000, lang='en')

There are several ways to measure the sentiment of these tweets.

We will take on these topics in the next article. Hoping till then you will surely experiment with twitter API and find out the various ways in which you would want to put the use of these interesting tweets.