-
Notifications
You must be signed in to change notification settings - Fork 0
/
Text_Mining.Rmd
2857 lines (2271 loc) · 108 KB
/
Text_Mining.Rmd
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
---
title: "Text Mining"
output: html_document
date: '2022-12-03'
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Part A:
In this section, we will be performing the bag of words analysis. After relevant analysis, the results will enable us to find the important words by ratings. The word analysis will be done in different n-gram levels (unigram, bigram and trigram).
Upon finding out the important words, we will visualize them in bar plots and wordclouds.
Finally, we will also perform some analysis to connect word importance with different components of the available metadata.
For this dataset, we will perform each step on the review level as well as on the company level.
* Loading the relevant libraries
```{r}
knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE, fig.align = "center")
library(ggplot2)
library(tidyverse)
library(dplyr)
library(tidytext)
library(jsonlite)
library(tidyr)
library(readr)
library(topicmodels)
library(geojsonR)
library(stringr)
library(dplyr)
library(tidyr)
library(stm)
library(udpipe)
library(cld2)
library(wordcloud)
library(xml2)
library(rvest)
library(janeaustenr)
library(data.table)
library(rjson)
library(lubridate)
library(textcat)
library(rJava)
library(qdap)
library(magrittr)
library(jsonlite)
library(topicmodels)
library(geojsonR)
library(hunspell)
library(ggrepel)
library(gridExtra)
library(widyr)
library(igraph)
library(textstem)
library(ggraph)
library(stringr)
library(future)
library(future.apply)
library(influential)
library(stringi)
library(tm)
```
# Data Preparation
## Ingest
We will now perform scraping with rvest to retrieve information from Trustpilot webpage.
```{r eval=FALSE}
#Creating a dataset to store all the scraped data
rm(store_reviews)
store_reviews <- data.frame()
#Defining functions to repeatedly perform specific crawling
get_description = function(store_links) {
store_page = read_html(store_links)
description = store_page %>% html_nodes("div.card_cardContent__sFUOe") %>% html_node("div.styles_container__9nZxD") %>% html_text() %>% .[c(1,2,3)] %>% paste0(collapse = " ")
return(description)
}
get_email = function(store_links) {
store_page = read_html(store_links)
email = store_page %>% html_nodes("div.card_cardContent__sFUOe") %>% html_node(".styles_contactInfoElement__SxlS3:nth-child(1) .styles_contactInfoLink__gMJWX") %>% html_text() %>% .[c(1,2,3)] %>% paste0(collapse = " ")
return(email)
}
get_phone = function(store_links) {
store_page = read_html(store_links)
phone = store_page %>% html_nodes("div.card_cardContent__sFUOe") %>% html_node(".styles_contactInfoElement__SxlS3+ .styles_contactInfoElement__SxlS3 .styles_contactInfoLink__gMJWX") %>% html_text() %>% .[c(1,2,3)] %>% paste0(collapse = " ")
return(phone)
}
get_address = function(store_links) {
store_page = read_html(store_links)
address = store_page %>% html_nodes("div.card_cardContent__sFUOe") %>% html_node("ul.typography_typography__QgicV") %>% html_text() %>% .[c(1,2,3)] %>% paste0(collapse = " ")
return(address)
}
#Looping through multiple pages and subpages and retrieving data into the desired dataset
for (page_result in seq(from = 1, to = 750, by = 15)) {
rm(sub_contents)
sub_contents <- data.frame()
link = paste0("https://www.trustpilot.com/categories/travel_agency?page=", page_result)
page = read_html(link)
name = page %>% html_nodes("div.styles_content__3mwYr") %>% html_node(".styles_displayName__1LIcI") %>% html_text()
overall = page %>% html_nodes("div.styles_rating__2FRLX") %>% html_nodes("span.styles_mobile__17MXv") %>% html_text()
category = page %>% html_nodes("div.card_cardContent__3Idve") %>% html_node("div.styles_wrapper__nFO8_") %>% html_text() %>% sub("·.*", "", .)
Sys.sleep(1)
total_reviews = page %>% html_nodes("div.styles_rating__2FRLX") %>% html_node("p.typography_typography__23IQz") %>% html_text()
store_links <- page %>%
html_nodes("div.paper_paper__29o4A") %>%
html_node(".styles_linkWrapper__3x9X7") %>%
html_attr("href") %>%
paste0("https://uk.trustpilot.com",.)
store_description = sapply(store_links, FUN = get_description, USE.NAMES = F)
Sys.sleep(2)
phone_number = sapply(store_links, FUN = get_phone, USE.NAMES = F)
email = sapply(store_links, FUN = get_email, USE.NAMES = F)
Sys.sleep(2)
store_address = sapply(store_links, FUN = get_address, USE.NAMES = F)
for (i in store_links) {
rm(sub_contents_catch)
sub_contents_catch <- data.frame()
for (subpage_result in seq(from = 1, to = 3, by = 1)) {
sub_links = paste0(i, "?page=", subpage_result)
sub_page = read_html(sub_links)
reviewer = sub_page %>% html_nodes("div.styles_consumerDetailsWrapper__p2wdr") %>%
html_node("div.typography_typography__QgicV") %>%
html_text(trim = TRUE) %>% paste0(collapse = "//")
Sys.sleep(1)
review_summary = sub_page %>% html_nodes("div.styles_reviewContent__0Q2Tg") %>%
html_node("a.link_internal__7XN06") %>%
html_text(trim = TRUE) %>% paste0(collapse = "//")
Sys.sleep(2)
review = sub_page %>% html_nodes("div.styles_reviewContent__0Q2Tg") %>% html_node("p.typography_typography__QgicV") %>% html_text() %>%
paste0(collapse = "//")
Sys.sleep(2)
date = sub_page %>% html_nodes("div.styles_reviewHeader__iU9Px") %>%
html_node("div.typography_typography__QgicV time") %>%
html_attr("datetime") %>% str_sub(.,1, 10) %>% paste0(collapse = "//")
country = sub_page %>% html_elements(xpath = "//div[contains(@class, 'styles_consumerDetailsWrapper__p2wdr')]") %>%
html_elements(xpath = ".//div[contains(@class, 'styles_consumerExtraDetails__fxS4S')]") %>%
html_node(".styles_detailsIcon__Fo_ua+ .styles_detailsIcon__Fo_ua") %>%
html_text(trim = TRUE) %>% paste0(collapse = "//")
Sys.sleep(2)
reviewer_rating = sub_page %>% html_nodes("div.styles_reviewHeader__iU9Px") %>%
html_node("div.star-rating_starRating__4rrcf img") %>% html_attr("alt") %>% paste0(collapse = "//")
sub_contents_catch = rbind(sub_contents_catch, data.frame(reviewer, review_summary, review, date, country, reviewer_rating))
ifelse(subpage_result == 5, t(sub_contents_catch) %>% as.data.frame() %>% unite(col = "1", sep = "//") %>% t(.) -> sub_contents_catch, print(paste("Sub_Page", subpage_result)))
}
sub_contents = rbind(sub_contents, sub_contents_catch)
}
store_reviews <- rbind(store_reviews,
data.frame(name, overall, category, store_description, phone_number, email, store_address, sub_contents, stringsAsFactors = FALSE))
print(paste("Page:", page_result))
}
#saveRDS(store_reviews, "store_reviews_final.rds)
```
* Transforming the scraped data
Now that the raw data is taken, we will perform some steps to convert it into analysable form.
```{r eval=FALSE}
#Reading the saved file
dataset <- readRDS("store_reviews_finals.rds")
dataset <- distinct(dataset)
#Correcting an anomaly
dataset$review[400] <- str_replace(dataset$review[400], "https://earnapp", "https:earnapp")
dataset$review[68] <- str_replace(dataset$review[68], " // ", "")
dataset$review[609] <- str_replace(dataset$review[609], " //M", "M")
dataset$review[862] <- str_replace(dataset$review[862], "on 2//7/09-as", "on 2/7/09-as")
dataset$review[902] <- str_replace(dataset$review[902], "https:// t.me", "https: t.me")
dataset$review[930] <- str_replace(dataset$review[930], "\\\\WHY///", "WHY")
#Separating the individual reviews
dataset <- dataset %>% separate_rows(7:12, sep = "//")
#Removing duplicates
dataset <- distinct(dataset)
dataset <- na.omit(dataset)
dataset <- dataset %>% filter(reviewer_rating != "")
#Saving the final dataset
#saveRDS(dataset, "raw_data_final.rds")
```
* Cleaning the variables
For the benefit of analysis, we will perform some cleaning to normalize the dataset. We utilized some techniques while scraping to ensure the row numbers match. We will now remove those unnecessary characters.
```{r}
review_data <- readRDS("raw_data_final.rds")
#Removing unwanted characters
review_data$store_description <- review_data$store_description %>% str_replace_all("NA", "")
review_data$email <- review_data$email %>% str_replace_all("NA", "")
review_data$store_address <- review_data$store_address %>% str_replace_all("NA", "")
review_data$phone_number <- review_data$phone_number %>% str_replace_all("NA", "")
review_data$reviewer_rating <- review_data$reviewer_rating %>% str_sub(start = 6, end = 8)
#Fixing the datatypes
review_data <- review_data %>% separate(date, into = c("year", "month", "day"), sep = "-")
review_data <- review_data %>% mutate(year = as.numeric(year),
month = as.numeric(month),
day = as.numeric(day))
review_data <- review_data %>% mutate(date = make_date(year, month, day))
review_data$date <- as.Date(review_data$date, format = "%Y %b,%d")
#Formatting the target variable
review_data$overall <- as.numeric(review_data$overall)
review_data$overall <- round(review_data$overall)
review_data$reviewer_rating <- as.numeric(review_data$reviewer_rating)
review_data <- review_data %>% arrange(desc(date))
```
The dataset is now ready for text analysis
## Prepare
We will now perform some modificatios on the reviews to bring it into a better format to analyse
```{r}
#Remove companies with less than 5 reviews
remove_names <- review_data %>%
group_by(name) %>%
summarise(total = n()) %>%
filter(total <= 5) %>% pull(name)
review_data <- review_data %>%
filter(!(name %in% remove_names))
#Assign unique keys to the stores
name_id <- review_data %>% distinct(name)
name_id$company_id <- 1:nrow(name_id)
review_data <- name_id %>%
inner_join(review_data)
#Create a new key to track each review
review_data$review_id <- 1:nrow(review_data)
#Create new object with only the full review text and the review_id
reviews<- review_data %>%
dplyr::select(review_id, review_summary, review, reviewer_rating)
reviews <- reviews %>%
mutate(reviewText =
paste(
coalesce(review_data$review_summary, ""),
coalesce(review_data$review, "")
)
) %>%
dplyr::select(-(review_summary:review))
review_data <- review_data %>% left_join(reviews)
```
* Cleaning the reviews
We will perform some basic text cleaning functions, which can be utilized throughout all the parts of this project.
```{r}
#Replacing the digits with empty space
review_data$reviewText <- gsub('[[:digit:]]+',' ', review_data$reviewText)
#Replacing the punctuations with empty space
review_data$reviewText <- gsub('[[:punct:]]+',' ', review_data$reviewText)
#Additional cleaning
review_data$reviewText <- bracketX(review_data$reviewText)
review_data$reviewText <- replace_contraction(review_data$reviewText)
review_data$reviewText <- replace_symbol(review_data$reviewText)
# Remove spaces and newlines
review_data$reviewText <- gsub("\n", " ", review_data$reviewText)
review_data$reviewText <- gsub("^\\s+", "", review_data$reviewText)
review_data$reviewText <- gsub("\\s+$", "", review_data$reviewText)
review_data$reviewText <- gsub("[ |\t]+", " ", review_data$reviewText) #spaces
#Getting the character lengths
review_data$char_length <- nchar(review_data$reviewText)
#Plotting the lengths
hist(review_data$char_length, breaks = 300, main = "Review Lengths")
#Filtering for minimum length of 100
review_data <- review_data %>% filter(char_length>100)
hist(review_data$char_length,breaks = 300,main = "Review Length -Left trim to 100")
#Filtering for maximum length of 1400
review_data <- review_data %>% filter(char_length<1400)
hist(review_data$char_length,breaks = 300,main = "Review Length(All) -Right trim to 1000")
#Cleaning the language of the reviews
review_data$reviewText <- iconv(review_data$reviewText)
review_data$language <- cld2::detect_language(review_data$reviewText)
review_data %>% filter(language =="en") -> review_data_en
```
* Cleaning the store descriptions
```{r}
#Replacing the digits with empty space
review_data_en$store_description <- gsub('[[:digit:]]+',' ', review_data_en$store_description)
#Replacing the punctuations with empty space
review_data_en$store_description <- gsub('[[:punct:]]+',' ', review_data_en$store_description)
#Additional cleaning
review_data_en$store_description <- bracketX(review_data_en$store_description)
review_data_en$store_description <- replace_contraction(review_data_en$store_description)
review_data_en$store_description <- replace_symbol(review_data_en$store_description)
# Remove spaces and newlines
review_data_en$store_description <- gsub("\n", " ", review_data_en$store_description)
review_data_en$store_description <- gsub("^\\s+", "", review_data_en$store_description)
review_data_en$store_description <- gsub("\\s+$", "", review_data_en$store_description)
review_data_en$store_description <- gsub("[ |\t]+", " ", review_data_en$store_description) #spaces
#Lemmatizing
lemma <- review_data_en %>% dplyr::select(company_id, store_description) %>% distinct(.)
lemma <- lemma %>% unnest_tokens(word, store_description)
lemma$word <- lemmatize_words(lemma$word)
lemma <- lemma %>% group_by(company_id) %>% summarise(store_description = paste(word, collapse = " "))
review_data_en$store_description <- NULL
review_data_en <- review_data_en %>% left_join(lemma)
#Cleaning the language
review_data_en$store_description <- iconv(review_data_en$store_description)
```
* Checking mistakes in reviews
We will use the 'hunspell' dictionary spelling suggestion to deal will the spelling mistakes identified in the reviews. Then, using judgement, we will manually fix the mistakes
```{r}
#Getting the reviews column
reviews <- review_data_en %>% arrange(review_id) %>% dplyr::select(review_id,reviewText)
#Tokenizing the reviews
tokens_for_spellcheck <- unnest_tokens(reviews,word,reviewText)
#Getting the unique words
unique_words <- unique(tokens_for_spellcheck$word)
head(unique_words)
length(unique_words)
#Finding the misspelled words
mispells <- hunspell(unique_words)
#Getting the unique spelling mistake
mispells <- unique(unlist(mispells))
length(mispells)
#Getting correct word suggestions
suggestive_words <- hunspell_suggest(mispells)
suggestive_words <- unlist(lapply(suggestive_words, function(x) x[1]))
head(suggestive_words)
mistakes.list <- as.data.frame(cbind(mispells,suggestive_words))
freq_mistake <- count(tokens_for_spellcheck,word)
freq_mistake <- inner_join(freq_mistake, mistakes.list, by = c("word" = "mispells"))
words_suggestion<-arrange(freq_mistake,desc(n))
word_NA <- words_suggestion %>% filter(is.na(suggestive_words))
#Manually dealing with the spelling suggestions
#write.csv(words_suggestion,"words_suggestion.csv")
#write.csv(word_NA,"word_NA.csv")
#Reading the prepared data
words_suggestion <- read.csv("words_suggestion.csv")
words_suggestion <- words_suggestion %>% dplyr::select(-X) %>% na.omit()
word_NA <- read.csv("word_NA.csv")
word_NA <- word_NA %>% dplyr::select(-X) %>% na.omit()
words_suggestions <- rbind(words_suggestion,word_NA)
words_suggestions <- arrange(words_suggestions)
sum(is.na(words_suggestions))
#Saving the final data
#write.csv(words_suggestions, "words_suggestions.csv")
#Replacing the mistakes words with suggestive ones
word.list <- read.csv("words_suggestions.csv", stringsAsFactors = FALSE)
mistake.words <- paste0(" ", word.list$word, " ")
correct.words <- paste0(" ", word.list$suggestive_words, " ")
mistake.replace <- function(df) {
df$reviewText <- stri_replace_all_regex(df$reviewText, mistake.words, correct.words, vectorize_all = FALSE)
return(df)
}
#Defining the number of cores
ncores <- 6L
plan(multiprocess, workers = ncores)
# split comments based on available cores
corpus_splitted <- split(reviews, seq(1, nrow(reviews), by=5))
reviews <- future_lapply(corpus_splitted, mistake.replace)
reviews <- rbindlist(reviews)
reviews <- as.data.frame(reviews)
reviews <- reviews %>% arrange(review_id)
#Creating a backup of the correct reviews
#saveRDS(reviews, "spell_mistake_correction.rds")
#Replacing the reviews with the corrected reviews
review_data_en$reviewText <- reviews$reviewText
#Creating a backup
#saveRDS(review_data_en, "review_data_en.rds")
```
* Tokenizing the reviews for stores
```{r}
#Grouping the reviews by stores
review_data_by_stores <- review_data_en %>%
unnest_tokens(word,reviewText)%>%
group_by(company_id) %>%
summarise(grouped_reviews = paste(word,collapse = " "))
#saveRDS(review_data_by_stores, "review_data_by_stores.rds")
#Splitting the dataset
split_size <- 100
tokens_list <- split(review_data_by_stores,
rep(1:ceiling(nrow(review_data_by_stores)/split_size),
each=split_size,
length.out=nrow(review_data_by_stores)))
# Tokenization
review_tokens_by_stores <- data.frame()
for(i in 1:length(tokens_list)){
review_tokens_k <- tokens_list[[i]] %>%
unnest_tokens(word,grouped_reviews) %>%
count(word,company_id) %>%
anti_join(stop_words)
print(i)
review_tokens_by_stores <- bind_rows(review_tokens_by_stores,review_tokens_k)
}
#Lemmatizing the tokens
review_tokens_by_stores$word <- lemmatize_words(review_tokens_by_stores$word)
```
* Filtering the tokens
We will try to even trim the reviews by looking at the word lengths.
```{r}
#Finding the token lengths
review_tokens_by_stores$token_length <- nchar(review_tokens_by_stores$word)
#Checking the distribution of the lengths
view(review_tokens_by_stores %>% group_by(token_length) %>% summarise(total =n()))
#Removing the short tokens
review_tokens_by_stores <- review_tokens_by_stores %>% filter(token_length > 2)
#Checking the longest tokens
view(review_tokens_by_stores %>% group_by(token_length) %>% summarise(total =n()) %>% arrange(desc(token_length)))
#Removing excessively long tokens
review_tokens_by_stores <- review_tokens_by_stores %>% filter(token_length<=16)
#Creating backups
#saveRDS(review_data_by_stores, "review_data_by_stores.rds")
#Getting the frequency of each token
review_tokens_by_stores <- review_tokens_by_stores %>% count(company_id, word, sort = TRUE)
get_overall <- review_data_en %>% dplyr::select(., c(2,3)) %>% distinct(company_id, overall)
review_tokens_by_stores <- review_tokens_by_stores %>% left_join(get_overall)
total_words <- review_tokens_by_stores %>%
group_by(word) %>%
summarize(total = sum(n))
review_tokens_by_stores <- review_tokens_by_stores %>% left_join(total_words)
#Calculating tf_idf of the tokens
review_tf_idf_by_stores <- review_tokens_by_stores %>% count(company_id, word) %>%
bind_tf_idf(word,company_id,n) %>% group_by(word) %>% arrange(desc(tf-idf))
#Checking the tf-idf distribution
hist(review_tf_idf_by_stores$tf_idf,breaks = 200,main="TF-IDF plot")
#Taking the cut-off value from histogram
review_tf_idf_by_stores <- review_tf_idf_by_stores %>%
filter(tf_idf < 0.1)
hist(review_tf_idf_by_stores$tf_idf,breaks = 400,main="TF-IDF plot")
review_tf_idf_by_stores <- review_tf_idf_by_stores %>%
filter(tf_idf<0.05)
hist(review_tf_idf_by_stores$tf_idf,breaks = 400,main="TF-IDF plot")
review_tf_idf_by_stores <- review_tf_idf_by_stores %>%
filter(tf_idf>0.002)
hist(review_tf_idf_by_stores$tf_idf,breaks = 400,main="TF-IDF plot")
review_tf_idf_by_stores %>% group_by(word) %>%
summarise(total =n()) %>%
arrange(desc(total)) %>%
top_n(50)
```
* Visualizing wordclouds by ratings
```{r}
custom_words <- c("class", "please", "job", "shop", "hand", "friend", "date", "service", "review", "product", "customer", "day", "days", "received", "money", "week", "buy", "company", "phone", "don", "ve", "ofcom", "ninja", "moonfruit", "cancelled", "virgin", "told", "people", "arrived", "paul", "av", "ben", "josh", "andy", "tom", "richer", "plugin", "amp", "hifi", "aquiss", "sounds", "controller", "zoltan", "ian", "idnet", "glue", "proxy", "helen", "eno", "oled", "sypwai", "george", "peter", "panamoz", "pine", "dotsquares", "laura", "vape", "amiga", "biz", "technoworld", "proxies", "star", "hesit", "futur", "easi", "instal", "satisfi", "effici", "solv", "refus", "disgrac", "competit", "ensur", "refus", "incr", "wix", "sb", "laskys", "responsiv", "wayv", "dab", "novads", "harvey")
tibble(word = custom_words,lexicon = rep("custom",length(custom_words))) %>% bind_rows(stop_words) -> custom_stopwords
```
```{r}
review_5 <- review_tokens_by_stores %>%
anti_join(custom_stopwords) %>%
filter(overall == 5) %>%
group_by(word) %>%
summarise(total = mean(total)) %>%
arrange(desc(total))
wordcloud(review_5$word, review_5$total, max.words = 25,
colors = c("gold3", "blue4", "darkgoldenrod4"))
```
Word Cloud for 5 star reviews
```{r}
review_4 <- review_tokens_by_stores %>%
anti_join(custom_stopwords) %>%
filter(overall == 4) %>%
group_by(word) %>%
anti_join(custom_stopwords) %>%
summarise(total = mean(total)) %>%
arrange(desc(total))
wordcloud(review_4$word, review_4$total, max.words = 25,
colors = c("gold3", "blue4", "darkgoldenrod4"))
```
Word Cloud for 4 star reviews
```{r}
review_3 <- review_tokens_by_stores %>%
anti_join(custom_stopwords) %>%
filter(overall == 3) %>%
group_by(word) %>%
anti_join(custom_stopwords) %>%
summarise(total = mean(total)) %>%
arrange(desc(total))
wordcloud(review_3$word, review_3$total, max.words = 25,
colors = c("gold3", "blue4", "darkgoldenrod4"))
```
Word Cloud for 3 star reviews
```{r}
review_2 <- review_tokens_by_stores %>%
anti_join(custom_stopwords) %>%
filter(overall == 2) %>%
group_by(word) %>%
anti_join(custom_stopwords) %>%
summarise(total = mean(total)) %>%
arrange(desc(total))
wordcloud(review_2$word, review_2$total, max.words = 25,
colors = c("gold3", "blue4", "darkgoldenrod4"))
```
Word Cloud for 2 star reviews
```{r}
review_1 <- review_tokens_by_stores %>%
anti_join(custom_stopwords) %>%
filter(overall == 1) %>%
group_by(word) %>%
anti_join(custom_stopwords) %>%
summarise(total = mean(total)) %>%
arrange(desc(total))
wordcloud(review_1$word, review_1$total, max.words = 25,
colors = c("gold3", "blue4", "darkgoldenrod4"))
```
Word Cloud for 1 star reviews
* Checking the wordcloud for dominant words across low and high ratings
```{r}
#Ratings of 4 and above are considered as high ratings
positive_reviews <- review_tokens_by_stores %>% anti_join(custom_stopwords) %>%
filter (overall == 4| overall == 5)
positive_reviews <- positive_reviews %>% dplyr::select(word)
#Ratings of 2 and below are considered as low ratings
negative_reviews <- review_tokens_by_stores %>% anti_join(custom_stopwords) %>%
filter (overall == 2| overall ==1 )
negative_reviews <- negative_reviews %>% dplyr::select(word)
combine_review <- c(positive_reviews,negative_reviews)
#Creating a corpus
corpus_combine = VCorpus(VectorSource(combine_review))
#Stemming the document
corpus_combine=tm_map(corpus_combine, stemDocument)
review_dtm_combine <- TermDocumentMatrix(corpus_combine)
all=as.matrix(review_dtm_combine)
colnames(all)=c("Words in high ratings","Words in low ratings")
#Creating comparison cloud
comparison.cloud(all,
colors = c("red", "blue"),
max.words = 100)
```
# Analyse
## Dealing with n-grams
Now, using the bag of words approach, we will get the top n-grams for both reviews and store descriptions.
* Unigrams of reviews
```{r}
#Bringing the data for using in n-grams
df <- review_data_en %>% dplyr::select(company_id, store_description, overall) %>% left_join(review_data_by_stores) %>% distinct(.)
#Tokenizing into unigrams
ngram_1_review <- df %>%
unnest_tokens(word, grouped_reviews, token = "ngrams", n =1) %>%
anti_join(custom_stopwords)
#Finding the most frequent unigrams
ngram_1_review <- ngram_1_review %>%
group_by(word) %>%
summarise(Frequency = n(),
Overall = round(mean(overall))) %>%
arrange(desc(Frequency))
#Visualizing the top frequent unigrams
df %>% unnest_tokens(word, grouped_reviews, token = "ngrams", n =1) %>%
anti_join(custom_stopwords) %>%
count(word, sort = TRUE) %>%
top_n(10) %>%
ggplot(aes(reorder(word, n), n)) +
geom_col() +
labs(title="Top 10 Unigram frequency for Reviews",
y = "Frequency",
x = "Terms") +
theme(plot.title = element_text(hjust = 0.5)) +
coord_flip()
#Visualizing the top frequent unigrams by ratings
ngram_1_review %>% group_by(Overall) %>%
slice_max(Frequency, n = 10) %>%
ungroup() %>%
ggplot(aes(Frequency, fct_reorder(word, Frequency), fill = Overall)) +
geom_col(show.legend = FALSE) +
facet_wrap(~ Overall, ncol = 2, scales = "free") +
labs(title="Top 10 Unigram frequency for Reviews by Overall",
y = "Average Rating",
x = "Frequency") +
theme(plot.title = element_text(hjust = 0.5))
```
* Bigrams of reviews
```{r}
#Adding stop words specifically for bigrams
bi_custom_words <- c("class", "please", "job", "shop", "hand", "friend", "date", "service", "review", "product", "customer", "day", "days", "received", "money", "week", "buy", "company", "phone", "don", "ve", "ofcom", "ninja", "moonfruit", "cancelled", "virgin", "told", "people", "arrived", "paul", "av", "ben", "josh", "andy", "tom", "richer", "plugin", "amp", "hifi", "aquiss", "sounds", "controller", "zoltan", "ian", "idnet", "glue", "proxy", "helen", "eno", "oled", "sypwai", "george", "peter", "panamoz", "pine", "dotsquares", "laura", "vape", "amiga", "biz", "technoworld", "proxies", "recommend", "fast", "machine", "avoid", "fridge", "freezer", "sb", "trust", "pilot", "pc")
tibble(word = bi_custom_words,lexicon = rep("custom",length(bi_custom_words))) %>% bind_rows(stop_words) -> bi_custom_stopwords
#Bringing the data
ngram_2_review <- df %>%
unnest_tokens(word, grouped_reviews, token = "ngrams", n =2)
#Tokenizing for bigrams
ngram_2_review$index <- seq.int(nrow(ngram_2_review))
df2 <- ngram_2_review %>%
separate(word, c("word1", "word2"), sep = " ") %>%
dplyr::select('index', 'word1','word2')
ngram_2_review <- left_join(ngram_2_review, df2, by = "index")
rm(df2)
ngram_2_review <- ngram_2_review %>%
filter(!word1 %in% bi_custom_stopwords$word) %>%
filter(!word2 %in% bi_custom_stopwords$word)
ngram_2_review_splitted <- ngram_2_review %>%
count(word1, word2, sort = TRUE)
#Finding the frequencies of the bigrams
ngram_2_review_combined <- ngram_2_review %>%
group_by(word) %>%
summarise(Frequency = n(),
Overall = round(mean(overall))) %>%
arrange(desc(Frequency)) %>%
na.omit()
#Visualizing the top frequent bigrams
ngram_2_review_combined %>% slice_max(Frequency, n = 8) %>%
ggplot(aes(reorder(word, Frequency), Frequency)) +
geom_col() +
labs(title="Top 10 Bigram Frequency for Reviews",
y = "Frequency",
x = "Terms") +
theme(plot.title = element_text(hjust = 0.5)) +
coord_flip()
#Visualizing the top frequent bigrams by ratings
ngram_2_review_combined %>% group_by(Overall) %>%
slice_max(Frequency, n = 8) %>%
ungroup() %>%
ggplot(aes(Frequency, fct_reorder(word, Frequency), fill = Overall)) +
geom_col(show.legend = FALSE) +
facet_wrap(~ Overall, ncol = 2, scales = "free") +
labs(title="Top 10 Bigram frequency for Reviews by Overall",
y = "Terms",
x = "Frequency") +
theme(plot.title = element_text(hjust = 0.5))
#Common bigrams in reviews
ngram_2_graph <- ngram_2_review_splitted %>%
filter(n > 60) %>%
graph_from_data_frame()
set.seed(321)
a <- grid::arrow(type = "closed", length = unit(.15, "inches"))
ggraph(ngram_2_graph, layout = "fr") +
geom_edge_link(aes(edge_alpha = n), show.legend = FALSE,
arrow = a, end_cap = circle(.07, 'inches')) +
geom_node_point(color = "lightblue", size = 3) +
geom_node_text(aes(label = name), vjust = 1, hjust = 1) +
theme_void()
```
* Trigrams of reviews
```{r}
#Adding stop words specifically for bigrams
tri_custom_words <- c("class", "please", "job", "service", "shop", "hand", "friend", "date", "review", "product", "customer", "day", "days", "money", "week", "buy", "company", "phone", "don", "ve", "ofcom", "ninja", "moonfruit", "virgin", "told", "people", "arrived", "paul", "av", "ben", "josh", "andy", "tom", "richer", "plugin", "amp", "hifi", "aquiss", "sounds", "zoltan", "ian", "idnet", "glue", "proxy", "helen", "eno", "oled", "sypwai", "george", "peter", "panamoz", "pine", "dotsquares", "laura", "vape", "amiga", "biz", "technoworld", "fridge", "freezer", "iphone", "pro", "trust", "pilot", "st", "uber", "reviews", "boots", "sh", "london", "british", "xl", "ms", "avern", "pm", "june", "bullguard")
tibble(word = tri_custom_words,lexicon = rep("custom",length(tri_custom_words))) %>% bind_rows(stop_words) -> tri_custom_stopwords
#Bringing the data
ngram_3_review <- df %>%
unnest_tokens(word, grouped_reviews, token = "ngrams", n =3)
#Tokenizing into trigrams
ngram_3_review$index <- seq.int(nrow(ngram_3_review))
df3 <- ngram_3_review %>%
separate(word, c("word1", "word2", "word3"), sep = " ") %>%
dplyr::select('index', 'word1','word2', 'word3')
ngram_3_review <- left_join(ngram_3_review, df3, by = "index")
rm(df3)
ngram_3_review <- ngram_3_review %>%
filter(!word1 %in% tri_custom_stopwords$word) %>%
filter(!word2 %in% tri_custom_stopwords$word) %>%
filter(!word3 %in% tri_custom_stopwords$word)
ngram_3_review_splitted <- ngram_3_review %>%
count(word1, word2, word3, sort = TRUE)
#Finding the frequencies
ngram_3_review <- ngram_3_review %>%
group_by(word) %>%
summarise(Frequency = n(),
Overall = round(mean(overall))) %>%
arrange(desc(Frequency)) %>%
na.omit()
#Visualizing the top frequent trigrams
ngram_3_review %>% slice_max(Frequency, n = 10) %>%
ggplot(aes(reorder(word, Frequency), Frequency)) +
geom_col() +
labs(title="Top 10 Trigram Frequency for Reviews",
y = "Frequency",
x = "Terms") +
theme(plot.title = element_text(hjust = 0.5)) +
coord_flip()
#Visualizing the top frequent trigrams by ratings
ngram_3_review %>% group_by(Overall) %>%
slice_max(Frequency, n = 7) %>%
ungroup() %>%
ggplot(aes(Frequency, fct_reorder(word, Frequency), fill = Overall)) +
geom_col(show.legend = FALSE) +
facet_wrap(~ Overall, ncol = 2, scales = "free") +
labs(title="Top 10 Trigram frequency for Reviews by Overall",
y = "Terms",
x = "Frequency") +
theme(plot.title = element_text(hjust = 0.5))
#Common bigrams in reviews
ngram_3_graph <- ngram_3_review_splitted %>%
filter(n > 6) %>%
graph_from_data_frame()
set.seed(321)
a <- grid::arrow(type = "closed", length = unit(.15, "inches"))
ggraph(ngram_3_graph, layout = "fr") +
geom_edge_link(aes(edge_alpha = n), show.legend = FALSE,
arrow = a, end_cap = circle(.07, 'inches')) +
geom_node_point(color = "lightblue", size = 3) +
geom_node_text(aes(label = name), vjust = 1, hjust = 1) +
theme_void()
```
* Unigrams of store description
```{r}
#Adding special stop words
custom_words_desc <- c("uk", "company", "customer", "business", "na", "mobile", "provide", "product", "facebook", "sony", "ireland", "tv", "computer", "phone", "oven", "laskys", "moonfruit", "cooper", "goldmanlife", "airwave", "imendmacs", "north", "battery", "lcd", "tnp", "mo", "tablet", "sellmyiphone", "iphonererecycler", "iphonerecycler", "st", "sia", "toshiba", "sonos", "nokia", "plusnet", "plasma", "virgin", "adapter")
tibble(word = custom_words_desc,lexicon = rep("custom",length(custom_words_desc))) %>% bind_rows(stop_words) -> custom_stopwords_desc
#Bringing the data for using in n-grams
df <- review_data_en %>% dplyr::select(company_id, store_description, overall) %>% left_join(review_data_by_stores) %>% distinct(.)
#Tokenizing into unigrams
ngram_1_desc <- df %>%
unnest_tokens(word, store_description, token = "ngrams", n =1) %>%
anti_join(custom_stopwords_desc)
#Finding the most frequent unigrams
ngram_1_desc <- ngram_1_desc %>%
group_by(word) %>%
summarise(Frequency = n(),
Overall = round(mean(overall))) %>%
arrange(desc(Frequency))
#Visualizing the top frequent unigrams
df %>%
unnest_tokens(word, store_description, token = "ngrams", n =1) %>%
anti_join(custom_stopwords_desc) %>%
count(word, sort = TRUE) %>%
top_n(10) %>%
ggplot(aes(reorder(word, n), n)) +
geom_col() +
labs(title="Top 10 Unigram frequency for Store Descriptions",
y = "Frequency",
x = "Terms") +
theme(plot.title = element_text(hjust = 0.5)) +
coord_flip()
#Visualizing the top frequent unigrams by ratings
ngram_1_desc %>%
group_by(Overall) %>%
slice_max(Frequency, n = 10) %>%
ungroup() %>%
ggplot(aes(Frequency, fct_reorder(word, Frequency), fill = Overall)) +
geom_col(show.legend = FALSE) +
facet_wrap(~ Overall, ncol = 2, scales = "free") +
labs(title="Top 10 Unigram frequency for Store Descriptions by Overall",
y = "Average Rating",
x = "Frequency") +
theme(plot.title = element_text(hjust = 0.5))
```
* Bigrams of store description
```{r}
#Adding special stop words
custom_words_desc <- c("uk", "company", "customer", "business", "na", "mobile", "provide", "product", "machine", "game", "console", "camera", "virgin", "ssl", "pc", "oven", "fridge", "freezer", "battery", "mo", "lcd", "tv", "cable", "tablet", "cable", "charger", "samsung", "sony")
tibble(word = custom_words_desc,lexicon = rep("custom",length(custom_words_desc))) %>% bind_rows(stop_words) -> custom_stopwords_desc
#Bringing the data
ngram_2_desc <- df %>%
unnest_tokens(word, store_description, token = "ngrams", n =2)
#Tokenizing for bigrams
ngram_2_desc$index <- seq.int(nrow(ngram_2_desc))
df2 <- ngram_2_desc %>%
separate(word, c("word1", "word2"), sep = " ") %>%
dplyr::select('index', 'word1','word2')
ngram_2_desc <- left_join(ngram_2_desc, df2, by = "index")
ngram_2_desc <- ngram_2_desc %>%
filter(!word1 %in% custom_stopwords_desc$word) %>%
filter(!word2 %in% custom_stopwords_desc$word)
ngram_2_desc_splitted <- ngram_2_desc %>%
count(word1, word2, sort = TRUE) %>% na.omit()
#Finding the frequencies of the bigrams
ngram_2_desc_combined <- ngram_2_desc %>%
group_by(word) %>%
summarise(Frequency = n(),
Overall = round(mean(overall))) %>%
arrange(desc(Frequency)) %>%
na.omit()
#Visualizing the top frequent bigrams
ngram_2_desc_combined %>% slice_max(Frequency, n = 10) %>%
ggplot(aes(reorder(word, Frequency), Frequency)) +
geom_col() +
labs(title="Top 10 Bigram Frequency for Listing Descriptions",
y = "Frequency",
x = "Terms") +
theme(plot.title = element_text(hjust = 0.5)) +
coord_flip()
#VIsualizing the top frequent bigrams by ratings
ngram_2_desc_combined %>% group_by(Overall) %>%
slice_max(Frequency, n = 10) %>%
ungroup() %>%
ggplot(aes(Frequency, fct_reorder(word, Frequency), fill = Overall)) +
geom_col(show.legend = FALSE) +
facet_wrap(~ Overall, ncol = 2, scales = "free") +
labs(title="Top 10 Bigram frequency for Store Descriptions by Overall",
y = "Terms",
x = "Frequency") +
theme(plot.title = element_text(hjust = 0.5))
#Common bigrams in reviews
ngram_2_graph <- ngram_2_desc_splitted %>%
filter(n > 4) %>%
graph_from_data_frame()
set.seed(2017)
a <- grid::arrow(type = "closed", length = unit(.15, "inches"))
ggraph(ngram_2_graph, layout = "fr") +
geom_edge_link(aes(edge_alpha = n), show.legend = FALSE,
arrow = a, end_cap = circle(.07, 'inches')) +
geom_node_point(color = "lightblue", size = 3) +
geom_node_text(aes(label = name), vjust = 1, hjust = 1) +
theme_void()
```
* Trigrams of store description
```{r}
#Adding special stop words
custom_words_desc3 <- c("uk", "company", "customer", "business", "na", "mobile", "provide", "product", "machine", "game", "console", "camera", "virgin", "ssl", "pc", "oven", "fridge", "freezer", "battery", "mo", "lcd", "tv", "cable", "tablet", "cable", "charger", "samsung", "sony")
tibble(word = custom_words_desc,lexicon = rep("custom",length(custom_words_desc))) %>% bind_rows(stop_words) -> custom_stopwords_desc3
#Bringing the data
ngram_3_desc <- df %>%
unnest_tokens(word, store_description, token = "ngrams", n =3)
#Tokenizing into trigrams
ngram_3_desc$index <- seq.int(nrow(ngram_3_desc))
df3 <- ngram_3_desc %>%
separate(word, c("word1", "word2", "word3"), sep = " ") %>%
dplyr::select('index', 'word1','word2', 'word3')
ngram_3_desc <- left_join(ngram_3_desc, df3, by = "index")
rm(df3)
ngram_3_desc <- ngram_3_desc %>%
filter(!word1 %in% custom_stopwords_desc3$word) %>%
filter(!word2 %in% custom_stopwords_desc3$word) %>%
filter(!word3 %in% custom_stopwords_desc3$word)
ngram_3_desc_splitted <- ngram_3_desc %>%
count(word1, word2, word3, sort = TRUE) %>% na.omit()
#Finding the frequencies
ngram_3_desc_combined <- ngram_3_desc %>%
group_by(word) %>%
summarise(Frequency = n(),
Overall = round(mean(overall))) %>%
arrange(desc(Frequency)) %>%
na.omit()
#Visualizing the top frequent trigrams