-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathapp.R
More file actions
1317 lines (1038 loc) · 54 KB
/
app.R
File metadata and controls
1317 lines (1038 loc) · 54 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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
library(scales)
library(tm)
library(wordcloud)
library(SnowballC)
library(rvest)
library(dplyr)
library(reshape2)
# library(tidytext)
library(syuzhet)
library(pander)
library(xlsx)
library(ggplot2)
library(RWeka)
library(RWekajars)
library(partykit)
library(DT)
library(shinydashboard)
library(qdap)
library(rJava)
romeo <- readLines("romeo.txt")
othello <- readLines("othello.txt")
midsummers <- readLines("midsummers.txt")
###Dashboard Beginning for Text Analysis App ######
ui <- dashboardPage(skin = "blue",
dashboardHeader(title = "Text Analysis"),
###Dashboard Sidebar Menu####
dashboardSidebar(
sidebarMenu(
##Tab One
menuItem("File Upload",tabName = "file",icon = icon("file-text-o")),
##Tabe One-Half
menuItem("Web Scrape Text",tabName = "scrape_text",icon = icon("fab fa-internet-explorer")),
##Tab Two
menuItem("Text Output",tabName = "text",icon = icon("file-text-o")),
##Tab WordBreakdown
menuItem("Word Breakdown",tabName = "breakdown",icon = icon("table")),
##Tab Three
menuItem("Wordcloud",tabName = "wordcloud",icon = icon("cloud")),
##Tab Four
menuItem("Word Count Bar Plot",tabName = "barplot",icon = icon("bar-chart-o")),
##Tab Five
menuItem("Emotional Sentiment",tabName = "emotionalsentiment",icon = icon("bar-chart-o")),
##Tab Six
menuItem(paste("Positive vs. Negative Sentiment"),tabName = "pnsentiment",icon = icon("bar-chart-o")),
##Tab Percentage
menuItem("Emotion Percentages Table",tabName = "emotionalpercentages",icon = icon("percent")),
##Tab Nine
#menuItem("Barplot % by Word",tabName = "plotg",icon = icon("bar-chart-o")),
##Tab Seven
menuItem("Plot Trajectory",tabName = "plottrajectory",icon = icon("line-chart")),
##Lexical Dispersion Plot
menuItem("Lexical Dispersion Plot",tabName = "lexical_plot",icon = icon("line-chart")),
##Tab Eight
menuItem("Word Tokenizer",tabName = "wordtokenizer",icon = icon("table")),
##Tab Ten
#menuItem("Sentence Sentiment",tabName = "sentencefinder",icon = icon("table")),
##Works Cited
menuItem("References:",tabName = "workscited"),
##Text Analysis Report
menuItem("Text Analysis Report",tabName = 'analysisreport'),
##Contact:
menuItem("Contact:",tabName = "contact"),
##Digital Ocean Credit
menuItem("Digital Ocean Credit",tabName="digitalocean")
)),
###Beginning of Dashboard Body####
dashboardBody(
tabItems(
###File Upload Tab
tabItem(tabName = "file",
fileInput("selection", "Upload Text File:",multiple = TRUE),
helpText(paste("Please upload a plain .txt file with the text",
"you would like to analyze."),
br(),
br(),
selectInput("datasetten", "Choose Sample Text:",
choices = c("Romeo and Juliet", "Othello", "Midsummer Nights Dream"),selected = "Romeo and Juliet"),
br(),
downloadButton("downloadromeo","Downaload Sample Text"),
#paste("Sample Text:"),a("Romeo and Juliet",href="https://www.rgonzo.us/shiny/textfiles/text/romeo.txt"),
br(),
br(),
paste("Windows Users: Please use a .txt plain text file extension via NOTEPAD *."),
br(),
br(),
paste("Linux Users: Please use a .txt plain text file extension."),
br(),
br(),
paste("Mac Users: Please use a .txt plain text file extension via TEXTEDIT *."),
br(),
br(),
a("Plain text tutorial: Windows and Mac",href="http://support.smqueue.com/support/solutions/articles/159273-saving-a-text-file-on-a-mac-or-pc-in-utf-8",target = "_blank"),
br(),
br(),
tags$b(paste("* Please ensure the file uploaded utilizes UTF-8 encoding")))),
###Text Output Tab####
tabItem(tabName = "text",
helpText(paste("This tab displays the uploaded text file.")),
actionButton("display","Display Text"),
br(),
br(),
box(title = "Text Ouput",textOutput("text",inline = FALSE),width = 450)),
###Word Frequency Barplot Tab####
tabItem(tabName = "barplot",
helpText(paste("This tab allows you to display the frequency of words in the uploaded text "),
br(),
paste("via a bar chart. The bar chart by default displays the first through tenth"),
br(),
paste("most frequent words in the text.")),
actionButton(inputId = "barplot",label = "Create Barplot"),
downloadButton(outputId = "downloadsix",label = "Download Barplot"),
selectInput(inputId = "download6",label = "Choose Format",choices = list("png","pdf","bmp","jpeg")),
numericInput(inputId = "numeric",label = " From:",min = 1,max = 50000,step = 1,value = 1),
numericInput(inputId = "numeric2",label = "To:",min = 1,max = 50000,step = 1,value = 10),
checkboxInput(inputId = "horz",label = "Horizontal Bars",value = FALSE),
selectInput(inputId = 'color',label = 'Color', choices = list("Blue","Red","Yellow","Green","Black","Orange","Pink","Brown","LightGreen","LightBlue","LightGrey"),
selected = "Blue"),
plotOutput("plot2")),
###WordCloud Tab####
tabItem(tabName = "wordcloud",
fluidRow(
box(actionButton(inputId = "update", label = "Create Wordcloud"),
helpText(paste("The minimum frequency refers to the minimum number of times"),
br(),
paste("the word needs to appear in the uploaded text to be included in the wordcloud.")),
sliderInput("freq","Minimum Frequency:",min = 1, max = 500, value = 10),
helpText(paste("The maximum number of words refers to the maximum number of words"),
br(),
paste("you want to appear in the wordcloud that is created.")),
sliderInput("max","Maximum Number of Words:",min = 1, max = 1000, value = 25),
selectInput(inputId = "pal",label = "Cloud Color",choices = c("Dark"="Dark2","Pastel One"="Pastel1","Pastel Two"="Pastel2","Set One"="Set1",
"Set Two"="Set2","Set Three"="Set3"),selected = "Dark2"),
downloadButton("download1","Download Wordcloud"),
selectInput(inputId = "download3",label = "Choose Wordcloud Format",choices = list("png","pdf","bmp","jpeg"))),
box(plotOutput("plot")))),
###Emotional Sentiment Bar Chart Tab####
tabItem(tabName = "emotionalsentiment",
helpText(paste("This tab allows you to calculate eight types of emotion present within the uploaded text."),
br(),
br(),
paste("The following types of emotion are calculated:"),
br(),
br(),
tags$b(paste("Anger, Anticipation, Disgust, Fear, Joy, Sadness, Surprise, and Trust.")),
br(),
paste("The emotions calculated are the 8 basic universal emotions conveyed by humans in all cultures."),
br(),
paste("Each bar represents the overall percentage of each emotion present within the uploaded text file.")),
actionButton("sentiment","Calculate Emotion"),
br(),
br(),
downloadButton("downloadseven","Download Emotional Sentiment Barplot"),
selectInput(inputId = 'colornow',label = 'Color', choices = list("Blue","Red","Yellow","Green","Black","Orange","Pink","Brown","LightGreen","LightBlue","LightGrey"),
selected = "Blue"),
plotOutput("nrcplot")),
###Positive & Negative sentiment Tab####
tabItem(tabName = "pnsentiment",
helpText(paste("This tab allows you to calculate the positive and negative sentiment present within the uploaded text."),
br(),
br(),
paste("The following sentiments are calculated:"),
br(),
br(),
tags$b(paste("Positive & Negative")),
br(),
paste("The bar graphs displayed are in relation to the percentage of positive and negative words present in the uploaded text.")),
actionButton("negative","Calculate Positive & Negative Sentiment"),
br(),
br(),
downloadButton(outputId = "downloadeight",label = "Download Pos vs. Neg Barplot"),
selectInput(inputId = 'colornow2',label = 'Color', choices = list("Blue","Red","Yellow","Green","Black","Orange","Pink","Brown","LightGreen","LightBlue","LightGrey"),
selected = "Blue"),
br(),
plotOutput("nrcplot2")),
###Emotional Percentages Table Tab####
tabItem(tabName = "emotionalpercentages",
box(helpText(paste("The data table created calculates the percentage of each emotion",
"present within the uploaded text file and outputs it to a table."),
br(),
br(),
paste("The following emotions are calculated:"),
br(),
tags$b(paste("Anger, Anticipation, Disgust, Fear, Joy, Sadness, Surprise, and Trust.")),
br(),
br(),
paste("The emotions calculated are the 8 basic universal emotions conveyed by humans in all cultures."),
# paste("The following sentiments are also calculated:"),
# br(),
# tags$b(paste("Positive & Negative")),
br(),
br(),
a("Reference: NRC Package",href="https://cran.r-project.org/web/packages/syuzhet/vignettes/syuzhet-vignette.html",target = "_blank")),
br(),
br(),
actionButton("scsentiment","Calculate Emotional %"),
br(),
br(),
downloadButton("downloadfour","Download Emotional %")),
box(DT::dataTableOutput("scosentiment"))),
###Text Plot Trajectory Tab#####
tabItem(tabName = "plottrajectory",
helpText(paste("This tab allows you to plot the trajectory of the uploaded text."),
br(),
br(),
paste("The plot will display the overall emotion of pieces of the text at different successive linear locations in the text. Large text files will be more condensed than small text files."),
br(),
paste("The plot displayed can be thought of as the story arc in a movie or book. If text items besides books are used it is highly suggested to order the text correctly. The graph will show"),
br(),
paste("how the emotional content of the uploaded text has changed over time e.g. beginning of a text to the end of the text.The Narrative Timeline axis refers to how the book,text, or comments"),
br(),
paste("have changed from the beginning of the text to the end of the same text being analyzed. The Emotional Valence axis refers to the positive/good-ness and the negative/bad-ness of the text."),
br(),
paste(" Positive valence or upward motion can be seen as the good linear parts of a story, while Negative Valence can be thought of as bad or negative linear parts of the story. Therefore,"),
br(),
paste(" as the plotted line moves up or down it is in turn visualizing the good or bad parts of the text being analyzed.")),
actionButton("trajectory","Create Plot Trajectory"),
br(),
br(),
downloadButton("downloadnine","Download Plot Trajectory"),
plotOutput("nrcplot3")),
###Text Bar Chart Tab #####
tabItem(tabName = "plotg",
helpText(paste("This tab allows you to create a bar chart that displays both the type of emotion and type of sentiment"),
br(),
paste("present within the uploaded text file. The percentage of each emotion and sentiment is displayed at "),
br(),
paste("the top of each bar.")),
actionButton("gplottwo","Create Barplot"),
br(),
br(),
plotOutput("gplot")),
###Word Tokenizer Tab####
tabItem(tabName = "wordtokenizer",
helpText(paste("This tab allows you to utilize a word tokenizer to see which words in a text are displayed together."),
br(),
paste("You can choose to display words from 1 to 5 tokens. Therefore, words that appear next to each other"),
br(),
paste("in the uploaded text will be displayed. If you choose 2, then two words that appear next to each"),
br(),
paste("other will be displayed. You can choose up to 5 words that display next to each other, thus allowing"),
br(),
paste("you ,the end user, to look for patterns in any text.")),
actionButton("bigram","Create Tokenizer Table"),
numericInput(inputId ="numeric3",label="Tokenizer Min.",min=1,max=5,value=2),
numericInput(inputId="numeric4",label="Tokenizer Max",min=1,max=5,value=2),
DT::dataTableOutput("nrcplot4")
),
###Sentence Sentiment Finder Tab#####
tabItem(tabName = "sentencefinder",
helpText(paste("This tab allows you to display sentences by emotion. A sentence may appear more"),
br(),
paste("than once if an one emotion is closely related to another: e.g. anger and disgust.")),
actionButton("emotion","Get Sentence Sentiment"),
br(),
br(),
downloadButton("downloadfive", label="Download Sentence Breakdown"),
br(),
helpText(paste("Select the following number below that corresponds with the emotion you want to display:"),
br(),
br(),
tags$b(paste("1 = Anger 2 = Anticipation 3 = disgust 4 = Fear 5 = Joy")),
br(),
br(),
tags$b(paste("6 = Sadness 7 = Surprise 8 = Trust 9 = Negative 10 = Positive"))),
numericInput(inputId = 'emselect',label = 'Emotion Selector',
value = 1,min = 1,max = 10,step = 1),
br(),
br(),
DT::dataTableOutput("nrcplot5")),
###Word Frequency Tab ######
tabItem(tabName = "breakdown",
helpText(paste("This tab allows you to display the frequency of each word present within the uploaded text file."),
br(),
paste("The frequency of each word will be shown and can be searched via the interactive table displayed below.")),
box(actionButton("wbdown","Create Word Breakdown"),
br(),
br(),
downloadButton("downloadtwo", label="Download Word Breakdown")),
DT::dataTableOutput("wordbreakdown")),
###Text Analysis Report Tab #####
tabItem(tabName = "analysisreport",
downloadButton(outputId = "text_report",label = "Download Text Analysis Report")),
###Works Cite ####
tabItem(tabName = "workscited",
helpText(strong(" References :"),
br(),
br(),
paste("Cashell, D. (2014)."),em("Social media sentiment analysis using data mining techniques"),paste(". National College of Ireland."),
br(),
br(),
paste("Hennessey, A. (2014)."),em("Sentiment analysis of twitter: using knowledge based and machine learning techniques"),paste(". National College of Ireland."),
br(),
br(),
paste("Jockers, M. (2016)."),em("Introduction to the syuzhet package"),paste(".Retrieved from:"),a("https://cran.r-project.org/web/packages/syuzhet/vignettes/syuzhet-vignette.html",href="https://cran.r-project.org/web/packages/syuzhet/vignettes/syuzhet-vignette.html",target="_blank"),
br(),
br(),
paste("Mohammad, S. (2013)."),em("NRC word-emotion association lexicon (aka emolex)"),paste(".Retrieved from:"),a("http://saifmohammad.com/WebPages/NRC-Emotion-Lexicon.htm",href="http://saifmohammad.com/WebPages/NRC-Emotion-Lexicon.htm",target="_blank"),
br(),
br(),
paste("Mullen. (2014)."),em("Introduction to sentiment analysis"),paste(".Retrieved from:"),a("https://lct-master.org/files/MullenSentimentCourseSlides.pdf",href="https://lct-master.org/files/MullenSentimentCourseSlides.pdf",target="_blank"),
br(),
br(),
paste("Robinson, D. (2016)."),em("Text analysis of trump's tweets confirms he writes only the angrier android half"),paste(".Retrieved from:"),a("http://varianceexplained.org/r/trump-tweets/",href= "http://varianceexplained.org/r/trump-tweets/",target="_blank"),
br(),
br(),
paste("Smith, D. (2015)."),em("Comparing subreddits, with latent semantic analysis in r"),paste(". Retrieved from:"),a("http://blog.revolutionanalytics.com/2017/03/comparing-subreddits.html",href="http://blog.revolutionanalytics.com/2017/03/comparing-subreddits.html",target="_blank"))),
tabItem(tabName = "contact",
helpText(paste("Application Author: Ben Gonzalez"),
br(),
br(),
paste("Email: gonzalezben81@gmail.com"),
br(),
br(),
paste("Phone: 314-472-5417"))),
tabItem(tabName = "digitalocean",
helpText(paste("Build your own Linux Server and host your own app with a $10 credit on Digital Ocean"),
br(),
br(),
paste("Click on this link to get your Digital Ocean Credit:"),a("Digital Ocean $10 Credit",href="https://m.do.co/c/b72d3479beb8",target="_blank")
)),
###Web Scrape Tab####
tabItem(tabName = "scrape_text",
textInput(inputId = "text",label = "Enter Website url:",value = "",placeholder = "Enter valid website here"),
br(),
helpText("Enter the HTML node such as 'p' for paragraph to scrape the relevant data from the website. You can then download the text file to save it and upload it for analysis later."),
textInput(inputId = "node",label = "HTML Node",value = "",placeholder = "Enter valid CSS selector here"),
h4("Reference Links:"),
br(),
a(img(src="~/www/CSSTWO.png",width="35",height="35"),href="http://www.w3schools.com/css/default.asp", target="_blank"),
a(img(src="~/www/html.png",width="35",height="35"),href="http://www.w3schools.com/html/default.asp", target="_blank"),
a(img(src="~/www/java2.png",width="35",height="35"),href="http://www.w3schools.com/js/default.asp", target="_blank"),
hr(),
actionButton(inputId = "do",label = "Get Data",icon = icon("gears")),
br(),
br(),
textInput(inputId = "name",label = "Save File As:",value = "",placeholder = "Type File Name Here"),
# downloadButton('download', 'Download',class = "butt")
br(),
downloadButton("download", label="Download"),
hr(),
verbatimTextOutput("printoutput")
),
tabItem(tabName = "lexical_plot",
actionButton("lexical_run","Create Lexical Dispersion Plot"),
hr(),
textInput(inputId = "words",label = "Word to search for in text:"),
hr(),
plotOutput("distPlot")
)
))
###End of Dashboard Body####
)
###Dashboard End for Text Analysis App ######
# Define server logic required to run the Text Analysis App
server <- function(input, output, session) {
options(shiny.maxRequestSize=100*1024^2)
memory.limit(size = 4095)
##Code for uploading Text File from User ##########
ford <- reactive({
req(input$selection) ## ?req # require that the input is available
inFile <- input$selection
df <- readLines(inFile$datapath)
return(df)
})
##Create DocumentTerm Matrix (DTM) ###########
getTermMatrix <- function(f) {
text <- readLines(f$datapath,encoding = "UTF-8")
docs<-Corpus(VectorSource(text))
docs<-tm_map(docs, content_transformer(tolower))
docs<-tm_map(docs, removePunctuation)
docs<-tm_map(docs, removeNumbers)
docs<-tm_map(docs, removeWords,
c(stopwords("SMART"),input$words))
myDTM = TermDocumentMatrix(docs,
control = list(minWordLength = 1,wordLengths=c(0,Inf)))
m = as.matrix(myDTM)
sort(rowSums(m), decreasing = TRUE)
}
terms <- reactive({
getTermMatrix(input$selection)
})
##Create Text Terms Object ###########
text_terms <-reactive({
doc_terms<- ford()
# Make a vector source: text_source
doc_source<-VectorSource(doc_terms)
## text_source is already in your workspace
# Make a volatile corpus: text_corpus
doc_corpus <- VCorpus(doc_source)
## text_source is already in your workspace
clean_corpus <- function(corpus){
corpus <- tm_map(corpus, stripWhitespace)
corpus <- tm_map(corpus, removePunctuation)
corpus <- tm_map(corpus, content_transformer(tolower))
corpus <- tm_map(corpus, removeWords, c(stopwords("english"),input$words))
return(corpus)
}
doc_corp<-clean_corpus(doc_corpus)
doc_dtm<-DocumentTermMatrix(doc_corp)
# Convert text_dtm to a matrix: text_m
doc_m<-as.matrix(doc_dtm)
# Calculate the rowSums: term_frequency
doc_frequencyone<-rowSums(doc_m)
# Sort term_frequency in descending order
doc_frequency<-sort(doc_frequencyone,decreasing=TRUE)
})
###Renders WordCloud Plot####
observeEvent(input$update,{output$plot <- renderPlot({
inFile <- input$selection
if (is.null(inFile))
return("Please Upload File")
withProgress(message = 'Creating WordCloud',
value = 0, {
for (i in 1:3) {
incProgress(1/3)
Sys.sleep(0.75)
}
},env = parent.frame(n=1))
##Wordcloud code
set.seed(1234)
v <- terms()
wordcloud(names(v), v, scale=c(6,0.5),
min.freq = input$freq, max.words=input$max,
rot.per=0.35,
colors=brewer.pal(8, input$pal))
})})
##Renders Barplot plot code ######
observeEvent(input$barplot,{output$plot2<-renderPlot({
withProgress(message = 'Creating BarPlot',
value = 0, {
for (i in 1:3) {
incProgress(1/3)
Sys.sleep(0.25)
}
},env = parent.frame(n=1))
doc_terms<- ford()
# Make a vector source: text_source
doc_source<-VectorSource(doc_terms)
# Make a volatile corpus: text_corpus
doc_corpus <- VCorpus(doc_source)
clean_corpus <- function(corpus){
corpus <- tm_map(corpus, stripWhitespace)
corpus <- tm_map(corpus, removePunctuation)
corpus <- tm_map(corpus, content_transformer(tolower))
corpus <- tm_map(corpus, removeWords, c(stopwords("english"),c(input$words)))
return(corpus)
}
doc_corp<-clean_corpus(doc_corpus)
doc_dtm<-DocumentTermMatrix(doc_corp)
# Convert text_dtm to a matrix: text_m
doc_m<-as.matrix(doc_dtm)
# Calculate the rowSums: term_frequency
doc_frequencyone<-colSums(doc_m)
# Sort term_frequency in descending order
doc_frequency<-sort(doc_frequencyone,decreasing=TRUE)
# termstwo<-text_terms()
# Plot a barchart of the 10 most common words,
barplot(doc_frequency[input$numeric:input$numeric2],col=input$color,horiz = input$horz,las=2)
})})
## Download code for wordcloud picture download ####
output$download1 <- downloadHandler(
filename = function() { paste("WordCloud",input$download3,sep = ".") },
content = function(file) {
if(input$download3=="png")
png(file)
else if (input$download3=="jpeg")
jpeg(file)
else if (input$download3=="bmp")
bmp(file)
else if (input$download3=="pdf")
pdf(file)
set.seed(1234)
v <- terms()
wordcloud(names(v),v, scale=c(6,0.5),
min.freq = input$freq, max.words=input$max,
rot.per=0.35,
colors=brewer.pal(8, input$pal))
dev.off()
})
##Displays Text of Uploaded File ###############
observeEvent(input$display,{output$text<-renderText({
inFile <- input$selection
if (is.null(inFile))
return("Please Upload File")
ford()})})
## Creates word breakdown matrix for csv file #####
texterdf2<- reactive({
withProgress(message = 'Downloading CSV File',
value = 0, {
for (i in 1:10) {
incProgress(1/10)
Sys.sleep(0.25)
}
},env = parent.frame(n=1))
doc_terms<- ford()
# Make a vector source
doc_source<-VectorSource(doc_terms)
# Make a volatile corpu
text <- VCorpus(doc_source)
##Function to Clean the Corpus
clean_corpus <- function(corpus){
corpus <- tm_map(corpus, stripWhitespace)
corpus <- tm_map(corpus, removePunctuation)
corpus <- tm_map(corpus, content_transformer(tolower))
corpus<- tm_map(corpus,removeNumbers)
corpus <- tm_map(corpus, removeWords, c(stopwords("english"),"the","you","httpstco","for","amp","today","--"))
return(corpus)
}
# Apply your customized function to the text_corp: clean_corp
text_corp<-clean_corpus(text)
# Create the dtm from the corpus: text_dtm
text_dtm<-DocumentTermMatrix(text_corp)
# Convert text_dtm to a matrix: text_m
text_m<-as.matrix(text_dtm)
## Calculate the rowSums: term_frequency ##################################################################
term_frequency<-colSums(text_m)
# Sort term_frequency in descending order
term_frequency<-sort(term_frequency,decreasing=TRUE)
##Creates data frame of words ########
text_freq<-data.frame(term=names(term_frequency),num=term_frequency)
text_freq
return(text_freq)
})
##Textbreakdown Download ###########
output$downloadtwo <- downloadHandler(
filename = function() { paste("TextBreakDown",input$name, sep='',".csv") },
content = function(file) {
write.csv(texterdf2(), file)
})
##Emotional Sentiment Analysis ###########
observeEvent(input$sentiment,{output$nrcplot<-renderPlot({
withProgress(message = 'Calculating Emotional Sentiment by Word',
value = 0, {
for (i in 1:3) {
incProgress(1/3)
Sys.sleep(0.25)
}
},env = parent.frame(n=1))
value<- ford()
value <- get_nrc_sentiment(value)
value
#Barplot of Emotional Sentiment
barplot(
sort(colSums(prop.table(value[, 1:8]))),
# horiz = input$horz2,
cex.names = 0.7,
las = 1,
main = "Emotional Sentiment by Word"
,col = input$colornow
)
})})
##Positive and Negative Sentiment Analysis ##########
##Sentiment Try
observeEvent(input$negative,{output$nrcplot2<-renderPlot({
withProgress(message = 'Calculating Positive & Negative Sentiment by Word',
value = 0, {
for (i in 1:3) {
incProgress(1/3)
Sys.sleep(0.25)
}
},env = parent.frame(n=1))
value<- ford()
value <- get_nrc_sentiment(value)
value
##Barplot of Emotional Sentiment
barplot(
sort(colSums(prop.table(value[, 9:10]))),
# horiz = input$horz2,
cex.names = 0.7,
las = 1,
main = "Positive vs. Negative Sentiment"
,col = input$colornow2
)
})})
##Get Trajectory #########
## Plot Trajectory #########
observeEvent(input$trajectory,{output$nrcplot3<-renderPlot({
withProgress(message = 'Creating Plot Trajectory',
value = 0, {
for (i in 1:3) {
incProgress(1/3)
Sys.sleep(0.25)
}
},env = parent.frame(n=1))
value<- ford()
s_v <- get_sentences(value)
s_v_sentiment <- get_sentiment(s_v)
plot(
s_v_sentiment,
type="l",
main="Plot Trajectory",
xlab = "Narrative Timeline",
ylab= "Emotional Valence"
)
})})
##Tokenizer Table ###################
##Reactive for Tokenizer Table
wordbreak2d<-reactive({
doc_terms<- ford()
# Make a vector source: doc_source
doc_source<-VectorSource(doc_terms)
# Make a volatile corpus: doc_corpus
doc_corpus <- VCorpus(doc_source)
clean_corpus <- function(corpus){
corpus <- tm_map(corpus, stripWhitespace)
corpus <- tm_map(corpus, removePunctuation)
corpus <- tm_map(corpus, content_transformer(tolower))
corpus <- tm_map(corpus, removeWords, c(stopwords("english"),c(input$words)))
return(corpus)
}
doc_corp<-clean_corpus(doc_corpus)
tokenizer<-function(x)
NGramTokenizer(x,Weka_control(min=input$numeric3,max=input$numeric4))
doc_dtm<-DocumentTermMatrix(doc_corp,control = list(tokenize = tokenizer))
# Convert doc_dtm to a matrix: doc_m
doc_m<-as.matrix(doc_dtm)
# Calculate the rowSums: term_frequency
doc_frequencyone<-colSums(doc_m)
# Sort term_frequency in descending order
doc_frequency<-names(doc_frequencyone)
doc_frequency <- as.data.frame(doc_frequency)
colnames(doc_frequency) <- c("Tokenized Words")
doc_frequency
})
###Renders the bigram table output to the end user
observeEvent(input$bigram,{output$nrcplot4<-DT::renderDataTable({
withProgress(message = 'Creating Bigram Table',
value = 0, {
for (i in 1:3) {
incProgress(1/3)
Sys.sleep(0.25)
}
},env = parent.frame(n=1))
DT::datatable(
wordbreak2d(),extensions = 'Buttons', options = list(
dom = 'Bfrtip',
buttons = c('copy', 'csv', 'excel', 'pdf', 'print')
))
})})
##Sentence Finder ##########
texterdf5<- reactive({
value<- ford()
s_v <- get_sentences(value)
nrc_data <- get_nrc_sentiment(s_v)
emotion_conveyed <- which(nrc_data[,input$emselect] > 0)
final <- as.matrix(s_v[emotion_conveyed])
final
})
observeEvent(input$emotion,{output$nrcplot5<-DT::renderDataTable({
withProgress(message = 'Getting Sentences',
value = 0, {
for (i in 1:3) {
incProgress(1/3)
Sys.sleep(0.25)
}
},env = parent.frame(n=1))
DT::datatable(
texterdf5(),extensions = 'Buttons', options = list(
dom = 'Bfrtip',
buttons = c('copy', 'csv', 'excel', 'pdf', 'print')
))
})})
##Sentiment Analysis Score ###########
observeEvent(input$scsentiment,{output$scosentiment<-DT::renderDataTable({
withProgress(message = 'Calculating Emotional Sentiment',
value = 0, {
for (i in 1:3) {
incProgress(1/3)
Sys.sleep(0.25)
}
},env = parent.frame(n=1))
value<- ford()
value <- get_nrc_sentiment(value)
prop.table(value[,1:8])
sentimentscores <- round(colSums(prop.table((value[,1:8])))*100,digits = 1)
sentimentscores <- as.data.frame(sentimentscores)
colnames(sentimentscores) <- c("Percentages")
Emotions <- c("anger","anticipation","disgust","fear","joy","sadness",
"surprise","trust")
Percentages<- sentimentscores$Percentages
emotionality<- cbind(Emotions,Percentages)
emotionality
})})
##Dataframe for Wordbreakdown ####
texterdf3<- reactive({
doc_terms<- ford()
doc_source<-VectorSource(doc_terms)
# Make a volatile corpus: rom_corpus
text <- VCorpus(doc_source)
##Function to Clean the Corpus
clean_corpus <- function(corpus){
corpus <- tm_map(corpus, stripWhitespace)
corpus <- tm_map(corpus, removePunctuation)
corpus <- tm_map(corpus, content_transformer(tolower))
corpus<- tm_map(corpus,removeNumbers)
corpus <- tm_map(corpus, removeWords, c(stopwords("english"),"the","you","httpstco","for","amp","today","--"))
return(corpus)
}
# Apply your customized function to the text_corp: clean_corp
text_corp<-clean_corpus(text)
# Create the dtm from the corpus: text_dtm
text_dtm<-DocumentTermMatrix(text_corp)
# Convert text_dtm to a matrix: text_m
text_m<-as.matrix(text_dtm)
## Calculate the rowSums: term_frequency ##################################################################
term_frequency<-colSums(text_m)
# Sort term_frequency in descending order
term_frequency<-sort(term_frequency,decreasing=TRUE)
##Creates data frame of words ########
text_freq<-data.frame(term=names(term_frequency),num=term_frequency)
colnames(text_freq) <- c("Term","Number of Occurences")
text_freq
return(text_freq)
})
##Word Breakdown Table ####
observeEvent(input$wbdown,{output$wordbreakdown<-DT::renderDataTable({
withProgress(message = 'Creating Word Breakdown',
value = 0, {
for (i in 1:3) {
incProgress(1/3)
Sys.sleep(0.25)
}
},env = parent.frame(n=1))
worddatabreakdown<- as.matrix.data.frame(texterdf3())
wordatabreakdown <- worddatabreakdown[,1:2]
wordatabreakdown
})})
##Download for Sentiment Percentages ####
texterdf4<- reactive({
withProgress(message = 'Downloading Emotional % CSV File',
value = 0, {
for (i in 1:10) {
incProgress(1/10)
Sys.sleep(0.25)
}
},env = parent.frame(n=1))
value<- ford()
value <- get_nrc_sentiment(value)
#colSums(as.matrix(value))
prop.table(value[,1:8])
sentimentscores <- round(colSums(prop.table((value[,1:8])))*100,digits = 1)
sentimentscores <- as.data.frame(sentimentscores)
colnames(sentimentscores) <- c("Percentages")
Emotions <- c("anger","anticipation","disgust","fear","joy","sadness",
"surprise","trust","negative","positive")
Percentages<- sentimentscores$Percentages
emotionality<- cbind(Emotions,Percentages)
})
output$downloadfour <- downloadHandler(
filename = function() { paste("Emotional Percentage Breakdown",input$name, sep='',".csv") },
content = function(file) {
write.csv(texterdf4(), file)
})
output$downloadfive <- downloadHandler(
filename = function() { paste("Emotion by Sentence Breakdown",input$name, sep='',".csv") },
content = function(file) {
write.csv(texterdf5(), file)
})
barplotdw <- reactive({
doc_terms<- ford()
# Make a vector source: text_source
doc_source<-VectorSource(doc_terms)
## text_source is already in your workspace
# Make a volatile corpus: text_corpus
doc_corpus <- VCorpus(doc_source)
## text_source is already in your workspace
clean_corpus <- function(corpus){
corpus <- tm_map(corpus, stripWhitespace)
corpus <- tm_map(corpus, removePunctuation)
corpus <- tm_map(corpus, content_transformer(tolower))
corpus <- tm_map(corpus, removeWords, c(stopwords("english"),c(input$words)))
return(corpus)
}
doc_corp<-clean_corpus(doc_corpus)
doc_dtm<-DocumentTermMatrix(doc_corp)
# Convert text_dtm to a matrix: text_m
doc_m<-as.matrix(doc_dtm)
# Calculate the rowSums: term_frequency
doc_frequencyone<-colSums(doc_m)
# Sort term_frequency in descending order
doc_frequency<-sort(doc_frequencyone,decreasing=TRUE)
# Plot a barchart of the 10 most common words,
barplot(doc_frequency[input$numeric:input$numeric2],col=input$color,horiz = input$horz,las=2)
})