Assignment 6: Text Analytics with quanteda

Published

November 1, 2026

Code
library(quanteda)
library(quanteda.textstats)
library(quanteda.textplots)
library(quanteda.textmodels)
library(tidyverse)
library(httr2)
library(rvest)
library(xml2)
library(knitr)

theme_set(theme_minimal(base_size = 11))
set.seed(6302)
Code
govinfo_key <- Sys.getenv("GOVINFO_API_KEY")

if (nzchar(govinfo_key)) {
  message("GovInfo API key successfully loaded.")
} else {
  stop("GovInfo API key not found. Check your .Renviron file.")
}

1 Archived tweets: The Biden–Xi summit

This section analyzes tweets collected around the November 2021 Biden–Xi virtual summit.

The main question is:

What did the Twitter conversation surrounding the summit look like, and what topics or accounts appeared most frequently?

We will examine four things:

  1. Frequent words.

  2. Hashtag co-occurrence network.

  3. Mention co-occurrence network.

  4. Latent Semantic Analysis (LSA).

1.1 Download and read the dataset

Code
summit_url <- paste0(
  "https://raw.githubusercontent.com/datageneration/",
  "datamethods/master/textanalytics/summit_11162021.csv"
)

summit <- read_csv(
  summit_url,
  show_col_types = FALSE
)

# Inspect the dataset
#limpse(summit)

1.2 Create a quanteda corpus

A corpus is a collection of documents. In this case, each tweet is one document.

Code
summit_corpus <- corpus(
  summit,
  text_field = "text",
  docid_field = "status_id"
)

#summary(summit_corpus)
Code
summit_tokens <- tokens(
  summit_corpus,
  remove_punct = TRUE,
  remove_symbols = TRUE,
  remove_url = TRUE
)

summit_dfm <- dfm(summit_tokens)

summit_dfm
Document-feature matrix of: 14,520 documents, 10,222 features (99.78% sparse)
and 88 docvars.
                     features
docs                  breaking news us president biden amp communist china
  1460701806644715520        1    1  1         1     1   1         1     2
  1460701781915103232        0    0  0         0     0   0         0     0
  1460701749266685952        0    0  0         0     1   0         0     0
  1460327759855587328        0    0  0         1     1   0         0     0
  1460493456330006528        0    0  0         0     1   0         0     0
  1460701607910264832        0    0  0         0     1   0         0     0
                     features
docs                  leader xi
  1460701806644715520      1  1
  1460701781915103232      0  0
  1460701749266685952      0  1
  1460327759855587328      0  1
  1460493456330006528      0  1
  1460701607910264832      0  1
[ reached max_ndoc ... 14,514 more documents, reached max_nfeat ... 10,212 more
features ]

The DFM represents the number of times each word appears in each tweet.

1.3 Describe the dataset

Code
summit_overview <- tibble(
  total_tweets = ndoc(summit_corpus),
  unique_accounts = n_distinct(summit$user_id),
  first_tweet = min(summit$created_at, na.rm = TRUE),
  last_tweet = max(summit$created_at, na.rm = TRUE)
)

summit_overview |>
  knitr::kable(
    caption = "Overview of the archived summit tweets"
  )
Overview of the archived summit tweets
total_tweets unique_accounts first_tweet last_tweet
14520 10024 2021-11-07 23:45:25 2021-11-16 20:10:23

1.4 Most frequent words

Code
summit_words <- summit_dfm |>
  dfm_remove(stopwords("en")) |>
  dfm_remove(
    pattern = c("amp", "https", "t.co")
  )

top_tweets <- topfeatures(summit_words, 20)

top_tweets
    biden        xi    summit   virtual president   jinping     china   chinese 
    12338     12027     11167      7483      6148      4766      3011      2716 
      joe    monday      hold        us    taiwan  biden-xi       u.s  tensions 
     2598      2540      2301      2179      1578      1556      1493      1420 
  china's       old    friend      said 
     1330      1246      1196      1113 
Code
top_tweets |>
  enframe(
    name = "word",
    value = "frequency"
  ) |>
  ggplot(
    aes(
      x = frequency,
      y = reorder(word, frequency)
    )
  ) +
  geom_col(fill= 'navy') +
  labs(
    title = "Most Frequent Words in Summit Tweets",
    x = "Word frequency",
    y = NULL
  )

One important distinction: word frequency measures how often a term appears, not how positively or negatively people feel about the subject.

1.5 Hashtag co-occurrence network

Next, we want to see which hashtags appear together in tweets.

For example, if #Biden and #China appear in the same tweet, the two hashtags will have a connection.

Code
tweet_dfm <- dfm(
  tokens(
    summit_corpus,
    remove_punct = TRUE
  )
)

tag_dfm <- dfm_select(
  tweet_dfm,
  pattern = "#*"
)

top_tags <- names(
  topfeatures(tag_dfm, 50)
)

tag_fcm <- fcm(tag_dfm) |>
  fcm_select(pattern = top_tags)

textplot_network(
  tag_fcm,
  min_freq = 50,
  edge_alpha = 0.7,
  edge_size = 1
) +
  labs(
    title = "Hashtag Co-occurrence Network"
  )

  • Larger nodes indicate more frequent hashtags.

  • Connected nodes are hashtags that occur together.

  • Clusters suggest groups of related discussion topics.

1.6 Mention co-occurrence network

Accounts mentioned in tweets:

Code
mention_dfm <- dfm_select(
  tweet_dfm,
  pattern = "@*"
)

top_mentions <- names(
  topfeatures(mention_dfm, 50)
)

mention_fcm <- fcm(mention_dfm) |>
  fcm_select(pattern = top_mentions)

textplot_network(
  mention_fcm,
  min_freq = 10,
  edge_color = "firebrick",
  edge_alpha = 0.7,
  edge_size = 1
) +
  labs(
    title = "Mention Co-occurrence Network"
  )

This tells us which public figures, media organizations, or other accounts were frequently mentioned together.

1.7 Latent Semantic Analysis (LSA)

The final part of the tweet analysis is LSA.

Unlike the frequency analysis, which looks at individual words, LSA identifies patterns in word usage across documents.

In this case, each point represents one tweet. Tweets with similar word-use patterns may appear closer together.

Code
summit_lsa_dfm <- summit_words |>
  dfm_trim(
    min_termfreq = 5,
    min_docfreq = 2
  )
Code
summit_lsa <- textmodel_lsa(
  summit_lsa_dfm,
  nd = 4
)

lsa_documents <- as_tibble(
  summit_lsa$docs,
  rownames = "document"
)

names(lsa_documents)[2:5] <- paste0(
  "dimension_", 1:4
)

ggplot(
  lsa_documents,
  aes(
    x = dimension_1,
    y = dimension_2
  )
) +
  geom_point(
    alpha = 0.2,
    size = 0.8,
    color= 'darkgreen'
  ) +
  labs(
    title = "LSA of Tweets About the Biden–Xi Summit",
    x = "LSA Dimension 1",
    y = "LSA Dimension 2"
  )

1.8 Save results for reproducibility

Code
dir.create("data", showWarnings = FALSE)

write_csv(
  summit_overview,
  "data/summit_overview.csv"
)

write_csv(
  enframe(top_tweets, name = "word", value = "frequency"),
  "data/summit_top_words.csv"
)

2 Presidential documents: GovInfo

The research question is:

How has the US government’s public language about Xi Jinping differed between the Biden and Trump administrations?

2.1 Understanding the source

The source is the Compilation of Presidential Documents (CPD) collection on GovInfo.

The documents:

  • Belong to the CPD collection.

  • Mention the exact phrase “Xi Jinping”.

  • Were published on or after January 20, 2021.

For the comparison:

  • Biden: January 20, 2021 to January 19, 2025.

  • Trump: January 20, 2025 onward.

Code
govinfo_key <- Sys.getenv("GOVINFO_API_KEY")

stopifnot(nzchar(govinfo_key))

govinfo_search_all <- function(
    query,
    api_key,
    page_size = 1000
) {
  
  offset <- "*"
  pages <- list()
  
  repeat {
    
    response <- request(
      "https://api.govinfo.gov/search"
    ) |>
      req_url_query(api_key = api_key) |>
      req_body_json(
        list(
          query = query,
          pageSize = as.character(page_size),
          offsetMark = offset,
          resultLevel = "package",
          sorts = list(
            list(
              field = "publishdate",
              sortOrder = "ASC"
            )
          )
        )
      ) |>
      req_perform()
    
    payload <- resp_body_json(
      response,
      simplifyVector = FALSE
    )
    
    pages <- append(
      pages,
      list(payload$results)
    )
    
    new_offset <- payload$offsetMark
    
    if (
      length(payload$results) == 0 ||
      is.null(new_offset) ||
      identical(new_offset, offset)
    ) {
      break
    }
    
    offset <- new_offset
  }
  
  purrr::list_flatten(pages)
}

This function handles pagination.

2.2 Define the query

Code
cpd_query <- paste(
  'collection:(CPD)',
  'AND "Xi Jinping"',
  'AND publishdate:range(2021-01-20,)'
)

cpd_retrieved_at <- format(
  Sys.time(),
  tz = "UTC",
  usetz = TRUE
)

cpd_results <- govinfo_search_all(
  query = cpd_query,
  api_key = govinfo_key
)

length(cpd_results)
[1] 351

GovInfo returned 351 raw search results.

2.3 Create a metadata table

We want to retain the document identifiers, titles, publication dates, and download links.

Code
scalar_chr <- function(x) {
  if (is.null(x) || length(x) == 0) {
    return(NA_character_)
  }
  
  as.character(x[[1]])
}
cpd_index <- tibble(
  package_id = map_chr(
    cpd_results,
    ~ scalar_chr(.x$packageId)
  ),
  
  title = map_chr(
    cpd_results,
    ~ scalar_chr(.x$title)
  ),
  
  date_issued = as.Date(
    map_chr(
      cpd_results,
      ~ scalar_chr(.x$dateIssued)
    )
  ),
  
  text_link = map_chr(
    cpd_results,
    ~ {
      link <- .x$download$txtLink
      
      if (is.null(link)) {
        link <- .x$download$htmlLink
      }
      
      scalar_chr(link)
    }
  )
) |>
  distinct(package_id, .keep_all = TRUE) |>
  filter(!is.na(text_link))

glimpse(cpd_index)
Rows: 351
Columns: 4
$ package_id  <chr> "DCPD-202100229", "DCPD-202100238", "DCPD-202100258", "DCP…
$ title       <chr> "Remarks at a Virtual Irish Community Event", "Remarks Dur…
$ date_issued <date> 2021-03-17, 2021-03-19, 2021-03-25, 2021-03-26, 2021-03-3…
$ text_link   <chr> "https://api.govinfo.gov/packages/DCPD-202100229/htm", "ht…

This removes duplicate package IDs and documents without a usable text or HTML link.

2.4 Download and extract document text

Code
read_govinfo_text <- function(url) {
  
  response <- request(url) |>
    req_url_query(api_key = govinfo_key) |>
    req_perform()
  
  page <- response |>
    resp_body_string() |>
    read_html()
  
  blocks <- page |>
    html_element("body") |>
    xml2::xml_children()
  
  block_text <- blocks |>
    html_text2() |>
    str_squish()
  
  metadata_start <- which(
    str_detect(block_text, "^Categories:")
  )[1]
  
  if (!is.na(metadata_start)) {
    block_text <- block_text[
      seq_len(metadata_start - 1)
    ]
  }
  
  block_text |>
    discard(~ .x == "") |>
    paste(collapse = "\n")
}
Code
cpd_docs <- cpd_index |>
  mutate(
    text = map_chr(
      text_link,
      read_govinfo_text
    )
  ) |>
  filter(
    str_detect(
      text,
      regex(
        "\\bXi\\s+Jinping\\b",
        ignore_case = TRUE
      )
    )
  )

nrow(cpd_docs)
[1] 238

2.5 Create the CPD corpus

Code
cpd_corpus <- corpus(
  cpd_docs,
  text_field = "text",
  docid_field = "package_id"
)

docvars(cpd_corpus, "title") <-
  cpd_docs$title

docvars(cpd_corpus, "date_issued") <-
  cpd_docs$date_issued

#summary(cpd_corpus)

2.6 Examine Xi Jinping in context using KWIC

KWIC stands for Key Word in Context.

Instead of looking at how many times Xi Jinping is mentioned, we examine the words immediately surrounding each mention.

Code
cpd_tokens <- tokens(cpd_corpus)

cpd_kwic <- kwic(
  cpd_tokens,
  pattern = phrase("Xi Jinping"),
  window = 12
)

cpd_kwic |>
  as_tibble() |>
  select(
    docname,
    pre,
    keyword,
    post
  ) |>
  slice_head(n = 20) |>
  knitr::kable(
    caption = "Xi Jinping in context: Selected CPD references"
  )
Xi Jinping in context: Selected CPD references
docname pre keyword post
DCPD-202100229 Minister Enda Kenny of Ireland ; former President Barack Obama ; President Xi Jinping of China ; and White House Press Secretary Jennifer R . Psaki
DCPD-202100238 It’s about who we are . Closing comment : I was with Xi Jinping in China . I spent more time with him , I’m told
DCPD-202100238 to Mayor Michael E . Duggan of Detroit , MI ; President Xi Jinping of China , in his former capacity as Vice President of China
DCPD-202100258 of what the relationship with China really is about . I’ve known Xi Jinping for a long time . Allegedly , by the time I left
DCPD-202100258 left office as Vice President , I had spent more time with Xi Jinping than any world leader had , because President Obama and the Chinese
DCPD-202100259 Do you have a comment on the Georgia election law ? President Xi Jinping of China / President Vladimir Vladimirovich Putin of Russia / Prime Minister
DCPD-202100271 just have to imagine again . I had a long discussion with Xi Jinping , the leader of China , when he called to congratulate me
DCPD-202100295 Fauci ; Senate Minority Leader A . Mitchell McConnell ; and President Xi Jinping of China .
DCPD-202100453 . ) , former adjutant general , Delaware National Guard ; President Xi Jinping of China ; and President Vladimir Vladimirovich Putin of Russia . He
DCPD-202100500 dealing with China . And again , we’re not looking—as I’ve told Xi Jinping myself , I’m not looking for conflict . Where we can cooperate
DCPD-202100500 he referred to former President Donald J . Trump ; and President Xi Jinping of China .
DCPD-202100559 particularly autocrats : How can I define America ? I was with Xi Jinping in—on the Tibetan Plateau , and he asked me that when I
DCPD-202100559 and Immigration Services ( USCIS ) Acting Director Tracy Renaud ; President Xi Jinping of China ; and Avery Lindsay , grandson of USCIS’s Outstanding Americans
DCPD-202100602 J . Portman ; Gov . Mike DeWine of Ohio ; President Xi Jinping of China ; and President Vladimir Vladimirovich Putin of Russia . He
DCPD-202100617 . Take a look at China . I’ve spent more time with Xi Jinping as a world leader than anyone else has . I spent 25
DCPD-202100617 he referred to President Vladimir Vladimirovich Putin of Russia ; and President Xi Jinping of China .
DCPD-202100619 look at China . I’ve spent an awful lot of time with Xi Jinping , President of China , more than , I’m told , than
DCPD-202100633 saying—and the press on the line has heard me say this before—that Xi Jinping , and—who I’ve met hours and hours with—over 25 hours—24 hours alone
DCPD-202100633 ; former Secretary of Commerce Penny S . Pritzker ; and President Xi Jinping of China . A portion of these remarks could not be verified
DCPD-202100657 looking at us ; they’re wondering . And you’ve got guys like Xi Jinping and Putin who think the answer is autocracy , because democracies can’t

2.7 Compare Biden and Trump using keyness

Now we compare the vocabulary of documents published under the two administrations.

Code
docvars(cpd_corpus, "administration") <- if_else(
  as.Date(docvars(cpd_corpus, "date_issued")) <
    as.Date("2025-01-20"),
  "Biden",
  "Trump"
)

table(
  docvars(cpd_corpus, "administration")
)

Biden Trump 
  170    68 

Check that both administrations are represented. If one group has no documents, you cannot perform the comparison.

Code
cpd_dfm <- cpd_corpus |>
  tokens(
    remove_punct = TRUE,
    remove_numbers = TRUE
  ) |>
  tokens_remove(
    c(
      stopwords("en"),
      "mr",
      "mrs",
      "ms",
      "sir"
    )
  ) |>
  dfm()

Group documents by administration

Code
cpd_grouped <- dfm_group(
  cpd_dfm,
  groups = docvars(
    cpd_corpus,
    "administration"
  )
)

cpd_grouped
Document-feature matrix of: 2 documents, 38,595 features (39.07% sparse) and 1
docvar.
       features
docs    administration joseph   r biden  jr remarks virtual irish community
  Biden           1657    332 854  2119 512     672     115   127       403
  Trump            237     21  56   251  45     144       1     4        25
       features
docs    event
  Biden   104
  Trump    11
[ reached max_nfeat ... 38,585 more features ]
Code
if (
  all(c("Biden", "Trump") %in%
      docnames(cpd_grouped))
) {
  
  cpd_keyness <- textstat_keyness(
    cpd_grouped,
    target = "Biden"
  )
  
  textplot_keyness(
    cpd_keyness,
    n = 20
  ) +
    labs(
      title = "Biden vs. Trump: CPD Vocabulary",
      subtitle = "Words distinguishing documents from each administration"
    )
  
} else {
  message(
    "Both administrations must be represented for keyness."
  )
}

Keyness identifies words that are statistically more associated with one group than the other.

The documents may differ in format, topic, and publication frequency, so they should not be treated as a direct measure of policy positions.

Compare: what does each source let you say about the summit, and about US–China relations? Who produced each text, and for whom?

The three sources provide different perspectives on the 2021 Biden–Xi summit and broader US–China relations because they were produced by different actors for different audiences. The archived tweets capture public discussion surrounding the summit, showing which topics, people, and issues attracted attention on social media. However, they represent users who chose to post during the collection period, not public opinion as a whole. The presidential documents from GovInfo provide a different perspective by showing how the Biden administration officially discussed Xi Jinping and China. These texts were produced by government officials for domestic and international audiences, so they reveal the administration’s public messaging rather than private diplomatic positions. Finally, inaugural addresses provide a broader historical perspective on how presidents communicate national priorities and foreign policy goals when taking office. They are written for the American public and wider international audience, but their ceremonial nature means they do not necessarily reflect specific policies or diplomatic relationships. Taken together, the sources show how the same relationship can be represented differently through public discussion, official government communication, and presidential rhetoric. However, none of them alone can fully explain the state of US–China relations or what happened behind closed diplomatic doors.

2.8 Create collection log and manifest

Code
dir.create(
  "data",
  showWarnings = FALSE
)

cpd_manifest <- cpd_index |>
  semi_join(
    cpd_docs,
    by = "package_id"
  ) |>
  mutate(
    query = cpd_query,
    retrieved_at_utc = cpd_retrieved_at
  )

cpd_log <- tibble(
  endpoint = "https://api.govinfo.gov/search",
  query = cpd_query,
  result_level = "package",
  sort = "publishdate ASC",
  retrieved_at_utc = cpd_retrieved_at,
  raw_results = length(cpd_results),
  documents_with_text = nrow(cpd_docs)
)

write_csv(
  cpd_manifest,
  "data/cpd_manifest.csv"
)

write_csv(
  cpd_log,
  "data/cpd_collection_log.csv"
)
Code
cpd_docs |>
  summarise(
    documents = n(),
    first_publication = min(
      date_issued,
      na.rm = TRUE
    ),
    last_publication = max(
      date_issued,
      na.rm = TRUE
    )
  ) |>
  knitr::kable(
    caption = "Overview of the collected CPD documents"
  )
Overview of the collected CPD documents
documents first_publication last_publication
238 2021-03-17 2026-09-29

3 Presidential inaugural addresses

The objective is to examine how presidential language has changed over time and whether there are differences between Democratic and Republican presidents.

3.1 Load the inaugural corpus

Code
docvars(data_corpus_inaugural) |>
  as_tibble() |>
  arrange(desc(Year)) |>
  slice_head(n = 5)
# A tibble: 5 × 4
   Year President FirstName Party     
  <int> <chr>     <chr>     <fct>     
1  2025 Trump     Donald J. Republican
2  2021 Biden     Joseph R. Democratic
3  2017 Trump     Donald J. Republican
4  2013 Obama     Barack    Democratic
5  2009 Obama     Barack    Democratic

3.2 Restrict the analysis to 1945 onward

Code
inaugural <- corpus_subset(
  data_corpus_inaugural,
  Year >= 1945
)

#summary(inaugural)

We are interested in the postwar period, not the entire history of the United States.

3.3 Create tokens and a data frame

Code
inaugural_tokens <- tokens(
  inaugural,
  remove_punct = TRUE,
  remove_numbers = TRUE
)

inaugural_dfm <- dfm(
  inaugural_tokens
)

3.4 Measure length, lexical diversity, and readability

Length: How many tokens are in each address?

Lexical diversity: How many distinct words are used relative to the total number of words?

Readability: How difficult is the text to read according to the Flesch Reading Ease formula?

Code
inaugural_lengths <- tibble(
  document = docnames(inaugural),
  year = docvars(inaugural, "Year"),
  president = docvars(inaugural, "President"),
  party = as.character(
    docvars(inaugural, "Party")
  ),
  tokens = ntoken(inaugural_dfm),
  types = ntype(inaugural_dfm)
)
Code
inaugural_lexical <- textstat_lexdiv(
  inaugural_dfm,
  measure = "TTR"
) |>
  as_tibble() |>
  select(
    document,
    TTR
  )
Code
inaugural_readability <- textstat_readability(
  inaugural,
  measure = "Flesch"
) |>
  as_tibble() |>
  select(
    document,
    Flesch
  )
Code
inaugural_metrics <- inaugural_lengths |>
  left_join(
    inaugural_lexical,
    by = "document"
  ) |>
  left_join(
    inaugural_readability,
    by = "document"
  )

inaugural_metrics |>
  mutate(
    across(
      c(TTR, Flesch),
      ~ round(.x, 2)
    )
  ) |>
  knitr::kable(
    caption = "Presidential address metrics, 1945 onward"
  )
Presidential address metrics, 1945 onward
document year president party tokens types TTR Flesch
1945-Roosevelt 1945 Roosevelt Democratic 555 257 0.46 68.38
1949-Truman 1949 Truman Democratic 2271 741 0.33 48.79
1953-Eisenhower 1953 Eisenhower Republican 2445 848 0.35 57.70
1957-Eisenhower 1957 Eisenhower Republican 1659 586 0.35 69.16
1961-Kennedy 1961 Kennedy Democratic 1364 533 0.39 57.12
1965-Johnson 1965 Johnson Democratic 1486 526 0.35 69.41
1969-Nixon 1969 Nixon Republican 2124 708 0.33 65.58
1973-Nixon 1973 Nixon Republican 1801 507 0.28 54.19
1977-Carter 1977 Carter Democratic 1221 490 0.40 53.38
1981-Reagan 1981 Reagan Republican 2431 842 0.35 58.75
1985-Reagan 1985 Reagan Republican 2553 857 0.34 57.58
1989-Bush 1989 Bush Republican 2315 748 0.32 73.10
1993-Clinton 1993 Clinton Democratic 1598 600 0.38 55.81
1997-Clinton 1997 Clinton Democratic 2157 719 0.33 59.22
2001-Bush 2001 Bush Republican 1583 584 0.37 60.12
2005-Bush 2005 Bush Republican 2071 725 0.35 53.19
2009-Obama 2009 Obama Democratic 2390 893 0.37 60.53
2013-Obama 2013 Obama Democratic 2092 776 0.37 53.56
2017-Trump 2017 Trump Republican 1443 538 0.37 58.58
2021-Biden 2021 Biden Democratic 2366 729 0.31 73.20
2025-Trump 2025 Trump Republican 2909 940 0.32 55.08

3.5 Visualize length and lexical diversity over time

Code
inaugural_metrics |>
  select(
    year,
    tokens,
    TTR
  ) |>
  pivot_longer(
    cols = c(tokens, TTR),
    names_to = "measure",
    values_to = "value"
  ) |>
  ggplot(
    aes(
      x = year,
      y = value
    )
  ) +
  geom_line() +
  geom_point() +
  facet_wrap(
    ~ measure,
    scales = "free_y",
    ncol = 1
  ) +
  labs(
    title = "Changes in Inaugural Address Length and Lexical Diversity",
    x = "Year",
    y = NULL
  )

3.6 Calculate cosine similarity

Next, we compare how similar inaugural addresses are in terms of vocabulary.

Cosine similarity compares the relative direction of two document vectors. A score closer to 1 indicates greater similarity in their word-use patterns.

First, normalize the DFM into proportions:

Code
inaugural_proportions <- dfm_weight(
  inaugural_dfm,
  scheme = "prop"
)
Code
inaugural_similarity <- textstat_simil(
  inaugural_proportions,
  margin = "documents",
  method = "cosine"
) |>
  as.matrix()
Code
as.data.frame(
  inaugural_similarity
) |>
  rownames_to_column(
    "document_1"
  ) |>
  pivot_longer(
    cols = -document_1,
    names_to = "document_2",
    values_to = "cosine"
  ) |>
  ggplot(
    aes(
      x = document_1,
      y = document_2,
      fill = cosine
    )
  ) +
  geom_tile() +
  scale_fill_viridis_c(
    limits = c(0, 1)
  ) +
  coord_equal() +
  labs(
    title = "Cosine Similarity Among Inaugural Addresses",
    x = NULL,
    y = NULL,
    fill = "Similarity"
  ) +
  theme(
    axis.text.x = element_text(
      angle = 60,
      hjust = 1,
      size = 7
    ),
    axis.text.y = element_text(
      size = 7
    )
  )

3.7 Compare Democratic and Republican vocabulary using keyness

This is similar to the Biden–Trump comparison, but now we compare political parties.

Code
party_dfm <- inaugural_dfm |>
  dfm_remove(
    stopwords("en")
  ) |>
  dfm_group(
    groups = docvars(
      inaugural_dfm,
      "Party"
    )
  )

party_keyness <- textstat_keyness(
  party_dfm,
  target = "Democratic"
)

textplot_keyness(
  party_keyness,
  n = 20
) +
  labs(
    title = "Vocabulary Differences: Democratic vs. Republican Presidents"
  )

Disclaimer: this is a relatively small corpus, and the speeches were delivered across different historical periods. Differences may reflect historical circumstances and individual presidents as well as party affiliation.

3.8 Check which is the latest address in data_corpus_inaugural.

If the 2025 address is missing, say how you would add it — and from which source.

Code
latest_inaugural <- docvars(data_corpus_inaugural) |>
  as_tibble() |>
  slice_max(Year, n = 1, with_ties = FALSE)

latest_inaugural |>
  knitr::kable(caption = "Latest address in data_corpus_inaugural")
Latest address in data_corpus_inaugural
Year President FirstName Party
2025 Trump Donald J. Republican

4 What is Wordfish?

Wordfish is an unsupervised text-scaling model developed by Slapin and Proksch (2008). It estimates the position of documents along a single latent dimension using word frequencies. It does not require you to supply predefined ideological scores. 

4.1 Prepare the inaugural dataframe

Code
wordfish_dfm <- inaugural_dfm |>
  dfm_remove(
    stopwords("en")
  ) |>
  dfm_trim(
    min_docfreq = 2,
    min_termfreq = 5
  )

This removes common English stopwords and words that appear too rarely to contribute meaningfully to the comparison.

4.2 Choose the direction of the scale

Wordfish can estimate the same dimension in either direction. For example, the first document could receive a negative score and the last a positive score, or vice versa. This is why the dir argument is important. We need to specify which documents should anchor the direction. I will use the earliest and latest inaugural addresses available in the corpus.

Code
wordfish_documents <- docvars(
  inaugural,
  field = c("Year", "President")
) |>
  as_tibble() |>
  mutate(
    document = docnames(inaugural)
  ) |>
  arrange(Year)

first_document <- wordfish_documents$document[1]

last_document <- wordfish_documents$document[
  nrow(wordfish_documents)
]

first_document
[1] "1945-Roosevelt"
Code
last_document
[1] "2025-Trump"
Code
stopifnot(
  first_document %in% docnames(wordfish_dfm),
  last_document %in% docnames(wordfish_dfm)
)

direction_documents <- match(
  c(first_document, last_document),
  docnames(wordfish_dfm)
)

direction_documents
[1]  1 21

4.3 Run Wordfish

Code
inaugural_wordfish <- textmodel_wordfish(
  wordfish_dfm,
  dir = direction_documents
)

#summary(inaugural_wordfish)

4.4 Results Visualization

Code
textplot_scale1d(
  inaugural_wordfish,
  margin = "documents",
  groups = docvars(
    inaugural,
    "Party"
  )
) +
  labs(
    title = "Wordfish Estimates for Presidential Inaugural Addresses",
    x = "Estimated Wordfish position",
    y = NULL)

Code
textplot_scale1d(
  inaugural_wordfish,
  margin = "features",
  highlighted = c(
    "government",
    "freedom",
    "nation",
    "people",
    "security",
    "democracy"
  )
)

1. What does Wordfish assume?

It assumes that word counts are generated through a Poisson process. The model accounts for differences in document length, the general frequency of words, and the extent to which particular words distinguish documents along a latent dimension.

2. What does the dimension measure?

You need to inspect the actual results. It might reflect historical differences, presidential communication styles, political ideology, or a combination.

3. How would you demonstrate that it measures ideology?

You would need external validation. For example:

  • Compare the positions with independently established presidential ideology scores.

  • Examine the words associated with each end.

  • Read selected passages from speeches at both extremes.

  • Check whether the results are robust to different preprocessing choices.

4. Why must you set dir?

The mathematical dimension has no inherent positive or negative direction. The dir argument fixes its orientation by identifying two documents and specifying that the first should have a lower estimated position than the second. It does not establish which end is liberal or conservative.

5 Comparing the three corpora

Differences in the data-generating process:

Corpus Who produces the text? What does it represent?
Summit tweets Twitter users, journalists, organizations, etc. Selected public discussion
CPD documents Presidents and their administrations; published by the Office of the Federal Register Official government communication
Inaugural addresses Presidents delivering inaugural speeches Formal presidential communication

Tweets: They provide insight into the immediate online discussion surrounding the summit. However, they cannot establish what Americans generally believed because Twitter users are not a representative sample of the population.

CPD documents: They show how the government publicly discussed Xi Jinping and China. However, official statements do not necessarily reflect private diplomatic discussions, internal disagreements, or public opinion.

Inaugural addresses: They allow comparisons of presidential language over time. However, they are ceremonial speeches, not comprehensive representations of presidential policy.

The important distinction is that these three sources were not generated in the same way. Therefore, their results should not be interpreted as if they were interchangeable measures of public opinion or political ideology.

6 Report

I. Introduction

The three corpora provide different perspectives on presidential communication and US–China relations. The first contains archived tweets surrounding the November 2021 Biden–Xi summit, the second consists of official presidential documents collected from GovInfo, and the third contains inaugural addresses from 1945 onward. Although all three involve political language, their data-generating processes differ considerably.

II. Summit tweets

The most frequent terms were biden, xi, summit, virtual, president, jinping, china. The hashtag network showed a cluster with hashtags such as: china, fentanyl, coronavirus, americans, joebiden, xijinping, and america, while the mention network suggested one main cluster between nba, teams, and a stadium. The LSA visualization showed a dense central area with quite a bit of other points around it. These patterns help characterize the collected Twitter discussion, but they cannot establish broader public opinion. The archive is limited by its collection keywords, time window, and the people who chose to post.

III. Government documents

The KWIC results showed that Xi Jinping was mentioned in contexts involving China, Russia, world leaders, the Tibed. The keyness comparison identified Biden-associated words: announce, press, national, briefing and Trump-associated words: much, do, bad, see, several, reporters. These differences may reflect changes in communication, but they could also result from differences in document types and topics. The collection only includes documents identified by the specified GovInfo query and exact-name selection.

IV. Inaugural addresses

The addresses differed in length and readability. Trump’s 2025 address was the longest (2,909 tokens), while Roosevelt’s 1945 address was the shortest (555 tokens) and had the highest lexical diversity (TTR = 0.46). Biden’s 2021 address had the highest Flesch readability score (73.20), whereas Truman’s 1949 address had the lowest (48.79). Cosine similarity suggested strong vocabulary similarities across several addresses, particularly between Eisenhower’s 1953 and 1957 speeches, reflecting consistency in his presidential language. The party comparison identified Democratic-associated words: democracy, change, must, forth, journey, and Republican-associated words shared, voices, strive, love, think, dreams, although historical differences and individual presidential styles complicate a purely partisan interpretation.

V. Wordfish and conclusion

Wordfish estimated a one-dimensional scale based on word frequencies. The plot shows the two parties overlapping considerably, this suggests that the dimension does not clearly separate presidents by party. Additionally, the same president appear close together, this may indicate consistency in their language across different inaugurations. Although we can conclude this, it still requires external validation before it can be interpreted as ideology. Overall, the three corpora demonstrate how text analysis can identify linguistic patterns while remaining dependent on how texts are produced and selected.

7 Data collection note: GovInfo

7.1 Source and permission

The presidential documents were collected from the Compilation of Presidential Documents (CPD) through the U.S. Government Publishing Office’s GovInfo API. The collection is published by the Office of the Federal Register within the National Archives and Records Administration. Government works are generally in the public domain under 17 U.S.C. § 105, although third-party copyrighted material included in government publications may have separate restrictions.

7.2 Query and selection

The collection used the query:

collection:(CPD) AND "Xi Jinping" AND publishdate:range(2021-01-20,)

All available pages of search results were retrieved. Duplicate package identifiers were removed, and documents without downloadable text were excluded. The downloaded text was then checked to retain documents containing the exact phrase “Xi Jinping” in the document body.

Documents published before January 20, 2025 were classified as Biden administration documents, while documents published on or after that date were classified as Trump administration documents.

7.3 Limitations and gaps

The collection does not represent every presidential statement about China. It excludes documents that do not contain the exact search phrase, private diplomatic discussions, and documents without accessible text. It may also include different types of presidential communication, such as speeches, press briefings, and written statements. Consequently, differences in vocabulary may reflect document format and subject matter rather than changes in foreign policy.

The collection manifest and retrieval log are provided for transparency and reproducibility. The downloaded document texts and API key are not published.