Twitter - Sentiment Analysis using R


# Sentiment Analysis using R



The approach followed here is to count the positive and negative words in each tweet and assign a sentiment score. 

This way, we can ascertain how positive or negative a tweet is. 

Also, there are multiple ways to calculate such scores; here is one formula to perform such calculations.

# Score = Number of positive words - Number of negative words
# If Score > 0, means that the tweet has 'positive sentiment'
# If Score < 0, means that the tweet has 'negative sentiment'
# If Score = 0, means that the tweet has 'neutral sentiment'

The below example collects the data from twitter on "RelianceJio" (@reliancejio).

---------------------------------------------------------------------------------------------------------

install.packages("twitteR",repos='http://cran.us.r-project.org')
install.packages("ROAuth",repos='http://cran.us.r-project.org')
install.packages("plyr",repos='http://cran.us.r-project.org')
install.packages("stringr",repos='http://cran.us.r-project.org')

library(twitteR) ### for fetching the tweets
library(plyr) ## for breaking the data into manageable pieces
library(ROAuth) # for R authentication
library(stringr) # for string processing

reqURL <- "https://api.twitter.com/oauth/request_token"
accessURL <- "http://api.twitter.com/oauth/access_token"
authURL <- "http://api.twitter.com/oauth/authorize"

api_key <- "<your api key>"
api_secret <- "<your api secret>"
access_token <- "<your access token>"
access_token_secret <- "<your access token secret>"
setup_twitter_oauth(api_key,api_secret,access_token,access_token_secret)

# get the api keys and access token , token secret from 
# https://apps.twitter.com/
# note: Login with twitter account and create an app to generate the api key, api secret, access token, access token secret.

posText <- read.delim("positive-words.txt", header=FALSE, stringsAsFactors=FALSE)
negText <- read.delim("negative-words.txt", header=FALSE, stringsAsFactors=FALSE)

# the positive-words.txt and negative-words.txt can be downloaded from this link

https://drive.google.com/open?id=1GLLJa_JU5z8u8IBaW7MBqbNeEoF3FVrV

https://drive.google.com/open?id=185pxU8Ew5577B7U_6zkUeKf2XI5Lt5pl

posText <- posText$V1
posText <- unlist(lapply(posText, function(x) { str_split(x, "\n") }))
negText <- negText$V1
negText <- unlist(lapply(negText, function(x) { str_split(x, "\n") }))
pos.words = c(posText, 'upgrade')

neg.words = c(negText, 'wtf', 'wait', 'waiting','epicfail', 'mechanical')

relianceJio_tweets= searchTwitter('@reliancejio', n=3)

relianceJio_tweets_txt = sapply(relianceJio_tweets, function(t) t$getText() )
#  getText() there for grabbing just the text content of each tweet.

noof_jio_tweets = c(length(relianceJio_tweets_txt))

relianceJio_tweets_txt

getScoreForTweets <- function(tweets_txt){
score <- sapply(tweets_txt, 
                       function(eachTweet){
                         eachTweet1 = gsub("[[:punct:]]", "", eachTweet)
                         eachTweet2 = gsub("[[:cntrl:]]", "", eachTweet1)
                         eachTweet3 = gsub("\\d+", "", eachTweet2)
                         eachTweet4 = sapply(eachTweet3,function(x){tolower(x)})
                         word.list = str_split(eachTweet4, "\\s+")
                         words = unlist(word.list)
                         pos.matches = match(words, pos.words)
                         neg.matches = match(words, neg.words)
                         pos.matches_log = !is.na(pos.matches)
                         neg.matches_log = !is.na(neg.matches)
                       
                         return(sum(pos.matches_log)-sum(neg.matches_log))
                       })
return(score)
}

score <- getScoreForTweets(relianceJio_tweets_txt)

senti <- data.frame(tweets=relianceJio_tweets_txt,score=score)

senti$polarity <- ifelse(senti$score >0,"positive",ifelse(senti$score < 0,"negative",ifelse(senti$score==0,"Neutral",0)))
names(senti)
senti$polarity
senti$score