1. Describe in one sentence what you aim to examine using user-generated text data and sentiment analysis

I want to study people’s attitudes towards pork belly. Do they think pork belly tastes yummy? Do they associate any “healthy benefits” or “healthy concerns” with pork belly?

  1. Search Reddit threads using a keyword of your choice.
  1. Specifying a subreddit for your search is optional.
  2. It is okay to combine data obtained by searching the keyword across multiple subreddits.
  3. You can choose any period, but ensure you gather a sufficient amount of data.
# load libraries
library("RedditExtractoR") 
library("anytime")
library("magrittr") 
library("ggplot2")
library("dplyr")
library("tidytext")
library("tidyverse")
library("igraph")
library("ggraph")
library("tidyr")
library("wordcloud2")
library("textdata")

library("ggdark")
library("gofastr")
library("syuzhet")
library("sentimentr")
library("lubridate")
# using keyword
threads <- find_thread_urls(keywords = "pork belly", 
                              sort_by = 'relevance', 
                              period = 'all')
## parsing URLs on page 1...
## parsing URLs on page 2...
## parsing URLs on page 3...
colnames(threads)
## [1] "date_utc"  "timestamp" "title"     "text"      "subreddit" "comments" 
## [7] "url"
head(threads)
##     date_utc  timestamp
## 1 2020-08-02 1596399210
## 2 2020-04-13 1586782076
## 3 2017-01-02 1483377980
## 4 2021-04-17 1618663639
## 5 2018-01-28 1517108040
## 6 2023-08-14 1692056430
##                                                                                                                    title
## 1                                                                              [Homemade] Slow smoked sticky pork belly.
## 2                                                                                                      Crispy Pork Belly
## 3                                                                                     Slow cooked pork belly (4032x3024)
## 4 Are we sharing Cubans? Ours includes our 12 hour sous vide house pork belly &amp; house smoked pulled pork.. delicious
## 5                                                   [Homemade] Shoyo Ramen with Roast Pork Belly and Whole Wheat Noodles
## 6                                                                                      Red braised pork belly [homemade]
##   text           subreddit comments
## 1                     food       44
## 2              ketorecipes       53
## 3                 FoodPorn       55
## 4      KitchenConfidential      132
## 5                     food      121
## 6                     food       18
##                                                                                                             url
## 1                         https://www.reddit.com/r/food/comments/i2iuag/homemade_slow_smoked_sticky_pork_belly/
## 2                                       https://www.reddit.com/r/ketorecipes/comments/g0iauh/crispy_pork_belly/
## 3                           https://www.reddit.com/r/FoodPorn/comments/5lmctx/slow_cooked_pork_belly_4032x3024/
## 4 https://www.reddit.com/r/KitchenConfidential/comments/msq30q/are_we_sharing_cubans_ours_includes_our_12_hour/
## 5                 https://www.reddit.com/r/food/comments/7thnk1/homemade_shoyo_ramen_with_roast_pork_belly_and/
## 6                               https://www.reddit.com/r/food/comments/15rb6vg/red_braised_pork_belly_homemade/
  1. Clean your text data and then tokenize it.
# create new column: date
threads <- threads %>% 
  mutate(date = as.POSIXct(date_utc)) %>%
  filter(!is.na(date))

# number of threads by week
threads %>% 
  filter(year(date) == 2022) %>% 
  ggplot(aes(x = date)) +
  geom_histogram(color="black", position = 'stack', binwidth = 60*60*24*7) +
  scale_x_datetime(date_labels = "%b %y",
                   breaks = seq(min(threads$date, na.rm = T), 
                                max(threads$date, na.rm = T), 
                                by = "1 month")) +
  theme_minimal()

replace_reg <- "http[s]?://[A-Za-z\\d/\\.]+|&amp;|&lt;|&gt;"

words_clean <- threads %>% 
  # drop URLs
  mutate(text = str_replace_all(text, replace_reg, "")) %>%
  # Tokenization (word tokens)
  unnest_tokens(word, text, token = "words") %>% 
  # drop stop words
  anti_join(stop_words, by = "word") %>% 
  # drop non-alphabet-only strings
  filter(str_detect(word, "[a-z]"))

# Check the number of rows after removal of the stop words. There should be fewer words now
print(
  glue::glue("Before: {nrow(words)}, After: {nrow(words_clean)}")
)
words_clean %>%
  count(word, sort = TRUE) %>%
  top_n(15, n) %>%
  mutate(word = reorder(word, n)) %>%
  ggplot(aes(x = word, y = n)) +
  geom_col() +
  xlab(NULL) +
  coord_flip() +
  labs(x = "words",
       y = "counts",
       title = "Unique wordcounts")

  1. Generate a word cloud that illustrates the frequency of words except your keyword.
n <- 20
h <- runif(n, 0, 1) # any color
s <- runif(n, 0.6, 1) # vivid
v <- runif(n, 0.3, 0.7) # neither too dark or bright

df_hsv <- data.frame(h = h, s = s, v = v)
pal <- apply(df_hsv, 1, function(x) hsv(x['h'], x['s'], x['v']))
pal <- c(pal, rep("grey", 10000))
words_clean %>% 
  filter(!word %in% c("pork","belly")) %>% 
  count(word, sort = TRUE) %>% 
  wordcloud2(color = pal, 
             minRotation = 0, 
             maxRotation = 0, 
             ellipticity = 0.8)
  1. Conduct a tri-gram analysis.
  1. Extract tri-grams from your text data.

  2. Remove tri-grams containing stop words or non-alphabetic terms.

  3. Present the frequency of tri-grams in a table.

  4. Discuss any noteworthy tri-grams you come across.

#get ngrams.
words_trigram <- threads %>%
  mutate(text = str_replace_all(text, replace_reg, "")) %>%
  select(text) %>%
  unnest_tokens(output = paired_words,
                input = text,
                token = "ngrams",
                n = 3)
#show ngrams with sorted values
words_trigram %>%
  count(paired_words, sort = TRUE) %>% 
  head(20) %>% 
  knitr::kable()
paired_words n
NA 222
2 hours at 2
a bit of 2
add a bit 2
brought it up 2
chicharrones if you 2
for the first 2
if you add 2
is it still 2
it came out 2
it in the 2
it still chicharrones 2
it up to 2
more and more 2
of hot sauce 2
one of the 2
pork belly and 2
pork belly it 2
sauce on it 2
still chicharrones if 2
#separate the paired words into three columns
words_trigram_pair <- words_trigram %>%
  separate(paired_words, c("word1", "word2", "word3"), sep = " ")

# filter rows where there are stop words under word 1 column, word 2 column or word 3 column
words_trigram_pair_filtered <- words_trigram_pair %>%
  # drop stop words
  filter(!word1 %in% stop_words$word & 
           !word2 %in% stop_words$word & 
           !word3 %in% stop_words$word) %>% 
  # drop non-alphabet-only strings
  filter(str_detect(word1, "[a-z]") & 
           str_detect(word2, "[a-z]") & 
           str_detect(word3, "[a-z]"))

# Filter out words that are not encoded in ASCII
# To see what's ASCCII, google 'ASCII table'
library(stringi)
words_trigram_pair_filtered %<>% 
  filter(stri_enc_isascii(word1) & 
           stri_enc_isascii(word2) &
           stri_enc_isascii(word3))

# Sort the new tri-gram (n=3) counts:
words_counts <- words_trigram_pair_filtered %>%
  count(word1, word2, word3) %>%
  arrange(desc(n))

head(words_counts, 20) %>% 
  knitr::kable()
word1 word2 word3 n
20lb turkey tomorrow 1
barbara lynch restaurant 1
brussels sprout banh 1
carried pork belly 1
chinese buddhist cuisine 1
coarse black pepper 1
costco seasoned liberally 1
cranberry apple slaw 1
crispy pork belly 1
cutting board wrapped 1
delicious ridiculous cook 1
entire cook rested 1
fat cap glued 1
fried brussels sprout 1
heat source bumped 1
homemade pork ramen 1
hot sauce mixed 1
lidl pork belly 1
lumberjack pecan pellets 1
meat church scored 1
  1. Perform a sentiment analysis on your text data using a dictionary method that accommodates negations.

You are welcome to apply a deep learning-based model to enrich your analysis, but employing the dictionary method is imperative.

pb_sentiment <- threads %>% 
  mutate(title = replace_na(title, ""),
         text = replace_na(text, ""),
         title_text = str_c(title, text, sep = ". "),
         sentiment_dict = sentiment_by(title_text) %>% pull(ave_sentiment),
         word_count = sentiment_by(title_text) %>% pull(ave_sentiment))
  1. Display 10 sample texts alongside their sentiment scores and evaluate the credibility of the sentiment analysis outcomes.
sentimentr_pb <- pb_sentiment %>%
  mutate(sentimentr_abs = abs(sentiment_dict),
         sentimentr_binary = case_when(sentiment_dict > 0 ~ 'positive',
                                       TRUE ~ 'negative')) %>% 
  group_by(sentimentr_binary) %>%
  arrange(desc(sentimentr_abs)) %>%
  slice_head(n = 5) %>%
  ungroup() %>% 
  arrange(sentiment_dict)

# negative
cat("negative posts\n")
## negative posts
sentimentr_pb %>% 
  filter(sentimentr_binary == 'negative') %>% 
  pull(title_text) %>% 
  print()
## [1] "Deep fried pork belly >$>$>$. "                                                                                        
## [2] "Not the cleanest plate. Pan seared scallops on Pea Spinach lemon purée with pork belly and butternut squash risotto.. "
## [3] "Forbidden pork belly. "                                                                                                
## [4] "Forbidden pork belly. "                                                                                                
## [5] "Pork belly fried rice. "
# positive
cat("\npositive posts\n")
## 
## positive posts
sentimentr_pb %>% filter(sentimentr_binary == 'positive') %>% pull(title_text) %>% print()
## [1] "Girlfriend cooked some pork belly, so tasty. "                                                                                                                                    
## [2] "[Pro/Chef] Steamed Buns With Pork Belly. "                                                                                                                                        
## [3] "Texas bbq, beef rib, brisket, pork belly, pork ribs, Turkey, taco sausage, yellow rose sausage. [Pro/chef]. "                                                                     
## [4] "Please share your number one tip for cooking pork belly. I cooked it yesterday for the first time and it came out pretty well. Next time I'm hoping to take it to the next level."
## [5] "Al Pastor Chicken Thighs and Pork Belly/Butt. First time doin this, came out so good. Was a bit tedious but well worth it in the end!"

The top 5 negative posts and the positive posts are printed above. From my point of view, the dictionary method in R did a good job in detecting positive posts, because 3 out of 5 posts show very clear postivie tone. For the second and the third post, they seem to be netrual expression, however, if take “pro/chef” into account it seems like the posts are about displaying the fantastic work from chefs.

2 out of the 5 negative posts do show some negative tone, but the 2 sentences are too short to understand what they are trying to say. The second sentence is more of a humble appreciation of the plate rather than a sign of dislike. It is funny to see that “fried” appear both in the first and fifth sentence. Not sure if “fried” is the cue for the algorithm to say the sentence is “negative”. If it is the case, it kinds of makes sense, because “fried” is not usually healthy though people usually like it.

  1. Discuss intriguing insights derived from the sentiment analysis, supporting your observations with at least two plots.
# create new columns: date, year, day_of_week, is_weekend, time
pb_sentiment %<>%
  mutate(sentimentr_abs = abs(sentiment_dict),
         sentimentr_binary = case_when(sentiment_dict > 0 ~ 'positive',
                                       TRUE ~ 'negative')) %>% 
  group_by(sentimentr_binary) %>%
  arrange(desc(sentimentr_abs)) %>%
  ungroup() %>% 
  arrange(sentiment_dict) %>%  
  mutate(date = as.POSIXct(date_utc)) %>%
  filter(!is.na(date)) %>% 
  mutate(year = year(date),
         day_of_week = wday(date, label = TRUE),
         is_weekend = ifelse(day_of_week %in% c("Sat", "Sun"), "Weekend", "Weekday"),
         time = timestamp %>% 
           anytime(tz = anytime:::getTZ()) %>% 
           str_split('-| |:') %>% 
           sapply(function(x) as.numeric(x[4])))
# sentiment by year
pb_sentiment %>% 
  ggplot(aes(x = year, fill = sentimentr_binary)) +
  geom_bar(position = 'stack') +
  scale_x_continuous(breaks = seq(min(pb_sentiment$year), 
                                  max(pb_sentiment$year), 
                                  by = 1)) +
  scale_fill_brewer(palette = 'PuRd', direction = -1) + 
  dark_theme_grey()
## Inverted geom defaults of fill and color/colour.
## To change them back, use invert_geom_defaults().

So sad to see that only a marginal proportion of posts are detected as postivie posts.

Use word cloud to see the words within negative and positive posts respectively to see what is happening there…

pb_sentiment_c <- pb_sentiment %>% 
  mutate(title_text = str_replace_all(title_text, replace_reg, "")) %>%
  unnest_tokens(word, title_text, token = "words") %>% 
  anti_join(stop_words, by = "word") %>% 
  filter(str_detect(word, "[a-z]")) %>% 
  filter(!word %in% c('pork','belly'))
pb_sentiment_c_negative <- pb_sentiment_c %>% 
  filter(sentimentr_binary == "negative")
pb_sentiment_c_positive <- pb_sentiment_c %>% 
  filter(sentimentr_binary == "positive")

pb_sentiment_c_negative_unique <- pb_sentiment_c_negative %>% 
  anti_join(pb_sentiment_c_positive, by = 'word')
pb_sentiment_c_positive_unique <- pb_sentiment_c_positive %>%
  anti_join(pb_sentiment_c_negative, by = 'word')

Words appearing in negative threads

#' Webshot a widget and place it in place with markdown syntax

markdown_widget <- function(widget,path=getwd(),filename="file.png"){
  require(htmlwidgets)
  require(webshot)
  saveWidget(widget,"tmp.html",selfcontained = F)
  file <- paste(path,filename,sep = "/")
  webshot("tmp.html",file,delay = 5,vwidth = 1024,vheight = 768)
  file.remove("tmp.html")
  paste0("![",file,"](",file,")\n\n") %>% cat()
}
pb_sentiment_c_negative_unique %>% 
  count(word, sort = TRUE) %>%
  wordcloud2(color = pal, 
             minRotation = 0, 
             maxRotation = 0, 
             ellipticity = 0.8)

Seemed like, starting from the second one, the wordcloud failed to render, I haven’t worked out how to install the right package of webshot, which can help snip the html widgets and render the png…

So I mannually took the snapshot of the wordclouds and insert it into my markdown file.

# library(webshot)
# library(htmlwidgets)
# widget_negative <- pb_sentiment_c_negative_unique %>% 
#   count(word, sort = TRUE) %>%
#   wordcloud2(color = pal, 
#              minRotation = 0, 
#              maxRotation = 0, 
#              ellipticity = 0.8)
# saveWidget(widget_negative, "pb_neg.html", selfcontained = F)
# webshot("pb_neg.html", "pb_neg.png", delay = 5, vwidth = 2000, vheight = 2000)
snapshot of my wordcloud since I wasn’t able to render it directly
snapshot of my wordcloud since I wasn’t able to render it directly

There are some words indicating some not-healthy cooking methods of pork belly. So those who posted about pork belly not-positively probably because they saw some unhealthily cooked meat. And “fat” is a word related to health concern as well.

Words appearing in positive threads

pb_sentiment_c_positive_unique %>% 
  count(word, sort = TRUE) %>%
  wordcloud2(color = pal, 
             minRotation = 0, 
             maxRotation = 0, 
             ellipticity = 0.8)
snapshot of my wordcloud since I wasn’t able to render it directly
snapshot of my wordcloud since I wasn’t able to render it directly

Relate this word cloud to the text printed in question 7, seems like some positive posts were showing the “pro” plate cooked by some chefs. So happy to see that family is a unique word in the positive posts, becasue I would like to interpret those posts as people are enjoying pork belly with their faimlies.

Sentiment by day of week.

# sentiment by day
pb_sentiment %>% 
  ggplot(aes(x = day_of_week, fill = sentimentr_binary)) +
  geom_bar(position = 'fill') +
  scale_fill_brewer(palette = 'PuRd', direction = -1) +
  dark_theme_grey()

It seems like, on Saturday, the positive posts about pork belly have the highest percentage of the total posts with the same key words. However, it probably simply because people are usually more relax on Saturdays and tend to enjoy more of everything, not only pork belly.

To answer my question I asked myself in question 1, there are some people enjoying eating pork belly. And some health concern about eating pork belly were found in the unique words in the negative posts. However, those health concern seem to be relative to the cooking method rather than the meat itself.

I could be biased, but the raw pork belly itself contains rich vitamins in its fat, and with healthy cooking method (such as slow boiling with mild sauce) and proper consuming frequencies, they are good for health.