library(tidyverse)
library(dplyr)
library(tidytext)
library(SnowballC) # for stemming
# Example: short FOMC excerpt
text_data <- tibble(
line = 1:3,
text = c(
"The Committee seeks to achieve maximum employment and inflation at the rate of 2 percent over the longer run.",
"The Committee judges that the risks to achieving its employment and inflation goals are balanced.",
"The Committee will carefully monitor incoming information and adjust the stance of monetary policy as appropriate."
)
)
# --- 0. Tokenize into words
tokens <- text_data %>%
unnest_tokens(word, text)
tokens# A tibble: 50 × 2
line word
<int> <chr>
1 1 the
2 1 committee
3 1 seeks
4 1 to
5 1 achieve
6 1 maximum
7 1 employment
8 1 and
9 1 inflation
10 1 at
# ℹ 40 more rows
## --- 1. Tokenize into bigrams (n = 2)
bigrams <- text_data %>%
unnest_tokens(bigram, text, token = "ngrams", n = 2)
bigrams# A tibble: 47 × 2
line bigram
<int> <chr>
1 1 the committee
2 1 committee seeks
3 1 seeks to
4 1 to achieve
5 1 achieve maximum
6 1 maximum employment
7 1 employment and
8 1 and inflation
9 1 inflation at
10 1 at the
# ℹ 37 more rows
## --- 2. 2-gram pipeline that removes stopwords inside the n-gram
bigrams_clean <- text_data %>%
unnest_tokens(bigram, text, token = "ngrams", n = 2) %>%
separate(bigram, c("w1","w2"), sep = " ") %>%
anti_join(stop_words, by = c("w1" = "word")) %>%
anti_join(stop_words, by = c("w2" = "word")) %>%
count(w1, w2, sort = TRUE) %>%
unite(bigram, w1, w2, sep = " ")
bigrams_clean# A tibble: 10 × 2
bigram n
<chr> <int>
1 2 percent 1
2 achieve maximum 1
3 carefully monitor 1
4 committee judges 1
5 committee seeks 1
6 incoming information 1
7 inflation goals 1
8 maximum employment 1
9 monetary policy 1
10 monitor incoming 1
## --- 3. Word tokenization + stemming
stemmed_words <- text_data %>%
unnest_tokens(word, text) %>%
mutate(stem = wordStem(word)) # apply stemming
stemmed_words# A tibble: 50 × 3
line word stem
<int> <chr> <chr>
1 1 the the
2 1 committee committe
3 1 seeks seek
4 1 to to
5 1 achieve achiev
6 1 maximum maximum
7 1 employment employ
8 1 and and
9 1 inflation inflat
10 1 at at
# ℹ 40 more rows
# Rebuild stemmed bigrams (filter stopwords first to avoid ‘the’/’and’ stems)
stem_bigrams <- text_data %>%
unnest_tokens(word, text) %>%
anti_join(stop_words, by = "word") %>%
mutate(stem = wordStem(word)) %>%
group_by(line) %>%
summarise(text_stem = paste(stem, collapse = " "), .groups = "drop") %>%
unnest_tokens(bigram, text_stem, token = "ngrams", n = 2) %>%
count(bigram, sort = TRUE)
stem_bigrams# A tibble: 23 × 2
bigram n
<chr> <int>
1 employ inflat 2
2 2 percent 1
3 achiev employ 1
4 achiev maximum 1
5 adjust stanc 1
6 carefulli monitor 1
7 committe carefulli 1
8 committe judg 1
9 committe seek 1
10 goal balanc 1
# ℹ 13 more rows

