Load packages
# install.packages("dplyr")
# install.packages("tidytext")
# install.packages("ggplot2")
library(dplyr)
library(tidytext)
library(ggplot2)
Create the dataset
text <- c("I love the quality of this product. The price is reasonable, and delivery was fast.",
"The product quality is excellent, but the shipping took too long.",
"Great customer service! I would definitely recommend this product to my friends.",
"The price is too expensive. However, the product looks beautiful.",
"Fast delivery and excellent service. I am very satisfied with my purchase.")
text_df <- tibble(line = 1:5, text = text)
text_df
## # A tibble: 5 × 2
## line text
## <int> <chr>
## 1 1 I love the quality of this product. The price is reasonable, and delive…
## 2 2 The product quality is excellent, but the shipping took too long.
## 3 3 Great customer service! I would definitely recommend this product to my…
## 4 4 The price is too expensive. However, the product looks beautiful.
## 5 5 Fast delivery and excellent service. I am very satisfied with my purcha…
Tokenize: one word per row
tidy_books <- text_df %>%
unnest_tokens(word, text)
tidy_books
## # A tibble: 60 × 2
## line word
## <int> <chr>
## 1 1 i
## 2 1 love
## 3 1 the
## 4 1 quality
## 5 1 of
## 6 1 this
## 7 1 product
## 8 1 the
## 9 1 price
## 10 1 is
## # ℹ 50 more rows
Remove stop words
data(stop_words)
tidy_books <- tidy_books %>%
anti_join(stop_words, by = "word")
tidy_books
## # A tibble: 26 × 2
## line word
## <int> <chr>
## 1 1 love
## 2 1 quality
## 3 1 product
## 4 1 price
## 5 1 reasonable
## 6 1 delivery
## 7 1 fast
## 8 2 product
## 9 2 quality
## 10 2 excellent
## # ℹ 16 more rows
Count the most common words
word_counts <- tidy_books %>%
count(word, sort = TRUE)
word_counts
## # A tibble: 17 × 2
## word n
## <chr> <int>
## 1 product 4
## 2 delivery 2
## 3 excellent 2
## 4 fast 2
## 5 price 2
## 6 quality 2
## 7 service 2
## 8 beautiful 1
## 9 customer 1
## 10 expensive 1
## 11 friends 1
## 12 love 1
## 13 purchase 1
## 14 reasonable 1
## 15 recommend 1
## 16 satisfied 1
## 17 shipping 1
Plot the most frequent words
word_counts %>%
filter(n >= 2) %>%
mutate(word = reorder(word, n)) %>%
ggplot(aes(n, word)) +
geom_col(fill = "steelblue") +
labs(x = "Frequency", y = NULL, title = "Most frequent words")
