Анализ инагурационных речей президентов США

Author
Affiliation

Тарасов Александр

НИУ ВШЭ

Published

December 19, 2025

Библиотеки

library(tidytext)
library(dplyr)
library(ggplot2)
library(tibble)
library(topicmodels)

Данные

Данные - инаугурационные речи президентов США из библиотеки quanteda.

library(quanteda)
head(data_corpus_inaugural)
Corpus consisting of 6 documents and 4 docvars.
1789-Washington :
"Fellow-Citizens of the Senate and of the House of Representa..."

1793-Washington :
"Fellow citizens, I am again called upon by the voice of my c..."

1797-Adams :
"When it was first perceived, in early times, that no middle ..."

1801-Jefferson :
"Friends and Fellow Citizens: Called upon to undertake the du..."

1805-Jefferson :
"Proceeding, fellow citizens, to that qualification which the..."

1809-Madison :
"Unwilling to depart from examples of the most revered author..."

Обработка

Создаем

inaug_tibble <- tibble(
  President = docvars(data_corpus_inaugural, "President"),
  Year      = docvars(data_corpus_inaugural, "Year"),
  Text      = as.character(data_corpus_inaugural)
) |> 
  filter(Year >= 1925)
inaug_tibble
# A tibble: 26 × 3
   President   Year Text                                                        
   <chr>      <int> <chr>                                                       
 1 Coolidge    1925 "My countrymen,\n\nno one can contemplate current condition…
 2 Hoover      1929 "My Countrymen: This occasion is not alone the administrati…
 3 Roosevelt   1933 "I am certain that my fellow Americans expect that on my in…
 4 Roosevelt   1937 "When four years ago we met to inaugurate a President, the …
 5 Roosevelt   1941 "On each national day of inauguration since 1789, the peopl…
 6 Roosevelt   1945 "Chief Justice, Mr. Vice President, my friends, you will un…
 7 Truman      1949 "Mr. Vice President, Mr. Chief Justice, and fellow citizens…
 8 Eisenhower  1953 "My friends, before I begin the expression of those thought…
 9 Eisenhower  1957 "The Price of Peace\nMr. Chairman, Mr. Vice President, Mr. …
10 Kennedy     1961 "Vice President Johnson, Mr. Speaker, Mr. Chief Justice, Pr…
# ℹ 16 more rows

Токенизируем

tokens_clean <- inaug_tibble$Text |>
  tokens(remove_punct = TRUE, remove_symbols = TRUE, remove_numbers = TRUE) |>
  tokens_tolower() |>
  tokens_remove(stopwords("en")) |>
  tokens_wordstem()  

Создаем матрицу

dfm_clean <- dfm(tokens_clean)

Оставляем слова, встретившиеся хотя бы 2 раза

dfm_pruned <- dfm_trim(dfm_clean, min_doc = 2)

Запускаем LDA

lda_model <- LDA(dfm_pruned, k = 5, control = list(seed = 123))

Топ 10 слов по темам

terms(lda_model, 10)
      Topic 1   Topic 2    Topic 3   Topic 4    Topic 5   
 [1,] "nation"  "us"       "nation"  "us"       "nation"  
 [2,] "peac"    "world"    "freedom" "america"  "peopl"   
 [3,] "peopl"   "govern"   "world"   "american" "us"      
 [4,] "can"     "america"  "can"     "must"     "world"   
 [5,] "govern"  "nation"   "peopl"   "nation"   "can"     
 [6,] "world"   "peopl"    "us"      "new"      "must"    
 [7,] "upon"    "let"      "free"    "world"    "american"
 [8,] "must"    "can"      "must"    "can"      "new"     
 [9,] "countri" "new"      "america" "time"     "america" 
[10,] "law"     "american" "unit"    "peopl"    "know"    

Распределяем темы по документам

topic_probs <- posterior(lda_model)$topics

Делаем новый тиббл

inaug_with_topic <- inaug_tibble |>
  mutate(
    ClosestTopic = max.col(topic_probs)
  )

Посмотрим на последние 5 речей

last5_topics <- inaug_with_topic |>
  arrange(desc(Year)) |>
  head(5) |>
  select(President, Year, ClosestTopic)

last5_topics
# A tibble: 5 × 3
  President  Year ClosestTopic
  <chr>     <int>        <int>
1 Trump      2025            5
2 Biden      2021            4
3 Trump      2017            2
4 Obama      2013            4
5 Obama      2009            5

Визуализации

Находим доминирующую тему в всех речей

inaug_all_with_topic <- inaug_tibble |>
  mutate(ClosestTopic = max.col(topic_probs))

Строим график, где показывается доминирующая тема в каждой речи за последние сто лет

ggplot(inaug_all_with_topic, aes(x = Year, y = ClosestTopic)) +
  geom_point(aes(color = factor(ClosestTopic)), size = 3) +
  scale_y_continuous(breaks = 1:5, limits = c(0.5, 5.5)) +
  labs(
    title = "Доминирующая тема в инаугурационных речах",
    x = "Год инаугурации",
    y = "Номер главной темы",
    color = "Тема"
  ) +
  theme_minimal() +
  theme(legend.position = "bottom")

Считаем сколько у каждого топика речей

topic_counts <- inaug_all_with_topic |>
  count(ClosestTopic, .drop = FALSE) |>
  mutate(ClosestTopic = factor(ClosestTopic, levels = 1:5))

График с количеством речей по каждому топику

ggplot(topic_counts, aes(x = ClosestTopic, y = n, fill = ClosestTopic)) +
  geom_col(width = 0.7) +
  labs(
    title = "Сколько раз каждая тема была доминирующей",
    x = "Номер темы",
    y = "Количество речей",
    fill = "Тема"
  ) +
  scale_fill_viridis_d(option = "plasma") +
  theme_minimal()

Выводы

  • Тема 5 самая популярная

  • Топик 1 изчезает после 53 года

  • Топик 3 появляется только после 93 года

  • Доминирующим топиком в речи 1 президента могут быть разные топики

Комментарии

В корпусе есть только фамилии президентов, из-за этого нельзя автоматически собрать все речи одного президента