-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lab2c-SentimentAnalysis.R
1327 lines (1106 loc) · 58.4 KB
/
Lab2c-SentimentAnalysis.R
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
# *****************************************************************************
# Lab 2.c.: Sentiment Analysis (Lexicon-Based) ----
#
# Course Code: BBT4206
# Course Name: Business Intelligence II
# Semester Duration: 21st August 2023 to 28th November 2023
#
# Lecturer: Allan Omondi
# Contact: aomondi [at] strathmore.edu
#
# Note: The lecture contains both theory and practice. This file forms part of
# the practice. It has required lab work submissions that are graded for
# coursework marks.
#
# License: GNU GPL-3.0-or-later
# See LICENSE file for licensing information.
# *****************************************************************************
# **[OPTIONAL] Initialization: Install and use renv ----
# The R Environment ("renv") package helps you create reproducible environments
# for your R projects. This is helpful when working in teams because it makes
# your R projects more isolated, portable and reproducible.
# Further reading:
# Summary: https://rstudio.github.io/renv/
# More detailed article: https://rstudio.github.io/renv/articles/renv.html
# "renv" It can be installed as follows:
# if (!is.element("renv", installed.packages()[, 1])) {
# install.packages("renv", dependencies = TRUE) # nolint
# }
# require("renv") # nolint
# Once installed, you can then use renv::init() to initialize renv in a new
# project.
# The prompt received after executing renv::init() is as shown below:
# This project already has a lockfile. What would you like to do?
# 1: Restore the project from the lockfile.
# 2: Discard the lockfile and re-initialize the project.
# 3: Activate the project without snapshotting or installing any packages.
# 4: Abort project initialization.
# Select option 1 to restore the project from the lockfile
# renv::init() # nolint
# This will set up a project library, containing all the packages you are
# currently using. The packages (and all the metadata needed to reinstall
# them) are recorded into a lockfile, renv.lock, and a .Rprofile ensures that
# the library is used every time you open the project.
# Consider a library as the location where packages are stored.
# Execute the following command to list all the libraries available in your
# computer:
.libPaths()
# One of the libraries should be a folder inside the project if you are using
# renv
# Then execute the following command to see which packages are available in
# each library:
lapply(.libPaths(), list.files)
# This can also be configured using the RStudio GUI when you click the project
# file, e.g., "BBT4206-R.Rproj" in the case of this project. Then
# navigate to the "Environments" tab and select "Use renv with this project".
# As you continue to work on your project, you can install and upgrade
# packages, using either:
# install.packages() and update.packages or
# renv::install() and renv::update()
# You can also clean up a project by removing unused packages using the
# following command: renv::clean()
# After you have confirmed that your code works as expected, use
# renv::snapshot(), AT THE END, to record the packages and their
# sources in the lockfile.
# Later, if you need to share your code with someone else or run your code on
# a new machine, your collaborator (or you) can call renv::restore() to
# reinstall the specific package versions recorded in the lockfile.
# [OPTIONAL]
# Execute the following code to reinstall the specific package versions
# recorded in the lockfile (restart R after executing the command):
# renv::restore() # nolint
# [OPTIONAL]
# If you get several errors setting up renv and you prefer not to use it, then
# you can deactivate it using the following command (restart R after executing
# the command):
# renv::deactivate() # nolint
# If renv::restore() did not install the "languageserver" package (required to
# use R for VS Code), then it can be installed manually as follows (restart R
# after executing the command):
if (!is.element("languageserver", installed.packages()[, 1])) {
install.packages("languageserver", dependencies = TRUE)
}
require("languageserver")
# Methods used for sentiment analysis include:
# (i) Training a known dataset
# (ii) Creating your own classifiers with rules
# (iii) Using predefined lexical dictionaries (lexicons); a lexicon approach
# Levels of sentiment analysis include:
# (i) Document
# (ii) Sentence
# (iii) Word
# STEP 1. Install and Load the Required Packages ----
# The following packages can be installed and loaded before proceeding to the
# subsequent steps.
## dplyr - For data manipulation ----
if (!is.element("dplyr", installed.packages()[, 1])) {
install.packages("dplyr", dependencies = TRUE)
}
require("dplyr")
## ggplot2 - For data visualizations using the Grammar for Graphics package ----
if (!is.element("ggplot2", installed.packages()[, 1])) {
install.packages("ggplot2", dependencies = TRUE)
}
require("ggplot2")
## ggrepel - Additional options for the Grammar for Graphics package ----
if (!is.element("ggrepel", installed.packages()[, 1])) {
install.packages("ggrepel", dependencies = TRUE)
}
require("ggrepel")
## ggraph - Additional options for the Grammar for Graphics package ----
if (!is.element("ggraph", installed.packages()[, 1])) {
install.packages("ggraph", dependencies = TRUE)
}
require("ggraph")
## tidytext - For text mining ----
if (!is.element("tidytext", installed.packages()[, 1])) {
install.packages("tidytext", dependencies = TRUE)
}
require("tidytext")
## tidyr - To tidy messy data ----
if (!is.element("tidyr", installed.packages()[, 1])) {
install.packages("tidyr", dependencies = TRUE)
}
require("tidyr")
## widyr - To widen, process, and re-tidy a dataset ----
if (!is.element("widyr", installed.packages()[, 1])) {
install.packages("widyr", dependencies = TRUE)
}
require("widyr")
## gridExtra - to arrange multiple grid-based plots on a page ----
if (!is.element("gridExtra", installed.packages()[, 1])) {
install.packages("gridExtra", dependencies = TRUE)
}
require("gridExtra")
## knitr - for dynamic report generation ----
if (!is.element("knitr", installed.packages()[, 1])) {
install.packages("knitr", dependencies = TRUE)
}
require("knitr")
## kableExtra - for nicely formatted output tables ----
if (!is.element("kableExtra", installed.packages()[, 1])) {
install.packages("kableExtra", dependencies = TRUE)
}
require("kableExtra")
## formattable - To create a formattable object ----
# A formattable object is an object to which a formatting function and related
# attributes are attached.
if (!is.element("formattable", installed.packages()[, 1])) {
install.packages("formattable", dependencies = TRUE)
}
require("formattable")
## circlize - To create a cord diagram or visualization ----
# by Gu et al. (2014)
if (!is.element("circlize", installed.packages()[, 1])) {
install.packages("circlize", dependencies = TRUE)
}
require("circlize")
## memery - For creating data analysis related memes ----
# The memery package generates internet memes that optionally include a
# superimposed inset plot and other atypical features, combining the visual
# impact of an attention-grabbing meme with graphic results of data analysis.
if (!is.element("memery", installed.packages()[, 1])) {
install.packages("memery", dependencies = TRUE)
}
require("memery")
## magick - For image processing in R ----
if (!is.element("magick", installed.packages()[, 1])) {
install.packages("magick", dependencies = TRUE)
}
require("magick")
## yarrr - To create a pirate plot ----
if (!is.element("yarrr", installed.packages()[, 1])) {
install.packages("yarrr", dependencies = TRUE)
}
require("yarrr")
## radarchart - To create interactive radar charts using ChartJS ----
if (!is.element("radarchart", installed.packages()[, 1])) {
install.packages("radarchart", dependencies = TRUE)
}
require("radarchart")
## igraph - To create ngram network diagrams ----
if (!is.element("igraph", installed.packages()[, 1])) {
install.packages("igraph", dependencies = TRUE)
}
require("igraph")
## wordcloud2 - For creating wordcloud by using 'wordcloud2.JS ----
if (!is.element("wordcloud2", installed.packages()[, 1])) {
install.packages("wordcloud2", dependencies = TRUE)
}
require("wordcloud2")
## textdata - Download sentiment lexicons and labeled text data sets ----
if (!is.element("textdata", installed.packages()[, 1])) {
install.packages("textdata", dependencies = TRUE)
}
require("textdata")
## readr - Load datasets from CSV files ----
if (!is.element("readr", installed.packages()[, 1])) {
install.packages("readr", dependencies = TRUE)
}
require("readr")
## stringr - For processing characters in a string ----
if (!is.element("stringr", installed.packages()[, 1])) {
install.packages("stringr", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
require("stringr")
## lexicon - An alternative to load the NRC lexicon ----
if (!is.element("lexicon", installed.packages()[, 1])) {
install.packages("lexicon", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
require("lexicon")
# STEP 2. Customize the Visualizations, Tables, and Colour Scheme ----
# The following defines a blue-grey colour scheme for the visualizations:
## shades of blue and shades of grey
blue_grey_colours_11 <- c("#27408E", "#304FAF", "#536CB5", "#6981c7", "#8da0db",
"#dde5ec", "#c8c9ca", "#B9BCC2", "#A7AAAF", "#888A8E",
"#636569")
blue_grey_colours_6 <- c("#27408E", "#304FAF", "#536CB5",
"#B9BCC2", "#A7AAAF", "#888A8E")
blue_grey_colours_4 <- c("#27408E", "#536CB5",
"#B9BCC2", "#888A8E")
blue_grey_colours_3 <- c("#6981c7", "#304FAF", "#888A8E")
blue_grey_colours_2 <- c("#27408E",
"#888A8E")
blue_grey_colours_1 <- c("#6981c7")
# Custom theme for visualizations
blue_grey_theme <- function() {
theme(
axis.ticks = element_line(
linewidth = 1, linetype = "dashed",
lineend = NULL, color = "#dfdede",
arrow = NULL, inherit.blank = FALSE),
axis.text = element_text(
face = "bold", color = "#3f3f41",
size = 12, hjust = 0.5),
axis.title = element_text(face = "bold", color = "#3f3f41",
size = 14, hjust = 0.5),
plot.title = element_text(face = "bold", color = "#3f3f41",
size = 16, hjust = 0.5),
panel.grid = element_line(
linewidth = 0.1, linetype = "dashed",
lineend = NULL, color = "#dfdede",
arrow = NULL, inherit.blank = FALSE),
panel.background = element_rect(fill = "#f3eeee"),
legend.title = element_text(face = "plain", color = "#3f3f41",
size = 12, hjust = 0),
legend.position = "right"
)
}
# Customize the text tables for consistency using HTML formatting
kable_theme <- function(dat, caption) {
kable(dat, "html", escape = FALSE, caption = caption) %>%
kable_styling(bootstrap_options = c("striped", "condensed", "bordered"),
full_width = FALSE)
}
# STEP 3. Load the Dataset ----
student_performance_dataset <-
read_csv("data/20230412-20230719-BI1-BBIT4-1-StudentPerformanceDataset.CSV",
col_types =
cols(
class_group = col_factor(levels = c("A", "B", "C")),
gender = col_factor(levels = c("1", "0")),
YOB = col_date(format = "%Y"),
regret_choosing_bi = col_factor(levels = c("1", "0")),
drop_bi_now = col_factor(levels = c("1", "0")),
motivator = col_factor(levels = c("1", "0")),
read_content_before_lecture =
col_factor(levels = c("1", "2", "3", "4", "5")),
anticipate_test_questions =
col_factor(levels = c("1", "2", "3", "4", "5")),
answer_rhetorical_questions =
col_factor(levels = c("1", "2", "3", "4", "5")),
find_terms_I_do_not_know =
col_factor(levels = c("1", "2", "3", "4", "5")),
copy_new_terms_in_reading_notebook =
col_factor(levels = c("1", "2", "3", "4", "5")),
take_quizzes_and_use_results =
col_factor(levels = c("1", "2", "3", "4", "5")),
reorganise_course_outline =
col_factor(levels = c("1", "2", "3", "4", "5")),
write_down_important_points =
col_factor(levels = c("1", "2", "3", "4", "5")),
space_out_revision =
col_factor(levels = c("1", "2", "3", "4", "5")),
studying_in_study_group =
col_factor(levels = c("1", "2", "3", "4", "5")),
schedule_appointments =
col_factor(levels = c("1", "2", "3", "4", "5")),
goal_oriented = col_factor(levels = c("1", "0")),
spaced_repetition =
col_factor(levels = c("1", "2", "3", "4")),
testing_and_active_recall =
col_factor(levels = c("1", "2", "3", "4")),
interleaving = col_factor(levels = c("1", "2", "3", "4")),
categorizing = col_factor(levels = c("1", "2", "3", "4")),
retrospective_timetable =
col_factor(levels = c("1", "2", "3", "4")),
cornell_notes = col_factor(levels = c("1", "2", "3", "4")),
sq3r = col_factor(levels = c("1", "2", "3", "4")),
commute = col_factor(levels = c("1", "2", "3", "4")),
study_time = col_factor(levels = c("1", "2", "3", "4")),
repeats_since_Y1 = col_integer(),
paid_tuition = col_factor(levels = c("0", "1")),
free_tuition = col_factor(levels = c("0", "1")),
extra_curricular = col_factor(levels = c("0", "1")),
sports_extra_curricular = col_factor(levels = c("0", "1")),
exercise_per_week = col_factor(levels = c("0", "1", "2", "3")),
meditate = col_factor(levels = c("0", "1", "2", "3")),
pray = col_factor(levels = c("0", "1", "2", "3")),
internet = col_factor(levels = c("0", "1")),
laptop = col_factor(levels = c("0", "1")),
family_relationships =
col_factor(levels = c("1", "2", "3", "4", "5")),
friendships = col_factor(levels = c("1", "2", "3", "4", "5")),
romantic_relationships =
col_factor(levels = c("0", "1", "2", "3", "4")),
spiritual_wellnes =
col_factor(levels = c("1", "2", "3", "4", "5")),
financial_wellness =
col_factor(levels = c("1", "2", "3", "4", "5")),
health = col_factor(levels = c("1", "2", "3", "4", "5")),
day_out = col_factor(levels = c("0", "1", "2", "3")),
night_out = col_factor(levels = c("0", "1", "2", "3")),
alcohol_or_narcotics =
col_factor(levels = c("0", "1", "2", "3")),
mentor = col_factor(levels = c("0", "1")),
mentor_meetings = col_factor(levels = c("0", "1", "2", "3")),
`Attendance Waiver Granted: 1 = Yes, 0 = No` =
col_factor(levels = c("0", "1")),
GRADE = col_factor(levels = c("A", "B", "C", "D", "E"))),
locale = locale())
View(student_performance_dataset)
## Create a filtered subset of the data ----
# Function to expand contractions
expand_contractions <- function(doc) {
doc <- gsub("I'm", "I am", doc, ignore.case = TRUE)
doc <- gsub("you're", "you are", doc, ignore.case = TRUE)
doc <- gsub("he's", "he is", doc, ignore.case = TRUE)
doc <- gsub("she's", "she is", doc, ignore.case = TRUE)
doc <- gsub("it's", "it is", doc, ignore.case = TRUE)
doc <- gsub("we're", "we are", doc, ignore.case = TRUE)
doc <- gsub("they're", "they are", doc, ignore.case = TRUE)
doc <- gsub("I'll", "I will", doc, ignore.case = TRUE)
doc <- gsub("you'll", "you will", doc, ignore.case = TRUE)
doc <- gsub("he'll", "he will", doc, ignore.case = TRUE)
doc <- gsub("she'll", "she will", doc, ignore.case = TRUE)
doc <- gsub("it'll", "it will", doc, ignore.case = TRUE)
doc <- gsub("we'll", "we will", doc, ignore.case = TRUE)
doc <- gsub("they'll", "they will", doc, ignore.case = TRUE)
doc <- gsub("won't", "will not", doc, ignore.case = TRUE)
doc <- gsub("can't", "cannot", doc, ignore.case = TRUE)
doc <- gsub("n't", " not", doc, ignore.case = TRUE)
return(doc)
}
# Select the class group, gender, average course evaluation rating,
# and most importantly, the likes and wishes from the original dataset
evaluation_likes_and_wishes <- student_performance_dataset %>%
mutate(`Student's Gender` =
ifelse(gender == 1, "Male", "Female")) %>%
rename(`Class Group` = class_group) %>%
rename(Likes = `D - 1. \nWrite two things you like about the teaching and learning in this unit so far.`) %>% # nolint
rename(Wishes = `D - 2. Write at least one recommendation to improve the teaching and learning in this unit (for the remaining weeks in the semester)`) %>% # nolint
select(`Class Group`,
`Student's Gender`, `Average Course Evaluation Rating`,
Likes, Wishes) %>%
filter(!is.na(`Average Course Evaluation Rating`)) %>%
arrange(`Class Group`)
evaluation_likes_and_wishes$Likes <- sapply(
evaluation_likes_and_wishes$Likes,
expand_contractions)
evaluation_likes_and_wishes$Wishes <- sapply(
evaluation_likes_and_wishes$Wishes,
expand_contractions)
head(evaluation_likes_and_wishes, 10)
# Function to remove special characters and convert all text to a standard
# lower case
remove_special_characters <- function(doc) {
gsub("[^a-zA-Z ]", "", doc, ignore.case = TRUE)
}
evaluation_likes_and_wishes$Likes <- sapply(evaluation_likes_and_wishes$Likes,
remove_special_characters)
evaluation_likes_and_wishes$Wishes <- sapply(evaluation_likes_and_wishes$Wishes,
remove_special_characters)
# Convert everything to lower case (to standardize the text)
evaluation_likes_and_wishes$Likes <- sapply(evaluation_likes_and_wishes$Likes,
tolower)
evaluation_likes_and_wishes$Wishes <- sapply(evaluation_likes_and_wishes$Wishes,
tolower)
# After removing special characters and converting everything to lower case
head(evaluation_likes_and_wishes, 10)
write.csv(evaluation_likes_and_wishes,
file = "data/evaluation_likes_and_wishes.csv",
row.names = FALSE)
# Function to censor/remove unwanted words
undesirable_words <- c("wow", "lol", "none", "na")
# unnest and remove stopwords, undesirable words, and short words
evaluation_likes_filtered <- evaluation_likes_and_wishes %>% # nolint
unnest_tokens(word, Likes) %>%
# do not join where the word is in the list of stopwords
anti_join(stop_words, by = c("word")) %>%
distinct() %>%
filter(!word %in% undesirable_words) %>%
filter(nchar(word) > 3) %>%
rename(`Likes (tokenized)` = word) %>%
select(-Wishes)
write.csv(evaluation_likes_filtered,
file = "data/evaluation_likes_filtered.csv",
row.names = FALSE)
evaluation_wishes_filtered <- evaluation_likes_and_wishes %>% # nolint
unnest_tokens(word, Wishes) %>%
# do not join where the word is in the list of stopwords
anti_join(stop_words, by = c("word")) %>%
distinct() %>%
filter(!word %in% undesirable_words) %>%
filter(nchar(word) > 3) %>%
rename(`Wishes (tokenized)` = word) %>%
select(-Likes)
write.csv(evaluation_wishes_filtered,
file = "data/evaluation_wishes_filtered.csv",
row.names = FALSE)
# STEP 4. Load the Required Lexicon (NRC) ----
# Sentiment analysis, also known as opinion mining, is a Natural Language
# Processing (NLP) technique used to determine and extract subjective
# information from text data. The goal of sentiment analysis is to assess and
# quantify the sentiment or emotional tone expressed in a piece of text, such
# as a sentence, paragraph, or document. It involves determining whether the
# text expresses a positive, negative, or neutral sentiment. It can also
# provide a more granular analysis, such as identifying specific emotions like
# joy, anger, sadness, or surprise.
# Methods used to perform sentiment analysis include:
# (i) training a known dataset
# (ii) creating your own classifiers with rules
# (iii) using predefined lexical dictionaries (lexicons).
# There are also different levels of analysis based on the text. These are:
# (i) document
# (ii) sentence
# (iii) word
# We will perform sentiment analysis using lexicons at the word level.
# A lexical dictionary (lexicon), specifically a sentiment lexicon, contains
# words or phrases and assigns sentiment or emotional polarity to each entry.
# Words are typically labelled as positive, negative, neutral, joy, anger,
# sadness, surprise, etc., to aid in sentiment analysis tasks.
# NOTE: No lexicon can have all words, nor should it. Many words are considered
# neutral and would not have an associated sentiment.
## Sample Sentiment Lexicons ----
# 3 common lexicons include:
### NRC ----
# By Mohammad & Turney (2013)
# Assigns words into one or more of the following ten categories:
# positive, negative, anger, anticipation, disgust, fear, joy, sadness,
# surprise, and trust.
nrc <- get_sentiments("nrc")
View(nrc)
# If you get an error locating the NRC lexicon using the code above,
# then you can locate it using the `lexicon` package instead of using the
# `tidytext` package as shown below:
# Alternative source of the NRC lexicon:
data(hash_nrc_emotions)
nrc <- hash_nrc_emotions
nrc <- nrc %>%
mutate(word = token, sentiment = emotion) %>%
select(word, sentiment)
View(nrc)
### AFINN ----
# Assigns words with a score that runs between -5 and 5. Negative scores
# indicate negative sentiments and positive scores indicate positive sentiments
afinn <- get_sentiments(lexicon = "afinn")
View(afinn)
### Bing ----
# Assigns words into positive and negative categories only
bing <- get_sentiments("bing")
View(bing)
### Loughran ----
# By Loughran & McDonald, (2010)
# The Loughran lexicon is specifically designed for financial text analysis and
# categorizes words into different financial sentiment categories.
loughran <- get_sentiments("loughran")
View(loughran)
# If you get an error locating the Loughran lexicon using the code above,
# then you can download it manually from the University of Notre Dame here:
# URL: https://sraf.nd.edu/loughranmcdonald-master-dictionary/
loughran <- read_csv("data/LoughranMcDonald_MasterDictionary_2018.csv")
View(loughran)
# STEP 5. Inner Join the Likes/Wishes with the Corresponding Sentiment(s) ----
evaluation_likes_filtered_nrc <- evaluation_likes_filtered %>%
inner_join(nrc,
by = join_by(`Likes (tokenized)` == word),
relationship = "many-to-many")
evaluation_wishes_filtered_nrc <- evaluation_wishes_filtered %>%
inner_join(nrc,
by = join_by(`Wishes (tokenized)` == word),
relationship = "many-to-many")
# STEP 6. Overall Sentiment ----
## Evaluation Likes ----
nrc_likes_plot <- evaluation_likes_filtered_nrc %>%
group_by(sentiment) %>%
# You can filter by the class group if you wish
# filter(`Class Group` == "A") %>%
summarise(word_count = n()) %>%
ungroup() %>%
mutate(sentiment = reorder(sentiment, word_count)) %>%
# `fill = -word_count` is used to make the larger bars darker
ggplot(aes(sentiment, word_count, fill = -word_count)) +
geom_col() +
guides(fill = FALSE) + # Turn off the legend
blue_grey_theme() +
labs(x = "Sentiment", y = "Word Count") +
# scale_y_continuous(limits = c(0, 15000)) + #Hard code the axis limit
ggtitle("Lexicon-Based Sentiment Analysis of Course Evaluation Likes") +
coord_flip()
plot(nrc_likes_plot)
# Various organizations have brand guidelines. You can download the
# University's brand guidelines from here:
# https://strathmore.edu/brand-guidelines/
img <- "images/SCES-logo-01-blue-grey-bg-with-meme-space.jpg"
# The meme's label can be specified here:
lab <- "The BBT4106: Business Intelligence I course
taught from 12th April 2023 to 19th July 2023
by Dr Allan Omondi"
# Overlay the plot on the image and create the meme file
meme(img, lab, "memes/nrc_likes_plot.jpg", inset = nrc_likes_plot)
#Read the file back in and display it!
nrc_meme <- image_read("memes/nrc_likes_plot.jpg")
plot(nrc_meme)
## Evaluation Wishes ----
nrc_wishes_plot <- evaluation_wishes_filtered_nrc %>%
group_by(sentiment) %>%
# You can filter by the class group if you wish
# filter(`Class Group` == "A") %>%
summarise(word_count = n()) %>%
ungroup() %>%
mutate(sentiment = reorder(sentiment, word_count)) %>%
# fill = -word_count is used to make the larger bars darker
ggplot(aes(sentiment, word_count, fill = -word_count)) +
geom_col() +
guides(fill = FALSE) + # Turn off the legend
blue_grey_theme() +
labs(x = "Sentiment", y = "Word Count") +
# scale_y_continuous(limits = c(0, 15000)) + #Hard code the axis limit
ggtitle("Lexicon-Based Sentiment Analysis of Course Evaluation Wishes") +
coord_flip()
plot(nrc_wishes_plot)
# Various organizations have brand guidelines. You can download the
# University's brand guidelines from here:
# https://strathmore.edu/brand-guidelines/
img <- "images/SCES-logo-01-blue-grey-bg-with-meme-space.jpg"
# The meme's label can be specified here:
lab <- "The BBT4106: Business Intelligence I course
taught from 12th April 2023 to 19th July 2023
by Dr Allan Omondi"
# Overlay the plot on the image and create the meme file
meme(img, lab, "memes/nrc_wishes_plot.jpg", inset = nrc_wishes_plot)
#Read the file back in and display it!
nrc_meme <- image_read("memes/nrc_wishes_plot.jpg")
plot(nrc_meme)
# STEP 7. Frequency Sentiment per Group and per Gender ----
## Evaluation Likes per Group ----
# We can save the plots by hard-coding the save function as follows:
# NOTE: Execute one filetype at a time, i.e., either PNG, JPEG, SVG, or PDF.
# png(filename = "visualizations/nrc_likes_chord.png",
# width = 1920, height = 1080, units = "px", pointsize = 12,
# bg = "transparent", res = 150)
jpeg(filename = "visualizations/nrc_likes_chord.jpeg",
width = 1920, height = 1080, units = "px", pointsize = 12,
bg = "transparent", res = 150)
# svg(filename = "visualizations/nrc_likes_chord.svg",
# width = 8.5, height = 8.5, pointsize = 12,
# bg = "transparent")
# pdf("visualizations/nrc_likes_chord.pdf",
# width = 8.5, height = 8.5,
# bg = "transparent", pagecentre = TRUE, paper = "A4")
grid_col <- c("A" = blue_grey_colours_11[1],
"B" = "#f3c487",
"C" = blue_grey_colours_11[5])
nrc_likes_chord <- evaluation_likes_filtered_nrc %>%
# filter(decade != "NA" & !sentiment %in% c("positive", "negative")) %>%
count(sentiment, `Class Group`) %>%
group_by(`Class Group`, sentiment) %>%
summarise(sentiment_sum = sum(n)) %>%
filter(sentiment_sum > 10) %>%
mutate(sentiment = reorder(sentiment, sentiment_sum)) %>%
ungroup()
circos.clear()
# Set the gap size
circos.par(gap.after = c(rep(5, length(unique(nrc_likes_chord[[1]])) - 1), 15,
rep(5, length(unique(nrc_likes_chord[[2]])) - 1), 15))
chordDiagram(nrc_likes_chord, grid.col = grid_col, transparency = .2)
title("Lexicon-Based Sentiment Analysis of Course Evaluation Likes per Group")
# To close the device used to create either the PNG, JPEG, SVG, or PDF.
dev.off()
# To plot the chord diagram in the IDE:
chordDiagram(nrc_likes_chord, grid.col = grid_col, transparency = .2)
title("Lexicon-Based Sentiment Analysis of Course Evaluation Likes per Group")
## Evaluation Wishes per Group ----
# We can save the plots by hard-coding the save function as follows:
# NOTE: Execute one filetype at a time, i.e., either PNG, JPEG, SVG, or PDF.
# png(filename = "visualizations/nrc_wishes_chord.png",
# width = 1920, height = 1080, units = "px", pointsize = 12,
# bg = "transparent", res = 150)
jpeg(filename = "visualizations/nrc_wishes_chord.jpeg",
width = 1920, height = 1080, units = "px", pointsize = 12,
bg = "transparent", res = 150)
# svg(filename = "visualizations/nrc_wishes_chord.svg",
# width = 8.5, height = 8.5, pointsize = 12,
# bg = "transparent")
# pdf("visualizations/nrc_wishes_chord.pdf",
# width = 8.5, height = 8.5,
# bg = "transparent", pagecentre = TRUE, paper = "A4")
grid_col <- c("A" = blue_grey_colours_11[1],
"B" = "#f3c487",
"C" = blue_grey_colours_11[5])
nrc_wishes_chord <- evaluation_wishes_filtered_nrc %>%
# filter(decade != "NA" & !sentiment %in% c("positive", "negative")) %>%
count(sentiment, `Class Group`) %>%
group_by(`Class Group`, sentiment) %>%
summarise(sentiment_sum = sum(n)) %>%
filter(sentiment_sum > 3) %>%
mutate(sentiment = reorder(sentiment, sentiment_sum)) %>%
ungroup()
circos.clear()
# Set the gap size
circos.par(gap.after = c(rep(5, length(unique(nrc_wishes_chord[[1]])) - 1), 15,
rep(5, length(unique(nrc_wishes_chord[[2]])) - 1), 15))
chordDiagram(nrc_wishes_chord, grid.col = grid_col, transparency = .2)
title("Lexicon-Based Sentiment Analysis of Course Evaluation Wishes per Group")
# To close the device used to create either the PNG, JPEG, SVG, or PDF.
dev.off()
# To plot the chord diagram in the IDE:
chordDiagram(nrc_wishes_chord, grid.col = grid_col, transparency = .2)
title("Lexicon-Based Sentiment Analysis of Course Evaluation Wishes per Group")
## Evaluation Likes per Gender ----
# We can save the plots by hard-coding the save function as follows:
# NOTE: Execute one filetype at a time, i.e., either PNG, JPEG, SVG, or PDF.
# png(filename = "visualizations/nrc_likes_gender_chord.png",
# width = 1920, height = 1080, units = "px", pointsize = 12,
# bg = "transparent", res = 150)
jpeg(filename = "visualizations/nrc_likes_gender_chord.jpeg",
width = 1920, height = 1080, units = "px", pointsize = 12,
bg = "transparent", res = 150)
# svg(filename = "visualizations/nrc_likes_gender_chord.svg",
# width = 8.5, height = 8.5, pointsize = 12,
# bg = "transparent")
# pdf("visualizations/nrc_likes_gender_chord.pdf",
# width = 8.5, height = 8.5,
# bg = "transparent", pagecentre = TRUE, paper = "A4")
grid_col <- c("Male" = blue_grey_colours_11[1],
"Female" = "#f387f3")
nrc_likes_chord <- evaluation_likes_filtered_nrc %>%
# filter(decade != "NA" & !sentiment %in% c("positive", "negative")) %>%
count(sentiment, `Student's Gender`) %>%
group_by(`Student's Gender`, sentiment) %>%
summarise(sentiment_sum = sum(n)) %>%
filter(sentiment_sum > 10) %>%
mutate(sentiment = reorder(sentiment, sentiment_sum)) %>%
ungroup()
circos.clear()
# Set the gap size
circos.par(gap.after = c(rep(5, length(unique(nrc_likes_chord[[1]])) - 1), 15,
rep(5, length(unique(nrc_likes_chord[[2]])) - 1), 15))
chordDiagram(nrc_likes_chord, grid.col = grid_col, transparency = .2)
title("Lexicon-Based Sentiment Analysis of Course Evaluation Likes per Gender")
# To close the device used to create either the PNG, JPEG, SVG, or PDF.
dev.off()
# To plot the chord diagram in the IDE:
chordDiagram(nrc_likes_chord, grid.col = grid_col, transparency = .2)
title("Lexicon-Based Sentiment Analysis of Course Evaluation Likes per Gender")
## Evaluation Wishes per Gender ----
# We can save the plots by hard-coding the save function as follows:
# NOTE: Execute one filetype at a time, i.e., either PNG, JPEG, SVG, or PDF.
# png(filename = "visualizations/nrc_wishes_gender_chord.png",
# width = 1920, height = 1080, units = "px", pointsize = 12,
# bg = "transparent", res = 150)
jpeg(filename = "visualizations/nrc_wishes_gender_chord.jpeg",
width = 1920, height = 1080, units = "px", pointsize = 12,
bg = "transparent", res = 150)
# svg(filename = "visualizations/nrc_wishes_gender_chord.svg",
# width = 8.5, height = 8.5, pointsize = 12,
# bg = "transparent")
# pdf("visualizations/nrc_wishes_gender_chord.pdf",
# width = 8.5, height = 8.5,
# bg = "transparent", pagecentre = TRUE, paper = "A4")
grid_col <- c("Male" = "lightblue",
"Female" = "lightpink")
nrc_wishes_chord <- evaluation_wishes_filtered_nrc %>%
# filter(decade != "NA" & !sentiment %in% c("positive", "negative")) %>%
count(sentiment, `Student's Gender`) %>%
group_by(`Student's Gender`, sentiment) %>%
summarise(sentiment_sum = sum(n)) %>%
filter(sentiment_sum > 3) %>%
mutate(sentiment = reorder(sentiment, sentiment_sum)) %>%
ungroup()
circos.clear()
# Set the gap size
circos.par(gap.after = c(rep(5, length(unique(nrc_wishes_chord[[1]])) - 1), 15,
rep(5, length(unique(nrc_wishes_chord[[2]])) - 1), 15))
chordDiagram(nrc_wishes_chord, grid.col = grid_col, transparency = .2)
title("Lexicon-Based Sentiment Analysis of Course Evaluation Wishes per Gender")
# To close the device used to create either the PNG, JPEG, SVG, or PDF.
dev.off()
# To plot the chord diagram in the IDE:
chordDiagram(nrc_wishes_chord, grid.col = grid_col, transparency = .2)
title("Lexicon-Based Sentiment Analysis of Course Evaluation Wishes per Gender")
# STEP 8. Percentage Sentiment per Group and per Gender ----
## Evaluation Likes per Group ----
# Get the count of words per sentiment per group
nrc_likes_per_sentiment_per_group_radar <- # nolint
evaluation_likes_filtered_nrc %>%
group_by(`Class Group`, sentiment) %>%
count(`Class Group`, sentiment) %>%
select(`Class Group`, sentiment, sentiment_count = n)
View(nrc_likes_per_sentiment_per_group_radar)
# Get the total count of sentiment words per group (not distinct)
nrc_likes_total_per_group_radar <- evaluation_likes_filtered_nrc %>% # nolint
count(`Class Group`) %>%
select(`Class Group`, group_total = n)
View(nrc_likes_total_per_group_radar)
# Join the two and create a percent field
nrc_likes_group_radar_chart <- nrc_likes_per_sentiment_per_group_radar %>%
inner_join(nrc_likes_total_per_group_radar, by = "Class Group") %>%
mutate(percent = sentiment_count / group_total * 100) %>%
select(-sentiment_count, -group_total) %>%
spread(`Class Group`, percent)
View(nrc_likes_group_radar_chart)
# Plot the radar visualization using chartJS
chartJSRadar(nrc_likes_group_radar_chart,
showToolTipLabel = TRUE,
main = "Lexicon−Based Percentage Sentiment Analysis of Course Evaluation Likes per Group") # nolint
## Evaluation Likes per Gender ----
# Get the count of words per sentiment per gender
nrc_likes_per_sentiment_per_gender_radar <- # nolint
evaluation_likes_filtered_nrc %>%
group_by(`Student's Gender`, sentiment) %>%
count(`Student's Gender`, sentiment) %>%
select(`Student's Gender`, sentiment, sentiment_count = n)
View(nrc_likes_per_sentiment_per_gender_radar)
# Get the total count of sentiment words per gender (not distinct)
nrc_likes_total_per_gender_radar <- evaluation_likes_filtered_nrc %>% # nolint
count(`Student's Gender`) %>%
select(`Student's Gender`, group_total = n)
View(nrc_likes_total_per_gender_radar)
# Join the two and create a percent field
nrc_likes_gender_radar_chart <- nrc_likes_per_sentiment_per_gender_radar %>%
inner_join(nrc_likes_total_per_gender_radar, by = "Student's Gender") %>%
mutate(percent = sentiment_count / group_total * 100) %>%
select(-sentiment_count, -group_total) %>%
spread(`Student's Gender`, percent)
View(nrc_likes_gender_radar_chart)
# Plot the radar visualization using chartJS
chartJSRadar(nrc_likes_gender_radar_chart,
showToolTipLabel = TRUE,
main = "Lexicon−Based Percentage Sentiment Analysis of Course Evaluation Likes per Gender") # nolint
## Evaluation Wishes per Group ----
# Get the count of words per sentiment per group
nrc_wishes_per_sentiment_per_group_radar <- # nolint
evaluation_wishes_filtered_nrc %>%
group_by(`Class Group`, sentiment) %>%
count(`Class Group`, sentiment) %>%
select(`Class Group`, sentiment, sentiment_count = n)
View(nrc_wishes_per_sentiment_per_group_radar)
# Get the total count of sentiment words per group (not distinct)
nrc_wishes_total_per_group_radar <- evaluation_wishes_filtered_nrc %>% # nolint
count(`Class Group`) %>%
select(`Class Group`, group_total = n)
View(nrc_wishes_total_per_group_radar)
# Join the two and create a percent field
nrc_wishes_group_radar_chart <- nrc_wishes_per_sentiment_per_group_radar %>%
inner_join(nrc_wishes_total_per_group_radar, by = "Class Group") %>%
mutate(percent = sentiment_count / group_total * 100) %>%
select(-sentiment_count, -group_total) %>%
spread(`Class Group`, percent)
View(nrc_wishes_group_radar_chart)
# Plot the radar visualization using chartJS
chartJSRadar(nrc_wishes_group_radar_chart,
showToolTipLabel = TRUE,
main = "Lexicon−Based Percentage Sentiment Analysis of Course Evaluation Wishes per Group") # nolint
## Evaluation Wishes per Gender ----
# Get the count of words per sentiment per gender
nrc_wishes_per_sentiment_per_gender_radar <- # nolint
evaluation_wishes_filtered_nrc %>%
group_by(`Student's Gender`, sentiment) %>%
count(`Student's Gender`, sentiment) %>%
select(`Student's Gender`, sentiment, sentiment_count = n)
View(nrc_wishes_per_sentiment_per_gender_radar)
# Get the total count of sentiment words per gender (not distinct)
nrc_wishes_total_per_gender_radar <- evaluation_wishes_filtered_nrc %>% # nolint
count(`Student's Gender`) %>%
select(`Student's Gender`, group_total = n)
View(nrc_wishes_total_per_gender_radar)
# Join the two and create a percent field
nrc_wishes_gender_radar_chart <- nrc_wishes_per_sentiment_per_gender_radar %>%
inner_join(nrc_wishes_total_per_gender_radar, by = "Student's Gender") %>%
mutate(percent = sentiment_count / group_total * 100) %>%
select(-sentiment_count, -group_total) %>%
spread(`Student's Gender`, percent)
View(nrc_wishes_gender_radar_chart)
# Plot the radar visualization using chartJS
chartJSRadar(nrc_wishes_gender_radar_chart,
showToolTipLabel = TRUE,
main = "Lexicon−Based Percentage Sentiment Analysis of Course Evaluation Likes per Gender") # nolint
# STEP 9. Classification of Words per Sentiment ----
## Evaluation Likes ----
evaluation_likes_filtered_nrc %>%
# filter(`Class Group` %in% "A") %>%
distinct(`Likes (tokenized)`) %>%
inner_join(nrc,
by = join_by(`Likes (tokenized)` == word),
relationship = "many-to-many") %>%
ggplot(aes(x = `Likes (tokenized)`, fill = sentiment)) +
facet_grid(~sentiment) +
geom_bar() + # Create a bar for each word per sentiment
theme(panel.grid.major.x = element_blank(),
axis.text.x = element_blank()) + # Place the words on the y-axis
xlab(NULL) + ylab(NULL) +
ggtitle(paste("Classification of Words in Course Evaluation Likes ",
"based on the NRC Lexicon")) +
coord_flip()
## Evaluation Wishes ----
evaluation_wishes_filtered_nrc %>%
# filter(`Class Group` %in% "A") %>%
distinct(`Wishes (tokenized)`) %>%
inner_join(nrc,
by = join_by(`Wishes (tokenized)` == word),
relationship = "many-to-many") %>%
ggplot(aes(x = `Wishes (tokenized)`, fill = sentiment)) +
facet_grid(~sentiment) +
geom_bar() + # Create a bar for each word per sentiment
theme(panel.grid.major.x = element_blank(),
axis.text.x = element_blank()) + # Place the words on the y-axis
xlab(NULL) + ylab(NULL) +
ggtitle(paste("Classification of Words in Course Evaluation Wishes ",
"based on the NRC Lexicon")) +
coord_flip()
# STEP 10. Average per Question ----
## Average per Question per Group ----
evaluation_rating_per_question_per_group <- student_performance_dataset %>% # nolint
rename(`Class Group` = class_group) %>%
filter(!is.na(`Average Course Evaluation Rating`)) %>%