# Package names
packages <- c("RedditExtractoR", "anytime", "magrittr", "ggplot2", "dplyr", "tidytext", "tidyverse", "igraph", "ggraph", "tidyr", "wordcloud2", "textdata", "sf", "tmap","ggdark","gofastr", "syuzhet", "sentimentr", "lubridate", "here")

# Install packages not yet installed
installed_packages <- packages %in% rownames(installed.packages())
if (any(installed_packages == FALSE)) {
install.packages(packages[!installed_packages])
}

# Load packages
invisible(lapply(packages, library, character.only = TRUE))

2. Search Reddit threads using ‘gender affirming care’ as keyword

2.1 Download threads data

# using keyword
threads <- find_thread_urls(keywords = 'gender affirming care', 
                              sort_by = 'relevance', 
                              period = 'all')
save(threads, file = "threads_data.rda")

Check the number of threads found by the keyword per subreddit.

load("threads_data.rda")
threads$subreddit %>% table() %>% sort(decreasing = T) %>% head(15)
## .
##           politics               news              trans               lgbt 
##                 50                 18                 10                  9 
##                MtF           missouri      NorthCarolina        transgender 
##                  8                  6                  5                  5 
##            Indiana           Nebraska     PublicFreakout              texas 
##                  4                  4                  4                  4 
## WhitePeopleTwitter         neoliberal      UpliftingNews 
##                  4                  3                  3

2.2 Download comments and additional information

There are lots of threads only have title information but don’t have text information in our downloaded data. To have more data for analysis, we will extract the comments from the threads. In this way, we will also get more insight on people’s attitude toward this topic through their comments.

# get individual comments
threads_content <- get_thread_content(threads$url[1:50])
threads_content1 <- get_thread_content(threads$url[51:100])
threads_content2 <- get_thread_content(threads$url[101:150])
threads_content3 <- get_thread_content(threads$url[151:200])

comments <- rbind(threads_content$comments, threads_content1$comments, threads_content2$comments, threads_content3$comments)

save(comments, file = "comments_data.rda") # 47308 comments in total

3. Data cleaning and Tokenization

Let’s tokenize the texts and plot the top 30 words to see what are some of the words that are frequently used.

load("comments_data.rda")

# Regex that matches URL-type string
replace_reg <- "http[s]?://[A-Za-z\\d/\\.]+|&amp;|&lt;|&gt;"

words_clean <- comments %>% 
  # drop URLs
  mutate(comment = str_replace_all(comment, replace_reg, "")) %>%
  # Tokenization (word tokens)
  unnest_tokens(word, comment, token = "words") %>% 
  # drop stop words - from the tidytext package
  anti_join(stop_words, by = "word") %>% 
  # drop non-alphabet-only strings
  filter(str_detect(word, "[a-z]")) %>% 
  # drop keywords
  filter(!grepl("gender|affirming|care", word, ignore.case = TRUE))
words_clean %>%
  count(word, sort = TRUE) %>%
  top_n(30, 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")

4. Generate a word cloud

This block of code generates a color palette designed to highlight a selected number of words while graying out the remaining ones.

n <- 30
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 %>% 
  count(word, sort = TRUE) %>% 
  wordcloud2(color = pal, 
             minRotation = 0, 
             maxRotation = 0, 
             ellipticity = 0.8)

5. Tri-grams analysis

5.1 Get tri-grams

words_tri_gram <- comments %>%
  mutate(comment = str_replace_all(comment, replace_reg, "")) %>%
  select(comment) %>%
  unnest_tokens(output = paired_words,
                input = comment,
                token = "ngrams",
                n = 3)

5.2 Remove tri-grams containing stop words or non-alphabetic terms

# Separate the paired words into three columns
words_tri_pair <- words_tri_gram %>%
  separate(paired_words, c("word1", "word2", "word3"), sep = " ")

words_tri_pair_filtered <- words_tri_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
library(stringi)
words_tri_pair_filtered %<>% 
  filter(stri_enc_isascii(word1) & stri_enc_isascii(word2) & stri_enc_isascii(word3))

5.3 Visualization

Frequency table

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

head(words_counts, 30) %>% 
  knitr::kable()
word1 word2 word3 n
gender affirming care 2717
gender affirming surgery 231
gender affirming surgeries 126
mental health outcomes 119
subreddit message compose 108
cross sex hormones 105
gender affirming hormones 84
gender affirming medical 83
gender reassignment surgery 83
hormone replacement therapy 80
life altering decisions 80
sex reassignment surgery 80
gender affirming healthcare 76
american medical association 73
mental health issues 68
banning gender affirming 67
ban gender affirming 64
american psychological association 57
gender affirming hormone 57
affirming medical care 54
mental health care 54
receiving gender affirming 50
gender affirming treatment 46
life saving medical 45
hate trans people 43
accusations hate speech 42
attack people personal 42
debate discuss argue 42
people personal insults 42
personal insults shill 42

By using the igraph and ggraph library we can visualize the words occurring in pairs.

# plot word network
words_counts %>%
  filter(n >= 30) %>%
  graph_from_data_frame() %>% # convert to graph
  ggraph(layout = "fr") +
  geom_edge_link(aes(edge_alpha = .6, edge_width = n)) +
  geom_node_point(color = "darkslategray4", size = 3) +
  geom_node_text(aes(label = name), vjust = 1.8) +
  labs(title = "Word Networks",
       x = "", y = "")
## Warning: Using the `size` aesthetic in this geom was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` in the `default_aes` field and elsewhere instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

Apart from surgical and hormone-related tri-grams, which are often the focal points of debate when discussing gender-affirming care, it’s crucial to recognize the significance of mental health. Tri-grams such as “mental health outcomes,” “mental health issues,” and “mental health care” highlight the immense mental pressures faced by transgender individuals, signaling a need for increased support in this area.

It’s evident that certain negative tri-grams, like “hate trans people”, “attack people personal” and “people personal insults” are prevalent. This underscores the ongoing hostility transgender individuals encounter in our society, partially explaining the challenges they may experience with their mental health.

6. Sentiment analysis

sentences <- get_sentences(comments$comment)
sentiment_scores <- sentiment_by(sentences)

comments_scores <- cbind(comments, sentiment_scores)

7. 10 sample texts alongside their sentiment scores and evaluate the credibility of the sentiment analysis outcomes.

# Randomly select 5 comments have score higher than 0.5
larger_than_05 <- comments_scores %>%
  filter(word_count > 5) %>%
  filter(ave_sentiment > 0.5) %>%
  slice_sample(n = 5, replace = FALSE) %>%
  select(c("ave_sentiment", "comment"))
knitr::kable(larger_than_05)
ave_sentiment comment
0.6177658 Cobra used to want to take over the world, but now Major Bludd tells us all they care about is keeping trans people in the closet.
0.5219701 So because one rich and famous example had surgery ONE year before turning 18, after most likely spending many, if not most, of her formative years working with professional doctors and therapists who agreed it was the correct medical procedure, there must be an epidemic of 12 year olds rushing out to get top surgery?
1.3953574 Yeah I’m pretty sure they’re asking about actual practical advice like is it affordable and accessible for transit.
0.5075647 Did you know doctors used to encourage smoking and used to say smoking was good for a person to do and that there was no negative effects from it as a matter a fact they used to say there was benefits.
0.6000000 You just seem really enlightened by your own intelligence.
# Randomly select 5 comments have score lower than -0.5
smaller_than_minus05 <- comments_scores %>%
  filter(word_count > 5) %>%
  filter(ave_sentiment < -0.5) %>%
  slice_sample(n = 5, replace = FALSE) %>%
  select(c("ave_sentiment", "comment"))
knitr::kable(smaller_than_minus05)
ave_sentiment comment
-1.0206207 Shut the fuck up lying bigot.
-0.7476928 If its for minors under 16 then its understandable IMO, but what the hell are they thinking when they wanna ban this shit for adults?
-0.5276449 Conservative on social issues means denying medical care to a person?
-0.5692100 It really sucks how we’re essentially forced to become endocrinologists.
-0.6240377 Love the ‘keep watching TV’ insult while regurgitating conservative talking points about mutilation.

The overall results appear to be accurate. However, upon testing multiple times with different samples, I’ve noticed that the score for negative comments seems more consistent than for positive ones. At times, the sentiment score fails to accurately interpret comments that contain rhetorical questions or sarcasm.

8. Discuss intriguing insights derived from the sentiment analysis

8.1 Keywords in positive/negative comments

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

reddit_sentiment_clean <- comments_scores %>% 
  mutate(comment = str_replace_all(comment, replace_reg, "")) %>%
  unnest_tokens(word, comment, token = "words") %>% 
  anti_join(stop_words, by = "word") %>% 
  filter(str_detect(word, "[a-z]")) 

# Use 0.5 and -0.5 as threshold
reddit_sentiment_clean_negative <- reddit_sentiment_clean %>% 
  filter(ave_sentiment < -0.5)
reddit_sentiment_clean_positive <- reddit_sentiment_clean %>% 
  filter(ave_sentiment > 0.5)

# Identify words that are uniquely seen in positive/negative comments
reddit_sentiment_clean_negative_unique <- reddit_sentiment_clean_negative %>% 
  anti_join(reddit_sentiment_clean_positive, by = 'word')
reddit_sentiment_clean_positive_unique <- reddit_sentiment_clean_positive %>%
  anti_join(reddit_sentiment_clean_negative, by = 'word')
n <- 30
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))

reddit_sentiment_clean_negative_unique %>% 
  count(word, sort = TRUE) %>%
  wordcloud2(color = pal, 
             minRotation = 0, 
             maxRotation = 0, 
             ellipticity = 0.8)
reddit_sentiment_clean_positive_unique %>% 
  count(word, sort = TRUE) %>%
  wordcloud2(color = pal, 
             minRotation = 0, 
             maxRotation = 0, 
             ellipticity = 0.8)

In the negative word cloud, ‘bigot’ and ‘bigotry’ stand out as the most frequent words. This indicates a strong disagreement between people on both sides, each perceiving the other as stubborn. Additionally, the appearance of ‘red’ as a keyword suggests that gender-affirming care has become a political issue. States dominated by Republicans or ‘red states’ continue to pass measures restricting access to gender-affirming care for youth, making it significantly challenging to obtain. The presence of words like ‘killing’ and ‘died’ in the word cloud raises awareness that the challenges faced by trans people go beyond limited medical access or mental support—it extends to threats on their lives.

In the positive word cloud, words like ‘provide,’ ‘accept,’ and ‘fair’ reflect the essential needs of the trans community. Notably, the frequent appearance of ‘jersey’ is intriguing. I did some research and found that Democratic governor Phil Murphy signed an executive order securing a person’s right to gender-affirming care in March of this year. This makes New Jersey at least the third state in the U.S. to establish protections for trans people, following California and Minnesota. Considering ‘jersey’ in the positive word cloud and ‘red’ in the negative word cloud, it’s plausible to assume that most individuals hold a more supportive attitude towards gender-affirming care on reddit.

8.2 Sentiment by year

If we don’t group data by year, the sentiment value seems have a normal distribution, but let’s see if there are differences between years.

ggplot(comments_scores, aes(x = ave_sentiment)) +
  geom_histogram(binwidth = 0.1, fill = "skyblue", color = "black") +
  labs(title = "Distribution of ave_sentiment", x = "ave_sentiment", y = "Frequency") +
  xlim(-1, 1)

# Create new columns: date, year, day_of_week, is_weekend, time
comments_scores %<>% 
  mutate(date = as.POSIXct(date)) %>%
  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])))
# Categorize sentiment value from 1-5, higher value means more positive
categorize_sentiment <- function(value) {
  if (value <= -0.8) {
    return(1)
  } else if (value > -0.8 & value < -0.3) {
    return(2)
  } else if (value >= -0.3 & value <= 0.3) {
    return(3)
  } else if (value > 0.3 & value < 0.8) {
    return(4)
  } else {
    return(5)
  }
}

comments_scores <- comments_scores %>%
  mutate(sentiment_category = sapply(ave_sentiment, categorize_sentiment))

category_counts <- comments_scores %>%
  group_by(sentiment_category,year) %>%
  summarize(count = n())
## `summarise()` has grouped output by 'sentiment_category'. You can override
## using the `.groups` argument.
# Sentiment by year
comments_scores %>%
  filter(!year == 2020) %>% # exclude 2020 because only one row of information
  mutate(sentiment_category = as.factor(sentiment_category)) %>%
  ggplot(aes(x = year, fill = sentiment_category)) +
  geom_bar(position = 'fill') +
  scale_x_continuous(breaks = seq(min(comments_scores$year), 
                                  max(comments_scores$year), 
                                  by = 1)) +
  scale_fill_brewer(palette = 'PuRd', direction = -1) + 
  labs(y = "Percentage") +
  dark_theme_grey()
## Inverted geom defaults of fill and color/colour.
## To change them back, use invert_geom_defaults().

In the bar chart, we observe that the majority of comments fall within the value of 3 (score range from -0.3 to 0.3), indicating a relatively neutral tone without strongly expressed emotions in most comments. Additionally, there appears to be a slight increase in the percentage of comments with values of 4 or 5 each year. To better analyze this trend, let’s compare these percentages in tables for a clearer view of the year-on-year changes.

# Calculate percentage for each sentiment category within each year
percentage_table <- comments_scores %>%
  group_by(year, sentiment_category) %>%
  summarise(count = n(), .groups = "drop") %>%
  group_by(year) %>%
  mutate(percentage = count / sum(count) * 100) %>%
  select(year, sentiment_category, percentage) %>%
  filter(! year == 2020) %>%
  pivot_wider(names_from = sentiment_category, values_from = percentage)
knitr::kable(percentage_table)
year 1 2 3 4 5
2019 0.3039514 2.431611 91.79331 5.471125 NA
2021 0.5405405 8.108108 84.86486 6.486486 NA
2022 0.5201560 8.361508 83.96619 6.840052 0.3120936
2023 0.3938317 8.250006 82.41056 8.551773 0.3938317

In the table, a clear trend emerges: the percentage of comments with a value of 4 has increased from 5.5% to nearly 8.6%. Interestingly, there were no comments rated as value 5 in 2019 and 2021, but they appeared in 2022, with a further increase in percentage in 2023. These findings can be interpreted as positive indicators, suggesting a growing positive or supportive attitude towards gender-affirming care-related topics among a larger audience.

However, it’s important to note the contrasting shifts. The percentage of neutral comments (value 3) has notably decreased. Simultaneously, negative comments have surged, particularly those rated as value 2, escalating from 2.4% to 9.3%. This shift indicates a polarization of viewpoints, signifying that individuals who previously held neutral positions are now transitioning towards more extreme stances—either more supportive or more hostile towards transgender individuals. This polarization mirrors the intensified debates surrounding this topic in our society today.