-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLab2b-ExploratoryDataAnalysisForQualitativeData.R
More file actions
1631 lines (1391 loc) · 70 KB
/
Lab2b-ExploratoryDataAnalysisForQualitativeData.R
File metadata and controls
1631 lines (1391 loc) · 70 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
# *****************************************************************************
# Lab 2.b.: Exploratory Data Analysis for Qualitative Data ----
#
# Course Code: BBT4206
# Course Name: Business Intelligence II
# Semester Duration: 21st August 2023 to 28th November 2023
#
# Lecturer: Allan Omondi
# Contact: aomondi_at_strathmore_dot_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,
# repos = "https://cloud.r-project.org") # 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,
repos = "https://cloud.r-project.org")
}
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,
repos = "https://cloud.r-project.org")
}
require("dplyr")
## ggplot2 - For data visualizations using the Grammar for Graphics package ----
if (!is.element("ggplot2", installed.packages()[, 1])) {
install.packages("ggplot2", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
require("ggplot2")
## ggrepel - Additional options for the Grammar for Graphics package ----
if (!is.element("ggrepel", installed.packages()[, 1])) {
install.packages("ggrepel", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
require("ggrepel")
## ggraph - Additional options for the Grammar for Graphics package ----
if (!is.element("ggraph", installed.packages()[, 1])) {
install.packages("ggraph", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
require("ggraph")
## tidytext - For text mining ----
if (!is.element("tidytext", installed.packages()[, 1])) {
install.packages("tidytext", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
require("tidytext")
## tidyr - To tidy messy data ----
if (!is.element("tidyr", installed.packages()[, 1])) {
install.packages("tidyr", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
require("tidyr")
## widyr - To widen, process, and re-tidy a dataset ----
if (!is.element("widyr", installed.packages()[, 1])) {
install.packages("widyr", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
require("widyr")
## gridExtra - to arrange multiple grid-based plots on a page ----
if (!is.element("gridExtra", installed.packages()[, 1])) {
install.packages("gridExtra", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
require("gridExtra")
## knitr - for dynamic report generation ----
if (!is.element("knitr", installed.packages()[, 1])) {
install.packages("knitr", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
require("knitr")
## kableExtra - for nicely formatted output tables ----
if (!is.element("kableExtra", installed.packages()[, 1])) {
install.packages("kableExtra", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
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,
repos = "https://cloud.r-project.org")
}
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,
repos = "https://cloud.r-project.org")
}
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,
repos = "https://cloud.r-project.org")
}
require("memery")
## magick - For image processing in R ----
if (!is.element("magick", installed.packages()[, 1])) {
install.packages("magick", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
require("magick")
## yarrr - To create a pirate plot ----
if (!is.element("yarrr", installed.packages()[, 1])) {
install.packages("yarrr", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
require("yarrr")
## radarchart - To create interactive radar charts using ChartJS ----
if (!is.element("radarchart", installed.packages()[, 1])) {
install.packages("radarchart", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
require("radarchart")
## igraph - To create ngram network diagrams ----
if (!is.element("igraph", installed.packages()[, 1])) {
install.packages("igraph", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
require("igraph")
## wordcloud2 - For creating wordcloud by using 'wordcloud2.JS ----
if (!is.element("wordcloud2", installed.packages()[, 1])) {
install.packages("wordcloud2", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
require("wordcloud2")
## readr - Load datasets from CSV files ----
if (!is.element("readr", installed.packages()[, 1])) {
install.packages("readr", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
require("readr")
## textstem - Used to lemmatize words ----
if (!is.element("textstem", installed.packages()[, 1])) {
install.packages("textstem", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
require("textstem")
## hunspell - High-Performance Stemmer, Tokenizer, and Spell Checker ----
if (!is.element("hunspell", installed.packages()[, 1])) {
install.packages("hunspell", dependencies = TRUE,
repos = "https://cloud.r-project.org")
}
require("hunspell")
## 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")
# 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("#7b90d1", "#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(data, caption) {
kable(data, "html", escape = FALSE, caption = caption) %>%
kable_styling(bootstrap_options = c("striped", "condensed", "bordered"),
full_width = FALSE)
}
# STEP 3. Load the Dataset ----
student_performance_dataset <-
readr::read_csv(
"data/20230412-20230719-BI1-BBIT4-1-StudentPerformanceDataset.CSV", # nolint
col_types =
readr::cols(
class_group =
readr::col_factor(levels = c("A", "B", "C")),
gender = readr::col_factor(levels = c("1", "0")),
YOB = readr::col_date(format = "%Y"),
regret_choosing_bi =
readr::col_factor(levels = c("1", "0")),
drop_bi_now =
readr::col_factor(levels = c("1", "0")),
motivator =
readr::col_factor(levels = c("1", "0")),
read_content_before_lecture =
readr::col_factor(levels =
c("1", "2", "3", "4", "5")),
anticipate_test_questions =
readr::col_factor(levels =
c("1", "2", "3", "4", "5")),
answer_rhetorical_questions =
readr::col_factor(levels =
c("1", "2", "3", "4", "5")),
find_terms_I_do_not_know =
readr::col_factor(levels =
c("1", "2", "3", "4", "5")),
copy_new_terms_in_reading_notebook =
readr::col_factor(levels =
c("1", "2", "3", "4", "5")),
take_quizzes_and_use_results =
readr::col_factor(levels =
c("1", "2", "3", "4", "5")),
reorganise_course_outline =
readr::col_factor(levels =
c("1", "2", "3", "4", "5")),
write_down_important_points =
readr::col_factor(levels =
c("1", "2", "3", "4", "5")),
space_out_revision =
readr::col_factor(levels =
c("1", "2", "3", "4", "5")),
studying_in_study_group =
readr::col_factor(levels =
c("1", "2", "3", "4", "5")),
schedule_appointments =
readr::col_factor(levels =
c("1", "2", "3", "4", "5")),
goal_oriented =
readr::col_factor(levels =
c("1", "0")),
spaced_repetition =
readr::col_factor(levels =
c("1", "2", "3", "4")),
testing_and_active_recall =
readr::col_factor(levels =
c("1", "2", "3", "4")),
interleaving =
readr::col_factor(levels =
c("1", "2", "3", "4")),
categorizing =
readr::col_factor(levels =
c("1", "2", "3", "4")),
retrospective_timetable =
readr::col_factor(levels =
c("1", "2", "3", "4")),
cornell_notes =
readr::col_factor(levels =
c("1", "2", "3", "4")),
sq3r = readr::col_factor(levels =
c("1", "2", "3", "4")),
commute = readr::col_factor(levels =
c("1", "2",
"3", "4")),
study_time = readr::col_factor(levels =
c("1", "2",
"3", "4")),
repeats_since_Y1 = readr::col_integer(),
paid_tuition = readr::col_factor(levels =
c("0", "1")),
free_tuition = readr::col_factor(levels =
c("0", "1")),
extra_curricular = readr::col_factor(levels =
c("0", "1")),
sports_extra_curricular =
readr::col_factor(levels = c("0", "1")),
exercise_per_week = readr::col_factor(levels =
c("0", "1",
"2",
"3")),
meditate = readr::col_factor(levels =
c("0", "1",
"2", "3")),
pray = readr::col_factor(levels =
c("0", "1",
"2", "3")),
internet = readr::col_factor(levels =
c("0", "1")),
laptop = readr::col_factor(levels = c("0", "1")),
family_relationships =
readr::col_factor(levels =
c("1", "2", "3", "4", "5")),
friendships = readr::col_factor(levels =
c("1", "2", "3",
"4", "5")),
romantic_relationships =
readr::col_factor(levels =
c("0", "1", "2", "3", "4")),
spiritual_wellnes =
readr::col_factor(levels = c("1", "2", "3",
"4", "5")),
financial_wellness =
readr::col_factor(levels = c("1", "2", "3",
"4", "5")),
health = readr::col_factor(levels = c("1", "2",
"3", "4",
"5")),
day_out = readr::col_factor(levels = c("0", "1",
"2", "3")),
night_out = readr::col_factor(levels = c("0",
"1", "2",
"3")),
alcohol_or_narcotics =
readr::col_factor(levels = c("0", "1", "2", "3")),
mentor = readr::col_factor(levels = c("0", "1")),
mentor_meetings = readr::col_factor(levels =
c("0", "1",
"2", "3")),
`Attendance Waiver Granted: 1 = Yes, 0 = No` =
readr::col_factor(levels = c("0", "1")),
GRADE = readr::col_factor(levels =
c("A", "B", "C", "D",
"E"))),
locale = readr::locale())
View(student_performance_dataset)
# Dimensions
dim(student_performance_dataset)
# Data Types
sapply(student_performance_dataset, class)
glimpse(student_performance_dataset)
# Summary of each variable
summary(student_performance_dataset)
# STEP 4. Create a subset of the data using the "dplyr" package ----
## The "dplyr" Package ----
# We will also require the "dplyr" package
# "dplyr" is a grammar of *data manipulation*, providing a consistent set of
# verbs that help you solve the most common data manipulation challenges:
# mutate() adds new variables that are functions of existing variables
# select() picks variables based on their names.
# group_by() groups the data into categories
# filter() picks cases based on their values.
# summarise() reduces multiple values down to a single summary.
# arrange() changes the ordering of the rows.
# Documentation of "dplyr":
# https://cran.r-project.org/package=dplyr or
# https://github.com/tidyverse/dplyr
## The Pipe Operator in the "dplyr" Package ----
# In R, the %>% symbol represents the pipe operator.
# The pipe operator is used for chaining or piping operations together in a
# way that enhances the readability and maintainability of code. It is
# useful when working with data manipulation and data transformation tasks.
# The %>% operator takes the result of the expression on its left and passes it
# as the first argument to the function on its right. This allows you to chain
# together a sequence of operations on a dataset or object.
# For example:
# Example 1:
# library(dplyr) # Load the dplyr package (which uses %>%) # nolint
# result <- df %>%
# filter(age > 30) %>% # Filter rows where age is greater than 30
# group_by(gender) %>% # Group the data by gender
# summarise(mean_salary = mean(salary)) # Calculate the mean salary for each group # nolint
# # 'result' now contains the result of these operations
# Example 2:
# nhanes_dataset <- nhanes_dataset %>%
# mutate(MAP = BPDiaAve + (1 / 3) * (BPSysAve - BPDiaAve)) # nolint
evaluation_per_group_per_gender <- student_performance_dataset %>% # nolint
mutate(`Student's Gender` =
ifelse(gender == 1, "Male", "Female")) %>%
select(class_group,
`Student's Gender`, `Average Course Evaluation Rating`) %>%
filter(!is.na(`Average Course Evaluation Rating`)) %>%
group_by(class_group, `Student's Gender`) %>%
summarise(average_evaluation_rating =
mean(`Average Course Evaluation Rating`)) %>%
arrange(desc(average_evaluation_rating), .by_group = TRUE)
# Plain tabular output
View(evaluation_per_group_per_gender)
# Decorated tabular output
evaluation_per_group_per_gender %>%
rename(`Class Group` = class_group) %>%
rename(`Average Course Evaluation Rating` = average_evaluation_rating) %>%
select(`Class Group`, `Student's Gender`,
`Average Course Evaluation Rating`) %>%
mutate(`Average Course Evaluation Rating` =
color_tile("#B9BCC2", "#536CB5")
(`Average Course Evaluation Rating`)) %>%
kable_theme(caption = "Course Evaluation Rating per Group and per Gender")
# Decorated visual bar chart
evaluation_per_group_per_gender %>%
ggplot() +
geom_bar(aes(x = class_group, y = average_evaluation_rating,
fill = `Student's Gender`),
stat = "identity", position = "dodge") +
expand_limits(y = 0) +
blue_grey_theme() +
scale_fill_manual(values = blue_grey_colours_2) +
ggtitle("Course Evaluation Rating per Group and per Gender") +
labs(x = "Class Group", y = "Average Rating")
# STEP 5. Data Cleansing for Qualitative Data ----
## Contractions ----
# Contractions in the English language are shortened forms of words or phrases
# created by combining two words and replacing one or more letters with an
# apostrophe ('), often for the purpose of making speech or writing more
# concise and informal. Contractions are often used in informal speech and
# writing but are generally avoided in formal writing, such as academic papers
# or business reports.
# A function to expand contractions in an English-language source (assuming
# that the students did not respond in sheng or Kiswahili).
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)
}
# Evaluation likes and wishes
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. Write 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`)
# Before expanding contractions (See row number 4)
View(evaluation_likes_and_wishes)
evaluation_likes_and_wishes$Likes <- sapply(evaluation_likes_and_wishes$Likes, expand_contractions) # nolint
evaluation_likes_and_wishes$Wishes <- sapply(evaluation_likes_and_wishes$Wishes, expand_contractions) # nolint
# After expanding contractions
View(evaluation_likes_and_wishes)
## Special Characters and Lower Case ----
# NOTE: The special characters should be removed *after* expanding the
# contractions
# A function to remove special characters
# Remember the use of regular expressions in the
# BBT3104: Advanced Database Systems course
# A tutorial on regular expressions: https://regexone.com/
# To test your regular expression: https://regexr.com/
remove_special_characters <- function(doc) {
gsub("[^a-zA-Z ]", "", doc, ignore.case = TRUE)
}
# Before removing special characters (See row number 11)
View(evaluation_likes_and_wishes)
evaluation_likes_and_wishes$Likes <- sapply(evaluation_likes_and_wishes$Likes, remove_special_characters) # nolint
evaluation_likes_and_wishes$Wishes <- sapply(evaluation_likes_and_wishes$Wishes, remove_special_characters) # nolint
# Convert everything to lower case (to standardize the text)
evaluation_likes_and_wishes$Likes <- sapply(evaluation_likes_and_wishes$Likes, tolower) # nolint
evaluation_likes_and_wishes$Wishes <- sapply(evaluation_likes_and_wishes$Wishes, tolower) # nolint
# After removing special characters and converting everything to lower case
View(evaluation_likes_and_wishes)
# [OPTIONAL] You can save the file as a CSV at this point
write.csv(evaluation_likes_and_wishes,
file = "data/evaluation_likes_and_wishes.csv",
row.names = FALSE)
## Tokenization ----
# The goal of text mining is to discover relevant information that is possibly
# unknown or hidden. Natural Language Processing (NLP) is one methodology used
# in text mining. It attempts to decipher the ambiguities in written language
# by:
# (i) tokenization
# (ii) clustering
# (iii) extracting entity and word relationships
# (iv) using algorithms to identify themes and quantify subjective
# information.
# Tokenization is the process of breaking out text into smaller meaningful
# units called tokens.
# In addition to expanding (removing) contractions, removing special
# characters, converting all text to lower case, and stemming/lemmatization,
# tokenization can also be performed as part of data cleansing for qualitative
# data.
# Tokenization is a crucial step in NLP because it allows text data to be
# represented in a format that can be used for further analysis and machine
# learning tasks. It forms the basis for many text processing techniques and is
# essential for understanding and working with textual data in computational
# applications.
## Stopword Removal, Short Word Removal, and Censorship ----
# A stopword is a commonly used word that is usually filtered out during text
# mining to improve the efficiency and focus of text analysis.
# Stopwords are words that are considered to be of little value in many text
# analysis tasks because they are frequently used in the language and do not
# carry significant meaning on their own.
# Examples of stopwords in English include:
# "the," "and," "is," "in," "it," "of," "to," "for," and "with."
View(stop_words)
# Additional examples can be seen here:
head(sample(stop_words$word, 20), 20)
# You can also create a list of words that you would like to censor
undesirable_words <- c("wow", "lol", "none", "na")
evaluation_likes_filtered <- evaluation_likes_and_wishes %>% # nolint
# We start by tokenization (un-nesting words). This is from the variable
# "Like" into the variable "word".
unnest_tokens(word, Likes, token = "ngrams", n = 1) %>%
# Then we remove stopwords using an anti-join (remember this from the
# BBT3104: Advanced Database Systems course)
# Anti-join: do not join where the word is in the list of stopwords
anti_join(stop_words, by = c("word")) %>%
distinct() %>%
# Censor or filter out unwanted words
filter(!word %in% undesirable_words) %>%
# Include only words that are more than 3 characters long (assuming that
# these are the words that are meaningful)
filter(nchar(word) > 3) %>%
# We then rename the variable "word" for ease of use.
rename(`Likes (tokenized)` = word) %>%
# We focus only on the likes in this data frame
select(-Wishes)
View(evaluation_likes_filtered)
# Lastly, we save the created data frame as a CSV file:
write.csv(evaluation_likes_filtered,
file = "data/evaluation_likes_filtered.csv",
row.names = FALSE)
# The same is done to create a data frame for the "wishes" only
evaluation_wishes_filtered <- evaluation_likes_and_wishes %>% # nolint
unnest_tokens(word, Wishes, token = "ngrams", n = 1) %>%
anti_join(stop_words, by = c("word")) %>%
distinct() %>%
filter(!word %in% undesirable_words) %>%
filter(nchar(word) > 3) %>%
rename(`Wishes (tokenized)` = word) %>%
select(-Likes)
View(evaluation_wishes_filtered)
write.csv(evaluation_wishes_filtered,
file = "data/evaluation_wishes_filtered.csv",
row.names = FALSE)
## Stemming/Lemmatization ----
# Stemming is a text processing technique used to reduce words to their base or
# root form, known as the "stem."
# The goal of stemming is to simplify words to their common linguistic root,
# which can help improve text analysis and Information Retrieval by treating
# different inflections or variations of a word as the same word.
# Stemming groups together words with the same meaning but different
# grammatical forms. For example, stemming can convert words like "jumping,"
# "jumps," and "jumped" to the common stem "jump."
# [CAUTION] Stemming is a simple and heuristic-based approach and may not always
# produce accurate results. In some cases, it may produce stems that are not
# actual words or may result in ambiguity. For this reason, more advanced
# techniques like *lemmatization*, which considers the context and grammatical
# structure of words, are often preferred for certain Natural Language
# Processing (NLP) tasks.
# Summary:
# (i) Stemming: generally refers to removing suffixes from words to get the
# common origin
# (ii) Lemmatization: reducing inflected (or sometimes derived) words to their
# word stem, base or root form
# (iii) Word replacement: replace words with more frequently used synonyms
# Refer to the following guide:
# https://cran.r-project.org/web/packages/textstem/readme/README.html
### Correct Spelling Mistakes ----
# We can correct spelling mistakes before lemmatization as follows:
# Define a custom function to correct spelling
correct_spelling <- function(x) {
sapply(1:length(x), # nolint
function(y) {
bad <- hunspell(x[y])[[1]]
good <-
unlist(lapply(hunspell_suggest(bad),
`[[`, 1))
if (length(bad)) {
for (i in 1:length(bad)){ # nolint
x[y] <<- gsub(bad[i], good[i], x[y])
}
}
}
)
x
}
#### Likes ----
# Before spelling correction
# Take note of the following misspelt words (for the trigram):
# Line 40: "applicationsthe" instead of "applications the" # nolint
# Line 102: "intergration" instead of "integration" # nolint
# etc.
View(evaluation_likes_filtered)
corrected_spelling <-
evaluation_likes_filtered$`Likes (tokenized)` %>%
correct_spelling()
evaluation_likes_filtered$`Likes (tokenized)` <- corrected_spelling
# After spelling correction
View(evaluation_likes_filtered)
### Repeat the pre-processing for the correctly spelt words ----
# This is done for the sake of the words which were split into more than one
# word after correcting the spelling mistake.
# The repeated pre-processing includes:
# 1. Expanding Contractions
evaluation_likes_filtered$`Likes (tokenized)` <- sapply(evaluation_likes_filtered$`Likes (tokenized)`, expand_contractions) # nolint
# 2. Remove special Characters
evaluation_likes_filtered$`Likes (tokenized)` <- sapply(evaluation_likes_filtered$`Likes (tokenized)`, remove_special_characters) # nolint
# 3. Convert to Lower-Case for a standard form
evaluation_likes_filtered$`Likes (tokenized)` <- sapply(evaluation_likes_filtered$`Likes (tokenized)`, tolower) # nolint
# 4. Tokenization, stopword removal, short word removal, and censorship
evaluation_likes_filtered <- evaluation_likes_filtered %>% # nolint
unnest_tokens(word, `Likes (tokenized)`, token = "ngrams", n = 1) %>%
anti_join(stop_words, by = c("word")) %>%
distinct() %>%
filter(!word %in% undesirable_words) %>%
filter(nchar(word) > 3) %>%
rename(`Likes (tokenized)` = word)
write.csv(evaluation_likes_filtered,
file = "data/evaluation_likes_filtered.csv",
row.names = FALSE)
View(evaluation_likes_filtered)
#### Wishes ----
# Before spelling correction
# Take note of the following misspelt words (for the trigram):
# Line 40: "applicationsthe" instead of "applications the" # nolint
# Line 102: "intergration" instead of "integration" # nolint
# etc.
View(evaluation_wishes_filtered)
corrected_spelling <-
evaluation_wishes_filtered$`Wishes (tokenized)` %>%
correct_spelling()
evaluation_wishes_filtered$`Wishes (tokenized)` <- corrected_spelling
# After spelling correction
View(evaluation_wishes_filtered)
### Repeat the pre-processing for the correctly spelt words ----
# This is done for the sake of the words which were split into more than one
# word after correcting the spelling mistake.
# The repeated pre-processing includes:
# 1. Expanding Contractions
evaluation_wishes_filtered$`Wishes (tokenized)` <- sapply(evaluation_wishes_filtered$`Wishes (tokenized)`, expand_contractions) # nolint
# 2. Remove special Characters
evaluation_wishes_filtered$`Wishes (tokenized)` <- sapply(evaluation_wishes_filtered$`Wishes (tokenized)`, remove_special_characters) # nolint
# 3. Convert to Lower-Case for a standard form
evaluation_wishes_filtered$`Wishes (tokenized)` <- sapply(evaluation_wishes_filtered$`Wishes (tokenized)`, tolower) # nolint
# 4. Tokenization, stopword removal, short word removal, and censorship
evaluation_wishes_filtered <- evaluation_wishes_filtered %>% # nolint
unnest_tokens(word, `Wishes (tokenized)`, token = "ngrams", n = 1) %>%
anti_join(stop_words, by = c("word")) %>%
distinct() %>%
filter(!word %in% undesirable_words) %>%
filter(nchar(word) > 3) %>%
rename(`Wishes (tokenized)` = word)
write.csv(evaluation_wishes_filtered,
file = "data/evaluation_wishes_filtered.csv",
row.names = FALSE)
View(evaluation_wishes_filtered)
### We can now perform lemmatization on the correctly spelt words ----
# We need to first create a lemma lookup table. The lemmatize_strings()
# function will then use this lookup table to replace the words.
# Think of the lemma lookup table as a subset of an entire lemma dictionary.
# This makes it easier to search for a word in the smaller lookup table
# instead of searching for a word in the entire lemma dictionary.
# Lemma lookup tables specific to a project can be made by referring to
# a pre-existing lemma dictionary. The code below shows how the "Hunspell"
# lemma dictionary is used to create the lemma lookup table (subset of
# the dictionary).
# Lemma dictionaries include:
# 1. Hunspell: https://hunspell.github.io/ or
# https://cran.r-project.org/package=hunspell
# 2. koRpus: https://reaktanz.de/?c=hacking&s=koRpus or
# https://cran.r-project.org/package=koRpus
# 3. Michal Měchura (2016): https://www.lexiconista.com/
# etc.
lemma_dictionary_for_likes <-
make_lemma_dictionary(evaluation_likes_filtered$`Likes (tokenized)`,
engine = "hunspell")
evaluation_likes_filtered$`Likes (tokenized)` <-
evaluation_likes_filtered$`Likes (tokenized)` %>%
lemmatize_strings(dictionary = lemma_dictionary_for_likes)
View(evaluation_likes_filtered)
lemma_dictionary_for_wishes <-
make_lemma_dictionary(evaluation_wishes_filtered$`Wishes (tokenized)`,
engine = "hunspell")
evaluation_wishes_filtered$`Wishes (tokenized)` <-
evaluation_wishes_filtered$`Wishes (tokenized)` %>%
lemmatize_strings(dictionary = lemma_dictionary_for_wishes)
View(evaluation_wishes_filtered)
# STEP 6. Word Count ----
## Evaluation Likes ----
### Word count per gender ----
word_count_per_gender_likes <- evaluation_likes_filtered %>%
group_by(`Student's Gender`) %>%
summarise(num_words = n()) %>%
arrange(desc(num_words))
word_count_per_gender_likes %>%
mutate(num_words = color_bar("lightblue")(num_words)) %>%
rename(`Number of Words` = num_words) %>%
kable("html", escape = FALSE, align = "c",
caption = "Number of Significant Words in Evaluation Likes
per Gender: Minus contractions, special characters,
stopwords, short words, and censored words.") %>%
kable_styling(bootstrap_options =
c("striped", "condensed", "bordered"),
full_width = FALSE)
### Word count per group ----
word_count_per_group <- evaluation_likes_filtered %>%
group_by(`Class Group`) %>%
summarise(num_words = n()) %>%
arrange(desc(num_words))
word_count_per_group %>%
mutate(num_words = color_bar("lightblue")(num_words)) %>%
rename(`Number of Words` = num_words) %>%
kable("html", escape = FALSE, align = "c",
caption = "Number of Significant Words in Evaluation Likes
per Group: Minus contractions, special characters,
stopwords, short words, and censored words.") %>%
kable_styling(bootstrap_options =
c("striped", "condensed", "bordered"),
full_width = FALSE)
## Evaluation Wishes ----
### Word count per gender ----
word_count_per_gender_wishes <- evaluation_wishes_filtered %>%
group_by(`Student's Gender`) %>%
summarise(num_words = n()) %>%
arrange(desc(num_words))
word_count_per_gender_wishes %>%
mutate(num_words = color_bar("lightblue")(num_words)) %>%
rename(`Number of Words` = num_words) %>%
kable("html", escape = FALSE, align = "c",
caption = "Number of Significant Words in Evaluation Wishes
per Gender: Minus contractions, special characters,
stopwords, short words, and censored words.") %>%
kable_styling(bootstrap_options =
c("striped", "condensed", "bordered"),
full_width = FALSE)
### Word count per group ----
word_count_per_group_wishes <- evaluation_wishes_filtered %>%
group_by(`Class Group`) %>%
summarise(num_words = n()) %>%
arrange(desc(num_words))
word_count_per_group_wishes %>%
mutate(num_words = color_bar("lightblue")(num_words)) %>%
rename(`Number of Words` = num_words) %>%
kable("html", escape = FALSE, align = "c",
caption = "Number of Significant Words in Evaluation Wishes
per Group: Minus contractions, special characters,
stopwords, short words, and censored words.") %>%
kable_styling(bootstrap_options =
c("striped", "condensed", "bordered"),
full_width = FALSE)
# STEP 7. Top Words ----
## Evaluation Likes ----
### Top 10 words for female students ----
evaluation_likes_filtered %>%
select(`Class Group`, `Student's Gender`,
`Average Course Evaluation Rating`, `Likes (tokenized)`) %>%
filter(`Student's Gender` == "Female") %>%
count(`Likes (tokenized)`, sort = TRUE) %>%
top_n(9) %>%
mutate(`Likes (tokenized)` = reorder(`Likes (tokenized)`, n)) %>%
ggplot() +
geom_col(aes(`Likes (tokenized)`, n), fill = blue_grey_colours_1) +
blue_grey_theme() +
xlab("Word in Course Evaluation") +
ylab("Number of Times Used (Term Frequency)") +
ggtitle("Most Frequently Used Words in Course Evaluation Likes for Female
Students") +
coord_flip()
### Top 10 words for male students ----
evaluation_likes_filtered %>%