PART I: Basic Text Analysis

Question I.

Import the dataset nyt.csv and utilize the ggplot2 package to create a time series plot representing the comment count. What trends do you observe here based on the time series plot? (tip: make sure that you convert the Date column to a Date class using the as.Date() function.)

# Install and load necessary packages
library(tidyverse)

# Read the CSV file and convert the Date column to Date class
nyt_data <- read.csv("/Users/mac/nyt.csv")
nyt_data$Date <- as.Date(nyt_data$Date)
str(nyt_data)
## 'data.frame':    8593 obs. of  3 variables:
##  $ Comment: chr  "Well Donald Trump has sort of truth issues with the u.s companies and what im talking about nobody will ever be"| __truncated__ "Sounds like commie propaganda to me" "Time for an UPDATE and analysis of what has come about and revealed since this video was made.  There was a gla"| __truncated__ "maybe we should had avoided direct contact with any sick or diseased family member. \nhugging them is a massive"| __truncated__ ...
##  $ Account: chr  "Atamanenco Vladislav" "Roof With A Floor" "Doug Hahn" "Tsiney Kinori" ...
##  $ Date   : Date, format: "2023-10-15" "2023-10-07" ...
# Group by Date and summarize the comment count
comments_sum <- nyt_data %>%
  group_by(Date) %>%
  summarize(num_comments = n())

# Extract year from Date
comments_sum <- comments_sum %>%
  mutate(year = lubridate::year(Date))

# Create a time series plot for comment count, differentiating by years
ggplot(data = comments_sum, aes(x = Date, y = num_comments, color = factor(year))) +
  geom_line() +
  labs(title = "NYT Comment Count Time Series",
       x = "Date",
       y = "Comment Count",
       color = "Year") +
  theme_bw()

# Filter data for a specific year (e.g., 2020)
year_to_plot <- 2020
filtered_data <- nyt_data %>%
  filter(lubridate::year(Date) == year_to_plot)

# Group by Date and summarize the comment count
comments_sum <- filtered_data %>%
  group_by(Date) %>%
  summarize(num_comments = n())

# Create a time series plot for comment count
ggplot(data = comments_sum, aes(x = Date, y = num_comments)) +
  geom_line() +
  labs(title = paste("NYT Comment Count Time Series for", year_to_plot),
       x = "Date",
       y = "Comment Count") +
  theme_bw()

Observations:

  1. The comment count reached its zenith in 2020, indicating the highest level of user engagement.
  2. In 2021, there is a noticeable drop in comment activity.
  3. The years 2022 and 2023 display a more stable trend, with no substantial changes in comment counts. This suggests a period of consistency or a potential plateau in user interaction.

Question II.

Skim through the comments and identify any necessary cleanup tasks. Address any required cleaning in the comments and save the cleaned version to a new column labeled clean_comment. Please provide the bullet points of the specific cleaning actions you performed on the comments.

# Load necessary libraries
library(glue)
library(tidyverse)

# Apply text cleaning to the 'comment' column
nyt_data <- nyt_data %>%
  
  # Remove HTML tags and quotation marks, normalize white space:
  mutate(
    clean_comment = Comment %>%
      str_replace_all("<[^>]+>|'", " ") %>%
      # Remove any characters that are not alphanumeric or white space
      str_replace_all("[^[:alnum:]\\s]", "") %>%
      # Remove words with two or fewer characters
      str_replace_all("\\b\\w{1,2}\\b", "") %>%
      # Lowercase
      tolower() %>%
      # Trim spaces at start and end
      str_squish()
  ) %>%
  filter(!str_detect(clean_comment, "[^a-zA-Z0-9\\s.,!?]")) #remove rows with Non-English comments

# Display the first 10 rows of the cleaned data
head(nyt_data$clean_comment, 10)
##  [1] "well donald trump has sort truth issues with the companies and what talking about nobody will ever taking comment seriously and will jus ignore comment"                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
##  [2] "sounds like commie propaganda"                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
##  [3] "time for update and analysis what has come about and revealed since this video was made there was glaring omission fauci the video remember him saying early that this was like the flu want know what trump was being told their meetings and briefings went against their recommendations and shut down the travel from china early and interview with fauci when asked about trump and his response and actions the outbreak said was impressive now see where the cdc and some hospitals are calling for the use hydroxychloroquine and ivermectin their protocol also the effects mrna there are lot questions answered still biggest question why did china allow travel out their country after the new year celebration they knew this virus was out there just saying"
##  [4] "maybe should had avoided direct contact with any sick diseased family member hugging them massive mistake you may become sick from others"                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
##  [5] "not surprised here america more concern was harming the economy"                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
##  [6] "unbelievable covid was politicalized america australia most chose band together are double vaccinated many lost lives unnecessarily"                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
##  [7] "blame all those death from june august blm top out around april then slowly drop then starting june til august blm protest and riot over all the country mass gathering and mass death during the time when blm was activing rioting looting and mass gathering covic case jump from 200"                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      
##  [8] "dont forgetthey were counting the number positive testnot the individual person some patients might have positive test before even being admitted the hospital"                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
##  [9] "johnny harrys usual calling like"                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
## [10] "drumpf had idea senseless"

Cleaning Tasks:

  1. Remove HTML Tags and Quotation Marks:

str_replace_all(“<[^>]+>|‘“,” “) - This removes HTML tags (anything between < and >) and single quotation marks from the ’Comment’ column.

  1. Remove Non-alphanumeric Characters and White spaces:

str_replace_all(“[^[:alnum:]\s]”, ““) - This removes any characters that are not alphanumeric or white space.

  1. Remove Words with Two or Fewer Characters:

str_replace_all(“\b\w{1,2}\b”, ““) - This removes words with two or fewer characters.

  1. Lowercase:

tolower(): This converts all text to lowercase.

  1. Trim Spaces at the Start and End:

str_squish(): This trims spaces at the beginning and end of the cleaned comment.

Question III.

From this point onward, you will only need to use the clean_comment column for all subsequent tasks. Please identify and list the top 20 most frequent terms within the comments after the cleaning process.

# Load necessary libraries
library(quanteda)
library(quanteda.textstats)

# Using clean_comment column
clean_dfm <- nyt_data$clean_comment %>%
  tokens(remove_punct = TRUE, remove_numbers = TRUE, remove_symbols = TRUE) %>%
  dfm(tolower = TRUE) %>%
  dfm_remove(stopwords("english"))

# Get the top 20 most frequent terms
top_terms <- textstat_frequency(clean_dfm, n = 20)

# Display the results
print(top_terms)
##      feature frequency rank docfreq group
## 1      trump      1906    1    1450   all
## 2     people      1679    2    1169   all
## 3       just       961    3     821   all
## 4       like       909    4     762   all
## 5      virus       850    5     624   all
## 6     johnny       773    6     738   all
## 7      china       760    7     500   all
## 8      covid       755    8     587   all
## 9    country       744    9     615   all
## 10       can       723   10     620   all
## 11       one       716   11     619   all
## 12  pandemic       708   12     582   all
## 13     video       652   13     579   all
## 14       now       650   14     571   all
## 15     world       608   15     496   all
## 16   america       576   16     480   all
## 17      even       514   17     451   all
## 18    deaths       514   17     377   all
## 19 president       511   19     417   all
## 20    harris       497   20     483   all

Question IV.

Create a plot displaying the top 20 word frequencies using ggplot2. Select the data visualization that you deem most suitable in this case.

library(ggplot2)

# top_terms is the data frame with the top 20 word frequencies
top_terms$feature <- with(top_terms, reorder(feature, -frequency))

top_terms %>%
  ggplot(aes(x = feature, y = frequency)) +
  geom_bar(stat = "identity", fill = "steelblue") +
  labs(title = "Top 20 Word Frequencies",
       y = "Frequency",
       x = NULL) +
  theme_classic() +
  theme(axis.text.x = element_text(angle = 60, hjust = 1),
        legend.position = "none")

Question V.

Generate a word cloud using the top 200 most frequent terms.

library(quanteda.textplots)
textplot_wordcloud(clean_dfm, max_words = 200, color = "darkred")

PART II: Lexicon-Based Sentiment Analysis

Question I(A).

Create a new column named Category based on the the Date column. If the date falls on or before 2021-01-20, recode it as Trump. If it is after 2021-01-20, recode it as Biden. This distinction indicates whether the comment was posted during the Trump administration or the Biden administration.

nyt_data <- nyt_data %>%
  mutate(
    Category = case_when(
      Date <= as.Date("2021-01-20") ~ "Trump",
      Date > as.Date("2021-01-20") ~ "Biden"
    )
  )

Question I(B).

Create a new column named ID based on the row number.

nyt_data <- nyt_data %>%
  mutate(
    ID = row_number()
  )

Question I(C).

Create a tidy format named nyt_tidy using the ID and clean_comment columns.

library(tidyverse)
library(tidytext)
nyt_tidy <- nyt_data %>%
  select(ID, clean_comment) %>%
  unnest_tokens(word, clean_comment)
# Display the first few rows of the selected columns
selected_columns <- nyt_data %>%
  select(ID, Date, Category)
print(head(selected_columns))
##   ID       Date Category
## 1  1 2023-10-15    Biden
## 2  2 2023-10-07    Biden
## 3  3 2023-10-06    Biden
## 4  4 2023-09-30    Biden
## 5  5 2023-09-29    Biden
## 6  6 2023-09-19    Biden
# Display the first few rows of nyt_tidy
print(head(nyt_tidy))
##   ID   word
## 1  1   well
## 2  1 donald
## 3  1  trump
## 4  1    has
## 5  1   sort
## 6  1  truth

Question II.

Compute the sentiment score for each comment using the valence-based AFINN lexicon, which measures sentiment with a numeric score between -5 and 5. Furthermore, please provide an explanation of how you derived the sentiment score. For instance, clarify whether you calculated it by summing the sentiment scores for each word or if you weighted it based on the comment’s length.

library(tidyverse)
library(tidytext)

# Inner Join with AFINN Lexicon
afinn <- nyt_tidy %>%
  inner_join(get_sentiments("afinn"), by = "word") %>%
  # Grouping by Comment ID
  group_by(ID) %>%
  # Summing Sentiment Scores
  summarise(sentiment = sum(value)) %>%
  # Adding a Dictionary Identifier
  mutate(dict = "AFINN")

# Display the resulting data frame
print(head(afinn))
## # A tibble: 6 × 3
##      ID sentiment dict 
##   <int>     <dbl> <chr>
## 1     1        -1 AFINN
## 2     2         0 AFINN
## 3     3         5 AFINN
## 4     4        -7 AFINN
## 5     5        -2 AFINN
## 6     6        -4 AFINN

The sentiment score was calculated by summing the sentiment scores assigned to individual words in each comment based on the valence-based AFINN lexicon. The AFINN lexicon assigns numeric scores to words indicating their sentiment polarity, with positive scores for positive sentiment and negative scores for negative sentiment. The sentiment score for a comment is obtained by summing these individual word scores, providing an overall sentiment measure for the comment.

Question III.

Using the sentiment score you calculated based on the AFINN lexicon as above, compare the sentiment score during the Trump administration (before or on 2021-01-20) and Biden administration (after 2021-01-20) utilizing a boxplot with ggplot2 (or any other types of visualization you find suitable). Share your observations and insights based on the visualization.

# Merge the AFINN scores with nyt_data
nyt_afinn <- nyt_data %>%
  select(c("ID", "Date", "clean_comment")) %>%
  merge(afinn, by = "ID", all.x = T) %>%
  mutate(
    wordcount = str_count(clean_comment, "\\w+"),
    sen_ave = sentiment / wordcount
  )

# Set Condition
nyt_afinn <- nyt_afinn %>%
  mutate(administration = ifelse(Date <= as.Date("2021-01-20"), "Trump", "Biden"))


# ggplot
ggplot(nyt_afinn, aes(x = administration, y = sen_ave, fill = administration)) +
  geom_boxplot() +
  labs(
    title = 'Comparison of Sentiment Scores between Trump and Biden',
    x = 'Administration',
    y = 'Sentiment Score'
  ) +
  scale_fill_manual(values = c("Trump" = "red", "Biden" = "blue")) +  # Adjust fill colors if needed
  theme_bw()

Observations:

  1. Box at 0 for Both Administrations:

The fact that the boxes for both Trump and Biden administrations are centered around 0 suggests that, on average, sentiments expressed in the text data are neutral.

  1. Median Position:

The position of the median line relative to 0 is crucial. A median line below 0 for Biden indicates that, despite the overall neutrality, there is a slight tendency towards negative sentiments. For Trump, the median coincides with 0, suggesting a more balanced distribution of positive and negative sentiments.

  1. Variability

Concentration around +1 and +2 in the upper range for Trump suggests that a significant portion of the sentiment scores during his administration is neutral or more positive, while the opposite is true for Biden.

Question IV.

Now, let’s explore a polarity-based lexicon, specifically the Bing, which measures sentiment with a binary category (positive and negative). Similarly, provide an explanation of how you interpreted sentiment in this context. Specify whether you derived a single sentiment score from positive and negative scores or retained both positive and negative scores. If the latter, clarify whether you used the sum for each sentiment type or if you weighted them based on the comment’s length.

bing <- nyt_tidy %>%
  inner_join(get_sentiments("bing"), by = "word") %>% 
  count(ID, sentiment) %>%
  pivot_wider(names_from = sentiment, values_from = n, values_fill = 0) %>% 
  mutate(dict = "BING")

The code above using the Bing lexicon counts the occurrences of positive and negative sentiments separately for each comment. It does not derive a single sentiment score but keeps both positive and negative counts in separate columns.

bing <- nyt_tidy %>%
  inner_join(get_sentiments("bing"), by = "word") %>% 
  count(ID, sentiment) %>%
  pivot_wider(names_from = sentiment, values_from = n, values_fill = 0) %>% 
  mutate(dict = "BING") %>%
  mutate(
    total_words = rowSums(select(., contains("BING"))),  # Total words in the comment
    sentiment_score = (positive - negative) / total_words  # Calculate sentiment score
  )

In the provided code snippet, sentiment analysis is conducted using the Bing lexicon, which classifies words into positive and negative sentiments. Unlike a simplistic approach of deriving a single sentiment score per comment, this code retains both positive and negative scores for a more nuanced analysis. The sentiment scores are tallied separately for positive and negative sentiments and organized into a structured format. To generate a comprehensive sentiment understanding, the code introduces a ‘sentiment_score’ column, computed as the normalized difference between positive and negative scores, divided by the total number of words in each comment. This nuanced approach considers the comment’s length, aiming to provide a more refined interpretation of sentiment on a per-word basis. This methodology goes beyond a mere sum or weighted sum of positive and negative scores, offering a more intricate and context-aware sentiment analysis.

Question V.

Utilizing the positive and negative scores generated from the Bing lexicon as described above, conduct a separate comparison of positive and negative scores during the Trump administration (before or on 2021-01-20) and Biden administration (after 2021-01-20) using boxplot with ggplot2(or any other types of visualization you find suitable). Share your observations and insights based on the visualization.

# Create a new data frame merging nyt_data with bing sentiment scores
nyt_bing <- nyt_data %>%
  select(c("ID", "Date", "clean_comment")) %>%
  merge(bing, by = "ID", all.x = TRUE) %>%
  mutate(
    wordcount = str_count(clean_comment, "\\w+"),
    pos_ave = positive / wordcount,
    neg_ave = negative / wordcount,
    sen_ave = (positive - negative) / (positive + negative)
  )

# Define Condition again
nyt_bing <- nyt_bing %>%
  mutate(administration = ifelse(Date <= as.Date("2021-01-20"), "Trump", "Biden"))

# ggplot
nyt_bing %>%
  select(c("ID", "positive", "negative", "administration")) %>%
  pivot_longer(!c(ID, administration), names_to = "sentiment", values_to = "value") %>%
  ggplot(aes(x = sentiment, y = value, color = sentiment)) +
  geom_boxplot() +
  theme_bw() +
  facet_wrap(~administration) +  # Add facet for Trump and Biden
  labs(
    title = "Distribution of Positive and Negative Sentiment Scores",
    x = "Sentiment Type",
    y = "Sentiment Score"
  )

Observations:

  1. Trump Administration:

Wider distribution of positive and negative sentiment scores. Presence of outliers for negative comments.

  1. Biden Administration:

Concentration of comments between 5-15 sentiment score for both positive and negative sentiments. Few outliers for negative sentiment, mostly between 20 and 30.

  1. General Observation:

Biden administration shows a trend towards less extreme sentiments. Significant proportion of comments in both administrations had moderate sentiment.

PART III: Topic Modeling

Question I.

Begin by pre-processing the clean_text column and preparing the documents to ensure they are ready for structural topic modeling. Start by pre-processing the clean_text column to ready the documents for structural topic modeling. Proceed to fit a 5-topic model, incorporating the co variate Category in the formula.

Question II.

Examine these five topics, and try you best to label those topics based on the top words (either based on the Highest Probability or the FREX score) and the top documents associated with a topic. If you are not able to label some of the topics, just leave them as non-meaningful topics (tip: labelTopics() and findThoughts() function)

# Load the required library
library(stm)

## Question 1

# Pre-processing
system.time(
processed_nyt <- textProcessor(nyt_data$clean_comment, 
                                 metadata=nyt_data,
                                 lowercase = TRUE,
                                 removestopwords = TRUE, 
                                 removenumbers = TRUE,
                                 removepunctuation = TRUE,
                                 stem = TRUE,
                                 wordLengths = c(3,Inf),
                                 sparselevel = 1,
                                 language = "en",
                                 verbose = TRUE, 
                                 striphtml = FALSE,
                                 v1 = FALSE)
)
## Building corpus... 
## Converting to Lower Case... 
## Removing punctuation... 
## Removing stopwords... 
## Removing numbers... 
## Stemming... 
## Creating Output...
##    user  system elapsed 
##  10.224   0.107  10.582
system.time(
nyt_output <- prepDocuments(processed_nyt$documents, processed_nyt$vocab, processed_nyt$meta)
)
## Removing 5507 of 10627 terms (5507 of 123282 tokens) due to frequency 
## Removing 58 Documents with No Words 
## Your corpus now has 8434 documents, 5120 terms and 117775 tokens.
##    user  system elapsed 
##   3.122   0.526   3.685
#  Fit a 5-topic model
nyt_5 <-stm(nyt_output$documents, nyt_output$vocab, data=nyt_output$meta, 
               K = 5, prevalence= ~ Category,
               seed = 123, verbose = T,
               max.em.its = 50, init.type = "Spectral")
## Beginning Spectral Initialization 
##   Calculating the gram matrix...
##   Finding anchor words...
##      .....
##   Recovering initialization...
##      ...................................................
## Initialization complete.
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 1 (approx. per word bound = -7.380) 
## ....................................................................................................
## Completed E-Step (1 seconds). 
## Completed M-Step. 
## Completing Iteration 2 (approx. per word bound = -7.273, relative change = 1.454e-02) 
## ....................................................................................................
## Completed E-Step (1 seconds). 
## Completed M-Step. 
## Completing Iteration 3 (approx. per word bound = -7.225, relative change = 6.613e-03) 
## ....................................................................................................
## Completed E-Step (1 seconds). 
## Completed M-Step. 
## Completing Iteration 4 (approx. per word bound = -7.202, relative change = 3.145e-03) 
## ....................................................................................................
## Completed E-Step (1 seconds). 
## Completed M-Step. 
## Completing Iteration 5 (approx. per word bound = -7.190, relative change = 1.682e-03) 
## Topic 1: peopl, one, get, think, see 
##  Topic 2: like, will, world, presid, state 
##  Topic 3: countri, johnni, pandem, now, american 
##  Topic 4: covid, death, time, america, happen 
##  Topic 5: trump, just, virus, china, video 
## ....................................................................................................
## Completed E-Step (1 seconds). 
## Completed M-Step. 
## Completing Iteration 6 (approx. per word bound = -7.183, relative change = 9.960e-04) 
## ....................................................................................................
## Completed E-Step (1 seconds). 
## Completed M-Step. 
## Completing Iteration 7 (approx. per word bound = -7.178, relative change = 6.379e-04) 
## ....................................................................................................
## Completed E-Step (1 seconds). 
## Completed M-Step. 
## Completing Iteration 8 (approx. per word bound = -7.175, relative change = 4.341e-04) 
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 9 (approx. per word bound = -7.173, relative change = 3.097e-04) 
## ....................................................................................................
## Completed E-Step (1 seconds). 
## Completed M-Step. 
## Completing Iteration 10 (approx. per word bound = -7.171, relative change = 2.297e-04) 
## Topic 1: peopl, one, get, think, see 
##  Topic 2: like, will, world, presid, state 
##  Topic 3: countri, johnni, pandem, now, american 
##  Topic 4: covid, death, time, america, happen 
##  Topic 5: trump, just, virus, china, video 
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 11 (approx. per word bound = -7.170, relative change = 1.758e-04) 
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 12 (approx. per word bound = -7.169, relative change = 1.379e-04) 
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 13 (approx. per word bound = -7.168, relative change = 1.104e-04) 
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 14 (approx. per word bound = -7.167, relative change = 8.999e-05) 
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 15 (approx. per word bound = -7.167, relative change = 7.451e-05) 
## Topic 1: peopl, one, get, think, see 
##  Topic 2: like, will, world, presid, state 
##  Topic 3: countri, johnni, pandem, now, american 
##  Topic 4: covid, death, time, america, happen 
##  Topic 5: trump, just, virus, china, video 
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 16 (approx. per word bound = -7.166, relative change = 6.261e-05) 
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 17 (approx. per word bound = -7.166, relative change = 5.323e-05) 
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 18 (approx. per word bound = -7.166, relative change = 4.574e-05) 
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 19 (approx. per word bound = -7.165, relative change = 3.967e-05) 
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 20 (approx. per word bound = -7.165, relative change = 3.472e-05) 
## Topic 1: peopl, one, get, think, see 
##  Topic 2: like, will, world, presid, state 
##  Topic 3: countri, johnni, pandem, now, case 
##  Topic 4: covid, death, time, america, happen 
##  Topic 5: trump, just, virus, china, video 
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 21 (approx. per word bound = -7.165, relative change = 3.059e-05) 
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 22 (approx. per word bound = -7.165, relative change = 2.716e-05) 
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 23 (approx. per word bound = -7.165, relative change = 2.426e-05) 
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 24 (approx. per word bound = -7.164, relative change = 2.182e-05) 
## ....................................................................................................
## Completed E-Step (3 seconds). 
## Completed M-Step. 
## Completing Iteration 25 (approx. per word bound = -7.164, relative change = 1.979e-05) 
## Topic 1: peopl, one, get, think, see 
##  Topic 2: like, will, world, presid, state 
##  Topic 3: countri, johnni, pandem, now, case 
##  Topic 4: covid, death, time, america, happen 
##  Topic 5: trump, just, virus, china, video 
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 26 (approx. per word bound = -7.164, relative change = 1.809e-05) 
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 27 (approx. per word bound = -7.164, relative change = 1.668e-05) 
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 28 (approx. per word bound = -7.164, relative change = 1.552e-05) 
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 29 (approx. per word bound = -7.164, relative change = 1.455e-05) 
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 30 (approx. per word bound = -7.164, relative change = 1.376e-05) 
## Topic 1: peopl, one, get, think, see 
##  Topic 2: like, will, world, presid, state 
##  Topic 3: countri, johnni, pandem, now, case 
##  Topic 4: covid, death, time, america, happen 
##  Topic 5: trump, just, virus, china, video 
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 31 (approx. per word bound = -7.164, relative change = 1.306e-05) 
## ....................................................................................................
## Completed E-Step (2 seconds). 
## Completed M-Step. 
## Completing Iteration 32 (approx. per word bound = -7.164, relative change = 1.247e-05) 
## ....................................................................................................
## Completed E-Step (1 seconds). 
## Completed M-Step. 
## Completing Iteration 33 (approx. per word bound = -7.164, relative change = 1.192e-05) 
## ....................................................................................................
## Completed E-Step (1 seconds). 
## Completed M-Step. 
## Completing Iteration 34 (approx. per word bound = -7.163, relative change = 1.140e-05) 
## ....................................................................................................
## Completed E-Step (1 seconds). 
## Completed M-Step. 
## Completing Iteration 35 (approx. per word bound = -7.163, relative change = 1.092e-05) 
## Topic 1: peopl, one, get, think, see 
##  Topic 2: like, will, world, presid, state 
##  Topic 3: countri, johnni, pandem, now, case 
##  Topic 4: covid, death, time, america, happen 
##  Topic 5: trump, just, virus, china, video 
## ....................................................................................................
## Completed E-Step (1 seconds). 
## Completed M-Step. 
## Completing Iteration 36 (approx. per word bound = -7.163, relative change = 1.045e-05) 
## ....................................................................................................
## Completed E-Step (1 seconds). 
## Completed M-Step. 
## Completing Iteration 37 (approx. per word bound = -7.163, relative change = 1.001e-05) 
## ....................................................................................................
## Completed E-Step (1 seconds). 
## Completed M-Step. 
## Model Converged
## Question 2

# Label topics based on the Highest Probability
label_probs <- labelTopics(nyt_5, n = 5)

# Print the labeled topics
print(label_probs)
## Topic 1 Top Words:
##       Highest Prob: peopl, one, get, think, see 
##       FREX: don, need, point, flu, vote 
##       Lift: applic, classifi, coconspir, coffin, distant 
##       Score: peopl, one, get, don, think 
## Topic 2 Top Words:
##       Highest Prob: like, will, world, presid, state 
##       FREX: like, wrong, research, didnt, leader 
##       Lift: charli, forest, game, golden, influenti 
##       Score: like, world, state, will, say 
## Topic 3 Top Words:
##       Highest Prob: countri, johnni, pandem, now, case 
##       FREX: million, end, doesn, yes, continu 
##       Lift: derang, servant, success, continu, doesn 
##       Score: countri, johnni, pandem, now, american 
## Topic 4 Top Words:
##       Highest Prob: covid, death, time, america, happen 
##       FREX: happen, blame, call, polit, back 
##       Lift: anywher, apolog, appoint, bait, buckl 
##       Score: covid, america, death, time, happen 
## Topic 5 Top Words:
##       Highest Prob: trump, just, virus, china, video 
##       FREX: much, still, respons, media, never 
##       Lift: adequ, anyway, avail, award, brief 
##       Score: trump, just, china, video, virus
# Find thoughts (top documents) for each topic
thoughts <- findThoughts(nyt_5, texts = nyt_output$meta$text, n = 5, topics = c(5))

Topic Labels:

  1. Public Opinion and Discussion: Discussing people’s views, thoughts, and the need for perspective.

  2. Global Affairs and Leadership: Covering topics like the world, presidency, and state affairs.

  3. Pandemic and Country Affairs: Focused on the pandemic, country-related issues, and cases.

  4. COVID-19 Impact: Discussing the impact of COVID-19, deaths, and political blame.

  5. Trump’s Influence and Media: Involves discussions about Trump, the virus, China, and media’s role.

Question III.

Finally, let’s investigate the impact of document-level metadata, specifically the covariate Category in this context. Use the estimateEffect() function to assess whether comments posted during the Trump or Biden administration exert an influence on the five identified topics Use stm default plot to show the results.

# Estimate the effect of 'Category' (Trump or Biden) on topics
predicted_category <- estimateEffect(c(1:5) ~ Category, stmobj = nyt_5, 
                                     metadata = nyt_output$meta, uncertainty = "Global")

# Plot the results with the default STM plot
plot(predicted_category, covariate = "Category", topics = c(1:5), method = "difference",
     cov.value1 = "Biden", cov.value2 = "Trump",
     main = "Differences between Trump and Biden Admin Topic Proportion",
     xlab = "Trump           Biden",
     labeltype = "custom",
     custom.labels = c("Topic 1", "Topic 2", "Topic 3", "Topic 4", "Topic 5"))