-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.R
More file actions
241 lines (197 loc) · 7.42 KB
/
server.R
File metadata and controls
241 lines (197 loc) · 7.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
library(shiny)
EnsurePackage<-function(x)
{x <- as.character(x)
if (!require(x,character.only=TRUE))
{
install.packages(pkgs=x,repos="https://mran.microsoft.com/")
require(x,character.only=TRUE)
}
}
PrepareTwitter<-function()
{
EnsurePackage("twitteR")
EnsurePackage("stringr")
EnsurePackage("ROAuth")
EnsurePackage("RCurl")
EnsurePackage("ggplot2")
EnsurePackage("reshape")
EnsurePackage("tm")
EnsurePackage("RJSONIO")
EnsurePackage("wordcloud")
EnsurePackage("gridExtra")
EnsurePackage("plyr")
EnsurePackage("e1071")
}
PrepareTwitter()
shinyServer(function(input, output, session) {
consumer_api_key <- "Wn9YFJ8jSiwFgIgOJOi2ihygN"
consumer_api_secret <- "3TS3AJieAaDcmRFgTR9s8CCW8TNEwT0Jy7HmSxn7LXn3T6ACo1"
access_token <- "888087350408040448-QLogwryUIePGG8tVTsSOsPMQ2lCYNsO"
access_token_secret <- "IYn638n1mS6KbMVCwaXNzeBABT8PGZXDTJbuywpjTRVby"
setup_twitter_oauth(consumer_api_key, consumer_api_secret, access_token, access_token_secret)
TweetFrame<-function(twtList)
{
df<- do.call("rbind",lapply(twtList,as.data.frame))
df$text <- sapply(df$text,function(row) iconv(row, "latin1", "ASCII", sub=""))
df$text = gsub("(f|ht)tp(s?)://(.*)[.][a-z]+", "", df$text)
return (df$text)
}
pos.words = scan('positive_words.txt', what='character', comment.char=';')
neg.words = scan('negative_words.txt', what='character', comment.char=';')
wordDatabase<-function()
{
pos.words<<-c(pos.words)
neg.words<<-c(neg.words)
}
score.sentiment <- function(sentences, pos.words, neg.words, .progress='none')
{
require(plyr)
require(stringr)
list=lapply(sentences, function(sentence, pos.words, neg.words)
{
sentence = gsub('[[:punct:]]',' ',sentence)
sentence = gsub('[[:cntrl:]]','',sentence)
sentence = gsub('\\d+','',sentence)
sentence = gsub('\n','',sentence)
sentence = tolower(sentence)
word.list = str_split(sentence, '\\s+')
words = unlist(word.list)
pos.matches = match(words, pos.words)
neg.matches = match(words, neg.words)
pos.matches = !is.na(pos.matches)
neg.matches = !is.na(neg.matches)
pp=sum(pos.matches)
nn = sum(neg.matches)
score = sum(pos.matches) - sum(neg.matches)
list1=c(score, pp, nn)
return (list1)
}, pos.words, neg.words)
score_new=lapply(list, `[[`, 1)
pp1=score=lapply(list, `[[`, 2)
nn1=score=lapply(list, `[[`, 3)
scores.df = data.frame(score=score_new, text=sentences)
positive.df = data.frame(Positive=pp1, text=sentences)
negative.df = data.frame(Negative=nn1, text=sentences)
list_df=list(scores.df, positive.df, negative.df)
return(list_df)
}
#TABLE DATA
library(reshape)
sentimentAnalyser<-function(result)
{
#Creating a copy of result data frame
test1=result[[1]]
test2=result[[2]]
test3=result[[3]]
#Creating three different data frames for Score, Positive and Negative
#Removing text column from data frame
test1$text=NULL
test2$text=NULL
test3$text=NULL
#Storing the first row(Containing the sentiment scores) in variable q
q1=test1[1,]
q2=test2[1,]
q3=test3[1,]
qq1=melt(q1, var='Score')
qq2=melt(q2, var='Positive')
qq3=melt(q3, var='Negative')
qq1['Score'] = NULL
qq2['Positive'] = NULL
qq3['Negative'] = NULL
#Creating data frame
table1 = data.frame(Text=result[[1]]$text, Score=qq1)
table2 = data.frame(Text=result[[2]]$text, Score=qq2)
table3 = data.frame(Text=result[[3]]$text, Score=qq3)
#Merging three data frames into one
table_final=data.frame(Text=table1$Text, Positive=table2$value, Negative=table3$value, Score=table1$value)
return(table_final)
}
percentage<-function(table_final)
{
#Renaming
posSc=table_final$Positive
negSc=table_final$Negative
#Adding column
table_final$PosPercent = posSc/ (posSc+negSc)
#Replacing Nan with zero
pp = table_final$PosPercent
pp[is.nan(pp)] <- 0
table_final$PosPercent = pp*100
#Negative Percentage
#Adding column
table_final$NegPercent = negSc/ (posSc+negSc)
#Replacing Nan with zero
nn = table_final$NegPercent
nn[is.nan(nn)] <- 0
table_final$NegPercent = nn*100
return(table_final)
}
wordDatabase()
twtList<-reactive({twtList<-searchTwitter(input$searchTerm, n=input$maxTweets, lang="en") })
tweets<-reactive({tweets<-TweetFrame(twtList() )})
result<-reactive({result<-score.sentiment(tweets(), pos.words, neg.words, .progress='none')})
table_final<-reactive({table_final<-sentimentAnalyser( result() )})
table_final_percentage<-reactive({table_final_percentage<-percentage( table_final() )})
output$tabledata<-renderTable(table_final_percentage())
#WORDCLOUD
wordclouds<-function(text)
{
library(tm)
library(wordcloud)
corpus <- VCorpus(VectorSource(text))
clean_text <- tm_map(corpus, removePunctuation)
clean_text <- tm_map(clean_text, content_transformer(tolower))
clean_text <- tm_map(clean_text, removeWords, stopwords("english"))
clean_text <- tm_map(clean_text, removeNumbers)
clean_text <- tm_map(clean_text, stripWhitespace)
return (clean_text)
}
text_word<-reactive({text_word<-wordclouds( tweets() )})
output$word <- renderPlot({ wordcloud(text_word(),colors=brewer.pal(8, "Dark2"),random.color = TRUE,max.words = 500, main="WordCloud") })
output$histPos<- renderPlot({ hist(table_final()$Positive, col=rainbow(10), main="Histogram of Positive Sentiment", xlab = "Positive Score") })
output$histNeg<- renderPlot({ hist(table_final()$Negative, col=rainbow(10), main="Histogram of Negative Sentiment", xlab = "Negative Score") })
output$histScore<- renderPlot({ hist(table_final()$Score, col=rainbow(10), main="Histogram of Score Sentiment", xlab = "Overall Score") })
nrc <- function(sentences)
{
sentence = gsub('[[:punct:]]',' ',tweets())
sentence = gsub('[[:cntrl:]]','',sentence)
sentence = gsub('\\d+','',sentence)
sentence = gsub('\n','',sentence)
sentence = tolower(sentence)
word.list = str_split(sentence, '\\s+')
words = unlist(word.list)
sen <-get_nrc_sentiment(words)
emo_bar = colSums(sen)
emo_sum = data.frame(count=emo_bar, emotion=names(emo_bar))
return (emo_sum)
}
nrcsen<-reactive({nrcsen<-nrc(tweets())})
output$histNRC<- renderPlot({ hist(nrcsen)})
#TOP TRENDING TOPICS
toptrends <- function(place)
{
a_trends = availableTrendLocations()
woeid = a_trends[which(a_trends$name==place),3]
trend = getTrends(woeid)
trends = trend[1:2]
dat <- cbind(trends$name)
dat2 <- unlist(strsplit(dat, split=", "))
dat3 <- grep("dat2", iconv(dat2, "latin1", "ASCII", sub="dat2"))
dat4 <- dat2[-dat3]
return (dat4)
}
trend_table<-reactive({ trend_table<-toptrends(input$trendingTable) })
output$trendtable <- renderTable(trend_table())
toptweeters<-function(tweetlist)
{
tweets <- twListToDF(tweetlist)
tweets <- unique(tweets)
d <- as.data.frame(table(tweets$screenName))
d <- d[order(d$Freq, decreasing=T), ]
names(d) <- c("User","Tweets")
return (d)
}
d<-reactive({d<-toptweeters( twtList() ) })
output$tweetersplot<-renderPlot ( barplot(head(d()$Tweets, 20), names=head(d()$User, 20), horiz=F, las=2, main="Top 20 users associated with the Hashtag", col=1) )
output$tweeterstable<-renderTable(head(d(),20))
})