Subscribe to DSC Newsletter

How to create a Twitter Sentiment Analysis using R and Shiny

Hi!

I will show you how to create a simple application in R & Shiny to perform Twitter Sentiment Analysis in real-time. I use RStudio. First, I create a Shiny Project. Then, in the ui.R file, I put this code:


shinyUI(fluidPage(

titlePanel("Sentiment Analysis"),

textOutput("currentTime"),
h4("Tweets:"),

sidebarLayout(

sidebarPanel(

dataTableOutput('tweets_table')

),


# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot"),
sidebarPanel(
plotOutput("positive_wordcloud")
),
sidebarPanel(
plotOutput("negative_wordcloud")
),
sidebarPanel(
plotOutput("neutral_wordcloud")
)
)

)
))

Here, I will show a title, the current time, a table with Twitter user name, a bar graph and wordclouds. Now, I will create the server side:

library(shiny)
library(tm)
library(wordcloud)
library(twitteR)

shinyServer(function(input, output, session) {

setup_twitter_oauth(consumer_key = "xxxxxxxxxxxx", consumer_secret = "xxxxxxxxxxxx")

token <- get("oauth_token", twitteR:::oauth_cache)
token$cache()

output$currentTime <- renderText({invalidateLater(1000, session)
paste("Current time is: ",Sys.time())})

observe({

invalidateLater(60000,session)

count_positive = 0
count_negative = 0
count_neutral = 0

positive_text <- vector()
negative_text <- vector()
neutral_text <- vector()

vector_users <- vector()
vector_sentiments <- vector()

tweets_result = ""

tweets_result = searchTwitter("word-or-expression-to-evaluate")
for (tweet in tweets_result){
print(paste(tweet$screenName, ":", tweet$text))

vector_users <- c(vector_users, as.character(tweet$screenName));

if (grepl("I love it", tweet$text, ignore.case = TRUE) == TRUE | grepl("Wonderful", tweet$text, ignore.case = TRUE) | grepl("Awesome", tweet$text, ignore.case = TRUE)){
count_positive = count_positive + 1

vector_sentiments <- c(vector_sentiments, "Positive")
positive_text <- c(positive_text, as.character(tweet$text))

} else if (grepl("Boring", tweet$text, ignore.case = TRUE) | grepl("I'm sleeping", tweet$text, ignore.case = TRUE)) {
count_negative = count_negative + 1

vector_sentiments <- c(vector_sentiments, "Negative")
negative_text <- c(negative_text, as.character(tweet$text))

} else {
count_neutral = count_neutral + 1
print("neutral")
vector_sentiments <- c(vector_sentiments, "Neutral")
neutral_text <- c(neutral_text, as.character(neutral_text))
}
}

df_users_sentiment <- data.frame(vector_users, vector_sentiments)

output$tweets_table = renderDataTable({
df_users_sentiment
})

output$distPlot <- renderPlot({

results = data.frame(tweets = c("Positive", "Negative", "Neutral"), numbers = c(count_positive,count_negative,count_neutral))

barplot(results$numbers, names = results$tweets, xlab = "Sentiment", ylab = "Counts", col = c("Green","Red","Blue"))

if (length(positive_text) > 0){

output$positive_wordcloud <- renderPlot({ wordcloud(paste(positive_text, collapse=" "), min.freq = 0, random.color=TRUE, max.words=100 ,colors=brewer.pal(8, "Dark2")) })
}

if (length(negative_text) > 0) {

output$negative_wordcloud <- renderPlot({ wordcloud(paste(negative_text, collapse=" "), random.color=TRUE, min.freq = 0, max.words=100 ,colors=brewer.pal(8,"Set3")) })
}


if (length(neutral_text) > 0){

output$neutral_wordcloud <- renderPlot({ wordcloud(paste(neutral_text, collapse=" "), min.freq = 0, random.color=TRUE , max.words=100 ,colors=brewer.pal(8, "Dark2")) })
}

})

})

})

It's a really simply code, not complex at all. The purpose of it is just for testing and so you guys can practice R language. If you have questions just let me know.

Thanks!

Diego.

Follow me on Twitter: https://twitter.com/jdiewitter

Views: 7651

Comment

You need to be a member of Data Science Central to add comments!

Join Data Science Central

Comment by Vikrant Choudhary on December 10, 2018 at 12:58am

It would be great if you can put this in git or other repository.

However thanks a lot for this idea,

Comment by Mary Anne Schultz on March 26, 2018 at 7:30am

Thanks, going to try this in my class at Claremont Graduate University--Social Media Data Analytics.

Comment by Matthias Raess on November 12, 2016 at 2:21pm

Hi,

Thanks for posting the scripts. One problem though: When I execute the app, I get the following error (I have put in a search term and my Twitter API information)...

Error in init_oauth1.0(self$endpoint, self$app, permission = self$params$permission, :
Unauthorized (HTTP 401).

Please help!

Comment by Sree Krishna on September 12, 2016 at 10:01pm

I encounter this problem every time I try the Twitter token in cache. 

"> token$cache()

Error in readRDS(cache_path) : error reading from connection"

I am sure this is an httr issue, but I am not able to find any solution to this problem. I tried to find yo on Twitter, but that twitter link doesn't seem to work! Please help! Thank you!

© 2019   Data Science Central ®   Powered by

Badges  |  Report an Issue  |  Privacy Policy  |  Terms of Service