Assignment 6

Author

Brennan Stout

Published

October 27, 2026

Report

###Tweets: ##Background: This summit was a notable meeting between the Chinese and US leaders to try and defuse some of the tensions which had been building during that time. It resulted in generally a favorable aspect between the two leaders. In the comparisons of the tweets which came out about that time, it is not overly surprising that the Xi administration linked to terms related to China more and the US administration linked to terms related to the US. The interesting part comes from the comparison of the use terms which came out of the summit, even as the tweets tend to be a rather limited view of the situation and biased to a given topic as the tweets gathered were all in English. From the documents it can be seen that both sides were using generally positive terms in regards to the situation, like relationship compromise and deepening. However, amusingly China referred to itself more than anything other while the US had nations as their most used term.

###Quantitative Text Analysis In the comparison of the presidential inaugural addresses, this is being done on length, word diversity, and readability. Additionally, these addresses can be understood on the cosine similarity and keyness by party. In terms of length, which can be can be understood in the number of tokens needed to process the address. However, despite the want of politicians to talk the number of tokens has not changed overly much across all the addresses. The one which has changed greatly is that of the word choice and complexity. As the decades have moved, and the understanding of who the address is aimed at has changed there is a notable drop in the complexity of the language being used measured in US grade level. Even despite this, there are still a lot of consistent words which will continue to be used between addresses and even addresses of a similar era will remain generally consistent. For example, topics like jobs or drugs will be usually relegated to more modern speakers, but terms like government or people are very often present with good reason. These are notable and well crafted address which are meant to be a summation of nation concerns and the beginning of some era of change, but these sorts of consistencies between addresses point to an amusing level of irony behind that particular concept.

Data Note: CPD collection

source: GovInfo Permission: Agreement Query: API Selection: 2021-01-20 forward gaps: Only goverment documents

Tweet and API comparison

GovInfo Compilation of Presidential Documents (CPD) & Xi-Biden Summit Tweets Description: 1. Collect every document from the Compilation of Presidential Documents (CPD) collection mentioning “Xi Jinping” since 20 January 2021 via the GovInfo Search API. 2. Analyzes the November 2021 Biden-Xi virtual summit tweets dataset using quanteda: - Keywords-in-Context (kwic()) around President Xi and summit discussions. - Differential keyness (textstat_keyness()) comparing rhetorical framing between the Biden and Xi administrations.

suppressPackageStartupMessages({
  library(httr2)
  library(jsonlite)
  library(readr)
  library(dplyr)
  library(stringr)
  library(quanteda)
  library(quanteda.textstats)
  library(quanteda.textplots)
  library(ggplot2)
})
Warning: package 'httr2' was built under R version 4.5.3
Warning: package 'jsonlite' was built under R version 4.5.3
Warning: package 'readr' was built under R version 4.5.3
Warning: package 'dplyr' was built under R version 4.5.3
Warning: package 'stringr' was built under R version 4.5.3
Warning: package 'quanteda' was built under R version 4.5.3
Warning: package 'quanteda.textstats' was built under R version 4.5.3
Warning: package 'quanteda.textplots' was built under R version 4.5.3
Warning: package 'ggplot2' was built under R version 4.5.3
api_key <- Sys.getenv("GOVINFO_API_KEY")
if (api_key == "") {
  warning("GOVINFO_API_KEY environment variable not set. Falling back to DEMO_KEY (subject to strict rate limits).")
  api_key <- "DEMO_KEY"
}
save_dir <- "govInfo_CPD_Xi"
if (!dir.exists(save_dir)) {
  dir.create(save_dir, recursive = TRUE)
}

search_query <- 'collection:(CPD) AND "Xi Jinping" AND publishdate:range(2021-01-20,)'
all_records <- list()
offset_mark <- "*"
page_size   <- 100
page_count  <- 1
total_count <- NA

repeat {
  message(sprintf("--> Fetching page %d (offsetMark: %s)...", page_count, offset_mark))
  
  req_body <- list(
    query      = search_query,
    pageSize   = page_size,
    offsetMark = offset_mark,
    sorts      = list(list(field = "publishdate", sortOrder = "DESC"))
  )
  
  resp <- tryCatch({
    request("https://api.govinfo.gov/search") |>
      req_url_query(api_key = api_key) |>
      req_body_json(req_body) |>
      req_perform() |>
      resp_body_json()
  }, error = function(e) {
    message("Error during API request: ", conditionMessage(e))
    NULL
  })
  
  if (is.null(resp) || is.null(resp$results) || length(resp$results) == 0) {
    message("No more records returned from API.")
    break
  }
  
  if (is.na(total_count) && !is.null(resp$count)) {
    total_count <- resp$count
    message(sprintf("Total matching CPD documents identified in GovInfo: %d", total_count))
  }
  
  batch <- resp$results
  all_records <- c(all_records, batch)
  message(sprintf("    Retrieved %d records (running total: %d of %s)", 
                  length(batch), length(all_records), ifelse(is.na(total_count), "?", as.character(total_count))))
  next_offset <- resp$offsetMark
  if (is.null(next_offset) || next_offset == offset_mark || 
      (!is.na(total_count) && length(all_records) >= total_count)) {
    message("Reached final page of search results.")
    break
  }
  
  offset_mark <- next_offset
  page_count  <- page_count + 1
  Sys.sleep(0.5) # politeness buffer
}
--> Fetching page 1 (offsetMark: *)...
Total matching CPD documents identified in GovInfo: 351
    Retrieved 100 records (running total: 100 of 351)
--> Fetching page 2 (offsetMark: AoJw4I72sJkDLkRDUEQtMjAyNTAwOTI5)...
    Retrieved 100 records (running total: 200 of 351)
--> Fetching page 3 (offsetMark: AoJw4K32nIwDLkRDUEQtMjAyMzAxMDc4)...
    Retrieved 100 records (running total: 300 of 351)
--> Fetching page 4 (offsetMark: AoJw4NO84P8CLkRDUEQtMjAyMjAwMjA4)...
    Retrieved 51 records (running total: 351 of 351)
Reached final page of search results.
download_log <- lapply(seq_along(all_records), function(i) {
  item <- all_records[[i]]
  pkg_id <- item$packageId
  
  pdf_url <- if (!is.null(item$download$pdfLink)) {
    item$download$pdfLink
  } else {
    paste0("https://api.govinfo.gov/packages/", pkg_id, "/pdf")
  }
  
  file_name <- paste0(pkg_id, ".pdf")
  dest_path <- file.path(save_dir, file_name)
  if (file.exists(dest_path) && file.size(dest_path) > 0) {
    status <- "Already Downloaded"
  } else {
    status <- tryCatch({
      request(pdf_url) |>
        req_url_query(api_key = api_key) |>
        req_perform(path = dest_path)
      "Success"
    }, error = function(e) {
      conditionMessage(e)
    })
    Sys.sleep(0.2)
  }
  
  data.frame(
    index        = i,
    package_id   = pkg_id,
    date_issued  = if (!is.null(item$dateIssued)) item$dateIssued else NA_character_,
    title        = if (!is.null(item$title)) item$title else NA_character_,
    collection   = if (!is.null(item$collectionCode)) item$collectionCode else "CPD",
    pdf_url      = pdf_url,
    file_path    = dest_path,
    size_mb      = if (file.exists(dest_path)) round(file.size(dest_path) / (1024^2), 2) else NA_real_,
    status       = status,
    stringsAsFactors = FALSE
  )
})

download_table <- do.call(rbind, download_log)

metadata_file <- file.path(save_dir, "cpd_xi_jinping_collection_log.csv")
write.csv(download_table, metadata_file, row.names = FALSE)

print(head(download_table[, c("package_id", "date_issued", "title", "size_mb", "status")], 10), row.names = FALSE)
         package_id date_issued
    DCPD-2026DIGEST  2026-10-16
 DCPD-2026CHECKLIST  2026-10-16
     DCPD-202600638  2026-09-24
     DCPD-202600636  2026-09-24
     DCPD-202600635  2026-09-23
     DCPD-202600631  2026-09-22
     DCPD-202600630  2026-09-22
     DCPD-202600620  2026-09-18
     DCPD-202600601  2026-09-12
     DCPD-202600598  2026-09-11
                                                                                                                              title
                                                                                          Digest of Other White House Announcements
                                                                                            Checklist of White House Press Releases
                                                                   Remarks at a State Dinner Honoring President Xi Jinping of China
                                                                  Remarks at a Welcoming Ceremony for President Xi Jinping of China
                                               Remarks in an Exchange With Reporters Upon Arrival From Joint Base Andrews, Maryland
             Remarks Prior to a Meeting With Prime Minister Sanae Takaichi of Japan and an Exchange With Reporters in New York City
 Remarks Following a Meeting With Prime Minister Andy Burnham of the United Kingdom and an Exchange With Reporters in New York City
                                                                 Remarks on Prescription Drug Prices and an Exchange With Reporters
                                                 Remarks to United States Embassy Personnel and Business Leaders in Dublin, Ireland
                    Presidential Determination on Major Drug Transit or Major Illicit Drug Producing Countries for Fiscal Year 2027
 size_mb             status
    0.80 Already Downloaded
    0.33 Already Downloaded
    0.24 Already Downloaded
    0.23 Already Downloaded
    0.24 Already Downloaded
    0.23 Already Downloaded
    0.26 Already Downloaded
    0.34 Already Downloaded
    0.28 Already Downloaded
    0.25 Already Downloaded
### Pt2
summit_url <- "https://raw.githubusercontent.com/datageneration/datamethods/master/textanalytics/summit_11162021.csv"
summit <- read_csv(summit_url, show_col_types = FALSE)

summit_clean <- summit %>%
  filter(!is.na(text) & text != "") %>%
  filter(is.na(lang) | lang == "en") %>%
  distinct(text, .keep_all = TRUE)

tweet_corpus <- corpus(summit_clean, text_field = "text")

custom_stops <- c(
  stopwords("english"),
  "rt", "https", "t.co", "amp", "via", "re", "co", "http",
  "u", "ur", "tweet", "twitter", "video", "photo", "status"
)

toks <- tokens(
  tweet_corpus,
  remove_punct   = TRUE,
  remove_symbols = TRUE,
  remove_numbers = TRUE,
  remove_url     = TRUE
) %>%
  tokens_tolower() %>%
  tokens_remove(custom_stops)


xi_kwic <- kwic(toks, pattern = "xi", window = 5)
cat(sprintf("Total occurrences of 'xi' in summit tweets: %d\n", nrow(xi_kwic)))
Total occurrences of 'xi' in summit tweets: 3314
print(head(as.data.frame(xi_kwic)[, c("pre", "keyword", "post")], 10), row.names = FALSE)
                                      pre keyword
   president biden communist china leader      xi
  biden urges guardrails conflict virtual      xi
  president joe biden chinese counterpart      xi
       biden opens virtual summit china's      xi
  breakthrough first virtual summit biden      xi
    held virtual summit chinese president      xi
                                joe biden      xi
   china unleashing covid-19 world summit      xi
    #xijinping virtual summit #biden told      xi
 bosses you’ll realize just condescending      xi
                                    post
   jinpig pledged virtual summit improve
                                  summit
 jinping expected discuss damage control
 white house #breakingnews #biden #china
         biden said u.s.will work dvance
       jinping historic meeting man runs
    jinping kick virtual summit expected
                                 jinping
  #america sever relations impose severe
 biden summit interaction especially old
xi_phrase_kwic <- kwic(toks, pattern = phrase("xi jinping"), window = 5)
cat(sprintf("\nTotal occurrences of phrase 'xi jinping': %d\n", nrow(xi_phrase_kwic)))

Total occurrences of phrase 'xi jinping': 1202
print(head(as.data.frame(xi_phrase_kwic)[, c("pre", "keyword", "post")], 10), row.names = FALSE)
                                           pre    keyword
       president joe biden chinese counterpart xi jinping
         held virtual summit chinese president xi jinping
                                     joe biden xi jinping
        china unleashing covid-19 world summit xi jinping
         president joe biden chinese president xi jinping
         hold virtual summit chinese president xi jinping
 us maintaining close communication facilitate xi jinping
       president biden tells chinese president xi jinping
       joe biden criticised decision president xi jinping
                                     joe biden xi jinping
                                         post
       expected discuss damage control rather
             historic meeting man runs united
            kick virtual summit expected last
                                             
                                             
                                       monday
             joe biden virtual summit chinese
 looking forward candid forthright discussion
         attend glasgow summit accusing china
              discuss complex nature ties two
multi_kwic <- kwic(toks, pattern = c("xi", "biden", "summit", "taiwan"), window = 4)
print(head(as.data.frame(multi_kwic)[, c("keyword", "pre", "post")], 12), row.names = FALSE)
 keyword                               pre                              post
   biden        breaking news us president         communist china leader xi
      xi      biden communist china leader     jinpig pledged virtual summit
  summit         xi jinpig pledged virtual improve cooperation china offered
   biden                             recap urges guardrails conflict virtual
      xi urges guardrails conflict virtual                            summit
  summit    guardrails conflict virtual xi                                  
   biden                 u.s president joe    chinese counterpart xi jinping
      xi     joe biden chinese counterpart   jinping expected discuss damage
  summit        key differences main focus       later today washington time
   biden                         #breaking      opens virtual summit china's
  summit     #breaking biden opens virtual            china's xi white house
      xi      opens virtual summit china's  white house #breakingnews #biden
# g_dispersion <- textplot_xray(
#   kwic(toks, pattern = "xi"),
#   kwic(toks, pattern = "biden"),
#   kwic(toks, pattern = "summit"),
#   kwic(toks, pattern = "taiwan")
# ) +
#   theme_bw() +
#   labs(title = "Lexical Dispersion of Summit Keywords Across Tweet Stream",
#        x = "Token Position in Corpus", y = "Keyword")
# print(g_dispersion)

biden_regex <- "\\b(biden|joe|potus|whitehouse|washington|us|u\\.s|usa|america|american)\\b"
xi_regex    <- "\\b(xi|jinping|china|chinese|beijing|ccp|prc)\\b"

raw_texts <- tolower(as.character(tweet_corpus))
has_biden <- str_detect(raw_texts, biden_regex)
has_xi    <- str_detect(raw_texts, xi_regex)

docvars(tweet_corpus, "admin_focus") <- case_when(
  has_biden & !has_xi ~ "Biden_Admin",
  !has_biden & has_xi ~ "Xi_Admin",
  has_biden & has_xi  ~ "Bilateral",
  TRUE                ~ "Other"
)

cat("Distribution of tweets by administration focus:\n")
Distribution of tweets by administration focus:
print(table(docvars(tweet_corpus, "admin_focus")))

Biden_Admin   Bilateral       Other    Xi_Admin 
         82        4424         264         133 
contrast_corpus <- corpus_subset(tweet_corpus, admin_focus %in% c("Biden_Admin", "Xi_Admin"))

contrast_toks <- tokens(
  contrast_corpus,
  remove_punct   = TRUE,
  remove_symbols = TRUE,
  remove_numbers = TRUE,
  remove_url     = TRUE
) %>%
  tokens_tolower() %>%
  tokens_remove(c(custom_stops, "biden", "xi", "jinping", "president", "summit", "virtual")) 
contrast_dfm <- dfm(contrast_toks) %>%
  dfm_trim(min_termfreq = 3) %>%
  dfm_group(groups = admin_focus)

keyness_biden_vs_xi <- textstat_keyness(contrast_dfm, target = "Biden_Admin", measure = "chi2")

cat("\nTop 15 distinctive features for the Biden Administration (positive chi2):\n")

Top 15 distinctive features for the Biden Administration (positive chi2):
print(head(keyness_biden_vs_xi, 15), row.names = FALSE)
      feature     chi2            p n_target n_reference
      nations 49.16747 2.350120e-12       28           1
 relationship 32.05326 1.500035e-08       19           1
   guardrails 30.02292 4.269695e-08       16           0
          set 30.02292 4.269695e-08       16           0
          two 28.28791 1.045469e-07       32          12
  complicated 23.43655 1.291024e-06       14           0
    deepening 23.43655 1.291024e-06       14           0
       stress 23.43655 1.291024e-06       14           0
     conflict 23.25370 1.419768e-06       19           4
        areas 22.65790 1.935631e-06       14           1
        looks 22.65790 1.935631e-06       14           1
           us 19.67849 9.162673e-06       12           0
 increasingly 19.58965 9.598761e-06       14           2
         need 15.87721 6.758757e-05       16           5
        crude 14.06860 1.762623e-04        9           0
cat("\nTop 15 distinctive features for the Xi Administration (negative chi2 / reference):\n")

Top 15 distinctive features for the Xi Administration (negative chi2 / reference):
print(tail(keyness_biden_vs_xi, 15), row.names = FALSE)
    feature       chi2            p n_target n_reference
     states  -7.992695 4.696646e-03        1          19
     united  -7.992695 4.696646e-03        1          19
     counts  -8.137653 4.335537e-03        0          15
        win  -8.137653 4.335537e-03        0          15
    without  -8.137653 4.335537e-03        0          15
        nyt  -8.637776 3.292631e-03        2          24
      still  -8.685178 3.208083e-03        0          16
 compromise  -9.233335 2.376484e-03        0          17
       york -10.699596 1.071589e-03        1          24
     #china -10.881617 9.712341e-04        0          20
        lee -13.088255 2.971530e-04        0          24
      myers -13.088255 2.971530e-04        0          24
     steven -13.088255 2.971530e-04        0          24
        new -13.437176 2.466866e-04        1          29
      china -43.913095 3.432843e-11        0          78
# Comparison plot
keyness_plot <- textplot_keyness(
  keyness_biden_vs_xi,
  n = 20,
  margin = 0.2,
  color = c("dodgerblue3", "firebrick2")
) +
  theme_minimal() +
  labs(
    title = "Differential Keyness: Biden Administration vs. Xi Administration",
    subtitle = "Analysis of Rhetorical Framing in Summit Tweets (target = Biden Admin; reference = Xi Admin)",
    x = "Chi-squared Keyness Statistic"
  )

# Display plot
print(keyness_plot)

Quantitative Text Analysis of U.S. Presidential Inaugural Addresses

Using quanteda: Length, Lexical Diversity, Readability, Cosine Similarity, Keyness by Party, and Wordfish Scaling (textmodel_wordfish)

suppressPackageStartupMessages({
  library(quanteda)
  library(quanteda.textmodels)
  library(tidyr)
  library(tibble)
})
Warning: package 'quanteda.textmodels' was built under R version 4.5.3
Warning: package 'tidyr' was built under R version 4.5.3
inaug_corpus <- data_corpus_inaugural

summary_info <- summary(inaug_corpus, n = 5)
print(summary_info)
corpus of 60 documents, showing 5 documents:

            Text Types Tokens Sentences Year  President FirstName
 1789-Washington   625   1537        24 1789 Washington    George
 1793-Washington    96    147         5 1793 Washington    George
      1797-Adams   826   2577        37 1797      Adams      John
  1801-Jefferson   717   1923        43 1801  Jefferson    Thomas
  1805-Jefferson   804   2380        45 1805  Jefferson    Thomas
                 Party
                  none
                  none
            Federalist
 Democratic-Republican
 Democratic-Republican
raw_toks <- tokens(inaug_corpus)

clean_toks <- tokens(
  inaug_corpus,
  remove_punct   = TRUE,
  remove_symbols = TRUE,
  remove_numbers = TRUE
) %>%
  tokens_tolower() %>%
  tokens_remove(stopwords("english"))

inaug_dfm <- dfm(clean_toks)

metrics_df <- data.frame(
  doc_id    = docnames(inaug_corpus),
  Year      = docvars(inaug_corpus, "Year"),
  President = docvars(inaug_corpus, "President"),
  Party     = docvars(inaug_corpus, "Party"),
  Length    = ntoken(inaug_corpus),
  Types     = ntype(inaug_corpus),
  stringsAsFactors = FALSE
)
Warning: `ntoken.corpus()` was deprecated in quanteda 4.0.
ℹ Please use `ntoken(tokens(x))` instead.
Warning: `ntype.corpus()` was deprecated in quanteda 4.0.
ℹ Please use `ntoken(tokens(x))` instead.
cat("\nTop 5 Longest Inaugural Addresses:\n")

Top 5 Longest Inaugural Addresses:
print(head(metrics_df[order(-metrics_df$Length), c("Year", "President", "Length")], 5), row.names = FALSE)
 Year President Length
 1841  Harrison   9125
 1909      Taft   5821
 1845      Polk   5186
 1821    Monroe   4886
 1889  Harrison   4721
cat("\nTop 5 Shortest Inaugural Addresses:\n")

Top 5 Shortest Inaugural Addresses:
print(head(metrics_df[order(metrics_df$Length), c("Year", "President", "Length")], 5), row.names = FALSE)
 Year  President Length
 1793 Washington    147
 1945  Roosevelt    633
 1865    Lincoln    775
 1905  Roosevelt   1079
 1849     Taylor   1178
p_length <- ggplot(metrics_df, aes(x = Year, y = Length, color = Party)) +
  geom_point(size = 2.5, alpha = 0.8) +
  geom_smooth(method = "loess", color = "darkgray", se = FALSE, linetype = "dashed") +
  theme_minimal() +
  labs(
    title = "Length of U.S. Presidential Inaugural Addresses Over Time",
    subtitle = "Word count measured by ntoken(); historical peak in 1841 (W.H. Harrison)",
    x = "Year", y = "Token Count"
  )
print(p_length)
`geom_smooth()` using formula = 'y ~ x'

lexdiv_res <- textstat_lexdiv(
  inaug_dfm,
  measure = c("TTR", "C", "R")
)

metrics_df$TTR  <- lexdiv_res$TTR
metrics_df$Root_TTR <- lexdiv_res$R

cat("\nSample Lexical Diversity (TTR) Scores:\n")

Sample Lexical Diversity (TTR) Scores:
print(head(metrics_df[, c("Year", "President", "Length", "TTR")], 6), row.names = FALSE)
 Year  President Length       TTR
 1789 Washington   1537 0.7806748
 1793 Washington    147 0.9354839
 1797      Adams   2577 0.6542056
 1801  Jefferson   1923 0.7293973
 1805  Jefferson   2380 0.6726014
 1809    Madison   1261 0.8326996
p_lexdiv <- ggplot(metrics_df, aes(x = Year, y = TTR)) +
  geom_point(aes(color = Party), size = 2.5) +
  geom_smooth(method = "loess", se = TRUE, color = "steelblue") +
  theme_minimal() +
  labs(
    title = "Lexical Diversity (TTR) Across Inaugural Addresses",
    subtitle = "Vocabulary repetition vs. richness across historical eras",
    x = "Year", y = "Type-Token Ratio (TTR)"
  )
print(p_lexdiv)
`geom_smooth()` using formula = 'y ~ x'

readability_res <- textstat_readability(
  inaug_corpus,
  measure = c("Flesch.Kincaid", "Flesch")
)

metrics_df$Flesch_Kincaid <- readability_res$Flesch.Kincaid
metrics_df$Flesch_Ease    <- readability_res$Flesch

cat("\nReadability by Era (Flesch-Kincaid Grade Level):\n")

Readability by Era (Flesch-Kincaid Grade Level):
cat("Earliest 5 Speeches Mean Grade Level:", 
    round(mean(head(metrics_df$Flesch_Kincaid, 5)), 1), "\n")
Earliest 5 Speeches Mean Grade Level: 23.1 
cat("Latest 5 Speeches Mean Grade Level:", 
    round(mean(tail(metrics_df$Flesch_Kincaid, 5)), 1), "\n")
Latest 5 Speeches Mean Grade Level: 9.3 
p_readability <- ggplot(metrics_df, aes(x = Year, y = Flesch_Kincaid)) +
  geom_point(aes(color = Party), size = 2.5) +
  geom_smooth(method = "lm", se = TRUE, color = "firebrick") +
  theme_minimal() +
  labs(
    title = "Historical Decline in Inaugural Address Reading Level",
    subtitle = "Flesch-Kincaid Grade Level steadily dropped from collegiate/graduate to 8th-10th grade",
    x = "Year", y = "Flesch-Kincaid Grade Level (U.S. School Grade)"
  )
print(p_readability)
`geom_smooth()` using formula = 'y ~ x'

dfm_trimmed <- dfm_trim(inaug_dfm, min_termfreq = 5, min_docfreq = 3)

cos_matrix <- as.matrix(textstat_simil(dfm_trimmed, method = "cosine"))

n_docs <- nrow(cos_matrix)
predecessor_sim <- numeric(n_docs)
predecessor_sim[1] <- NA

for (i in 2:n_docs) {
  predecessor_sim[i] <- cos_matrix[i, i - 1]
}
metrics_df$Predecessor_Sim <- predecessor_sim

p_sim <- ggplot(na.omit(metrics_df), aes(x = Year, y = Predecessor_Sim)) +
  geom_line(color = "darkgray") +
  geom_point(aes(color = Party), size = 2.5) +
  theme_minimal() +
  labs(
    title = "Rhetorical Continuity with Immediate Predecessor",
    subtitle = "Cosine similarity between consecutive inaugural addresses over time",
    x = "Year", y = "Cosine Similarity"
  )
print(p_sim)

postwar_corpus <- corpus_subset(inaug_corpus, Year >= 1945)
postwar_dfm <- tokens(postwar_corpus, remove_punct = TRUE, remove_numbers = TRUE) %>%
  tokens_tolower() %>%
  tokens_remove(stopwords("english")) %>%
  dfm() %>%
  dfm_group(groups = President)

postwar_sim <- textstat_simil(postwar_dfm, method = "cosine")
cat("\nCosine Similarity Matrix Among Post-WWII Presidents (Sample):\n")

Cosine Similarity Matrix Among Post-WWII Presidents (Sample):
print(round(as.matrix(postwar_sim)[1:6, 1:6], 3))
           Biden  Bush Carter Clinton Eisenhower Johnson
Biden      1.000 0.664  0.506   0.654      0.472   0.526
Bush       0.664 1.000  0.563   0.685      0.624   0.555
Carter     0.506 0.563  1.000   0.575      0.474   0.470
Clinton    0.654 0.685  0.575   1.000      0.503   0.606
Eisenhower 0.472 0.624  0.474   0.503      1.000   0.467
Johnson    0.526 0.555  0.470   0.606      0.467   1.000
bipartisan_corpus <- corpus_subset(inaug_corpus, Party %in% c("Democratic", "Republican"))

party_dfm <- tokens(bipartisan_corpus, remove_punct = TRUE, remove_numbers = TRUE) %>%
  tokens_tolower() %>%
  tokens_remove(stopwords("english")) %>%
  dfm() %>%
  dfm_group(groups = Party)

keyness_party <- textstat_keyness(party_dfm, target = "Democratic", measure = "chi2")

cat("\nTop 10 Democratic Key Features (Positive Chi2):\n")

Top 10 Democratic Key Features (Positive Chi2):
print(head(keyness_party, 10), row.names = FALSE)
   feature     chi2            p n_target n_reference
 democracy 39.11714 3.991251e-10       50          14
    fellow 20.11417 7.295430e-06       51          28
        us 19.94724 7.960860e-06      222         220
    spirit 16.09988 6.008784e-05       59          40
    sacred 15.46649 8.398110e-05       19           5
  powerful 14.14635 1.691253e-04       18           5
    pledge 12.25402 4.642573e-04       23          10
   ancient 11.43146 7.221098e-04       13           3
     forth 10.79312 1.018780e-03       14           4
  domestic 10.05137 1.522345e-03       21          10
cat("\nTop 10 Republican Key Features (Negative Chi2 / Reference Group):\n")

Top 10 Republican Key Features (Negative Chi2 / Reference Group):
print(tail(keyness_party, 10), row.names = FALSE)
        feature       chi2            p n_target n_reference
       southern  -9.285416 2.309854e-03        0          14
       election  -9.933568 1.622916e-03        3          25
 administration -10.075031 1.502921e-03       14          53
      amendment -11.275813 7.852345e-04        0          17
        country -12.634834 3.786249e-04       64         162
       business -12.678509 3.698824e-04       11          51
    enforcement -13.266445 2.701991e-04        0          20
       congress -13.346362 2.589245e-04       22          78
           laws -13.810719 2.021795e-04       22          79
            law -31.409577 2.089478e-08       17         100
# Plot keyness
p_keyness <- textplot_keyness(
  keyness_party,
  n = 15,
  margin = 0.2,
  color = c("dodgerblue3", "firebrick3")
) +
  theme_minimal() +
  labs(
    title = "Differential Word Keyness by Political Party",
    subtitle = "Target = Democratic Party | Reference = Republican Party (Chi-squared measure)",
    x = "Chi-squared Statistic"
  )
print(p_keyness)

wf_model <- textmodel_wordfish(dfm_trimmed, dir = c(1, ndoc(dfm_trimmed)))

metrics_df$Theta    <- wf_model$theta
metrics_df$SE_Theta <- wf_model$se.theta

cat("\nSummary of Wordfish Theta Estimates:\n")

Summary of Wordfish Theta Estimates:
summary(metrics_df$Theta)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
-1.3197 -0.9742 -0.1805  0.0000  1.0412  1.5086 
textplot_scale1d(wf_model, margin = "documents")

p_wf_time <- ggplot(metrics_df, aes(x = Year, y = Theta, color = Party)) +
  geom_point(size = 3, alpha = 0.85) +
  geom_errorbar(aes(ymin = Theta - 1.96 * SE_Theta, ymax = Theta + 1.96 * SE_Theta), width = 1.5, alpha = 0.4) +
  geom_smooth(aes(group = 1), method = "loess", color = "darkgray", se = FALSE, linetype = "dashed") +
  theme_minimal() +
  labs(
    title = "Wordfish Latent Dimension (Theta) Over Time",
    subtitle = "Unsupervised scaling reveals clear chronological language evolution across centuries",
    x = "Year", y = "Estimated Latent Position (Theta)"
  )
print(p_wf_time)
`geom_smooth()` using formula = 'y ~ x'

textplot_scale1d(wf_model, margin = "features") +
  labs(
    title = "Wordfish Feature Estimates: Word Weight (Beta) vs Word Marginal Frequency (Psi)",
    subtitle = "Outlier words have the highest discriminatory power across speeches"
  )

wf_features <- data.frame(
  word = wf_model$features,
  beta = wf_model$beta,
  psi  = wf_model$psi,
  stringsAsFactors = FALSE
)

cat("\nTop Words on Negative Scale (Historical/Early Era):\n")

Top Words on Negative Scale (Historical/Early Era):
print(head(wf_features[order(wf_features$beta), c("word", "beta", "psi")], 10), row.names = FALSE)
         word      beta       psi
     examples -4.937441 -6.825200
  legislature -4.738485 -6.261285
    judiciary -4.683887 -6.892189
       tribes -4.488824 -6.824592
      defects -4.283573 -6.774695
 improvements -4.274937 -6.294947
   respective -4.158575 -5.410089
   collisions -4.089270 -6.373659
   introduced -4.067133 -6.531133
         veto -4.053853 -6.179763
cat("\nTop Words on Positive Scale (Modern Era):\n")

Top Words on Positive Scale (Modern Era):
print(head(wf_features[order(-wf_features$beta), c("word", "beta", "psi")], 10), row.names = FALSE)
       word     beta       psi
       jobs 4.940933 -6.274754
     sights 4.517485 -6.748441
        yes 4.502796 -5.773752
       dawn 4.383855 -6.574268
      story 4.381607 -5.045288
     winter 4.324732 -6.497420
 challenges 3.787723 -4.471029
      drugs 3.656449 -5.639074
  america's 3.600193 -3.566330
    today's 3.593179 -5.376616