W4: Dictionaries and Sentiment Analysis
W2 split text into tokens and built a DFM; W4 takes the next step: first define the concept to be measured, then use a “word → category” lookup table (a dictionary) to turn text into scores, and finally use human judgement to validate what the score actually measures.
This week’s learning objectives
Slide 2 lists five objectives; the first four correspond to the four main parts of these notes, and the fifth connects to your own final project. Come back and tick them off when you have finished:
- Measurement: state clearly what a dictionary score is “intended to measure”. (Chapters 00, 04)
- Dictionary construction: build and revise word or phrase lists from political texts. (Chapters 02, 03, 06)
- Scoring: turn matches into scores, and explain the denominator and texts with “no matches at all”. (Chapters 04, 05)
- Validation: assess validity using published evidence and human judgement. (Chapters 07, 08)
- Own project: plan a dictionary measure for your own research. (The plan builder in Chapters 11 and 14)
A political science research question
This week’s guiding question: When do MPs describe household economic conditions negatively? The example sentence is “Families cannot afford rent or energy bills.” We could compare speakers, periods, or government vs. opposition.
The key is to read two things at once: rent tells us the issue (household costs), while cannot afford is the evaluation (hardship). The slide’s reminder: mentioning inflation does not tell us how an MP evaluates household conditions.
Attention, sentiment, stance: three different questions
| Concept | Question asked | Example on the slide |
|---|---|---|
| Issue attention | What is mentioned? | This speech discusses energy bills. |
| Sentiment | How is something evaluated? | High energy bills are hurting families. |
| Stance | What position is taken towards a target? | I support the government’s price cap. |
Negative words used to describe a problem may come together with support for a policy. “Negative sentiment” is not the same as “opposition”.
One measurement workflow
Click each step below to see the explanation (content taken from slide 5):
- Find relevant sentences: household income, cost of living, affordability.
- Code the evaluation and its target: how are household conditions described?
- Validate against human judgement: include both texts the dictionary matched and texts it did not match.
- Compare speakers or periods: relevant sentences judged negative ÷ all relevant sentences.
Slide 5 is also candid: today’s class practises two things separately — counting issue mentions and counting positive and negative words. To really answer the opening question we would still need to link the “evaluation” to its “target”, and that step is not completed today.
Construct, indicator, score, claim
| Level | Concrete example (slide 6) |
|---|---|
| Construct | How much MPs talk about household costs |
| Indicator | Count matches of terms such as rent and energy bills (one phrase match) |
| Score | Speech A: 4 matches / 100 words = 4 per 100 words; Speech B: 4 / 200 = 2 per 100 words |
| Claim | Per 100 words, A has twice as many household-cost matches as B |
Note the last sentence of slide 6: this only counts mentions; to measure negative evaluation we also need to recognise language such as cannot afford.
Same corpus, different units of analysis
| Text unit | Corresponding political science question |
|---|---|
| Sentence | Which statements describe household hardship? |
| Speech | What share of a speech discusses hardship? |
| Speaker-period | How does a speaker’s attention change over time? |
This week’s practice data: 5,000 UK House of Commons speeches, 1945–2025 (Data/hc_sample_1945_2025.rds). When splitting or combining texts, keep the speaker, date and source ID.
Exercise: which concept does this sentence measure?
Choose one for each sentence: issue attention, sentiment or stance. (The sentences are adapted from the concepts on slides 3–4 and 66; the reasoning is shown after you answer.)
How to use these notes
- Each chapter has a slide panel on the right (wide screens) or behind the bottom-right button (phones); it turns the page automatically when you scroll to a passage marked “Slide N”.
- R code is taken from
W4/classroom/W4_classroom.R(C01–C16) and the after-classW4/lab/Lab_Session_W4.R; all output is from actually running it locally (R 4.5.3, quanteda 4.5.1, quanteda.textstats 0.97.2, irr 0.85, ggplot2 4.0.3; Linux aarch64) and has been checked against the numbers on the slides one by one. - There are three kinds of interactive components: real data (exported from this week’s Data/), toy intuition (marked “Supplement (not from the lecture)”), and exercises (answer boxes, flip cards, claim judgements, plan builder).
- Progress and answers are stored only in this browser; the sidebar shows how much you have completed.
Bag of words, DFM and dictionaries
Dictionary methods build on W2’s bag of words: documents are split into tokens and counted into a document × feature table (DFM). This chapter first runs C01 to load the data, then uses a small two-sentence example to make DFMs, document length and dictionary matching clear.
C01: set up once, use for the whole class
Each document is one parliamentary speech contribution. C01 locates workflow.R, switches the working directory and source()s it; workflow.R prepares in one go the objects used later: speeches, discovery_tokens, comparison, check_scores, policy_scores, validation, etc. After that, keep the same R session.
# C01: Setup
# First use: uncomment the next line to install.
# install.packages(c("quanteda", "quanteda.textstats"))
library(quanteda)
library(quanteda.textstats)
paths <- c("workflow.R", "W4/classroom/workflow.R",
"classroom/workflow.R", "../classroom/workflow.R")
found <- paths[file.exists(paths)]
if (length(found) == 0) found <- file.choose()
setwd(dirname(normalizePath(found[1])))
source("workflow.R")> library(quanteda)
Package version: 4.5.1
Unicode version: 17.0
ICU version: 78.3
Parallel computing: 2 of 2 threads used.
See https://quanteda.io for tutorials and examples.
> library(quanteda.textstats)
> paths <- c("workflow.R", "W4/classroom/workflow.R",
+ "classroom/workflow.R", "../classroom/workflow.R")
> found <- paths[file.exists(paths)]
> if (length(found) == 0) found <- file.choose()
> setwd(dirname(normalizePath(found[1])))
> source("workflow.R")- Reads
hc_sample_1945_2025.rds(checks 5,000 rows with no missing text) and gives each speech an IDspeech_0001…. toks: punctuation removed, lowercased;lengths_original= the number of tokens per speech, and every later “per 100 words” or “per 1,000 words” denominator uses it.policy_tokens: a second token stream that keeps punctuation, used specifically for phrase matching so that phrases do not run across full stops.- With a fixed seed
set.seed(719104)it draws 80 speeches as the hand-coding sample (30 development + 50 test);discovery_tokens= the 4,950 speeches left after removing the 50 test speeches. Use only discovery to find terms; keep test for testing (end of Chapter 02, Chapter 07).
C02: counts and document length
Predict first: what will prices be in row A?
# C02: Counts and document length
library(quanteda)
demo <- c(A = "Prices rise. Prices worry voters.",
B = "Prices fall.")
demo_tokens <- tokens(demo, remove_punct = TRUE)
demo_dfm <- dfm(demo_tokens)
selected <- dfm_match(demo_dfm, c("prices", "rise", "fall"))
as.matrix(selected)
ntoken(demo_tokens)> library(quanteda)
> demo <- c(A = "Prices rise. Prices worry voters.",
+ B = "Prices fall.")
> demo_tokens <- tokens(demo, remove_punct = TRUE)
> demo_dfm <- dfm(demo_tokens)
> selected <- dfm_match(demo_dfm, c("prices", "rise", "fall"))
> as.matrix(selected)
features
docs prices rise fall
A 2 1 0
B 1 0 1
> ntoken(demo_tokens)
A B
5 2 - Rows = documents; columns = the selected words; each cell is a count. Row A: prices 2, rise 1, fall 0.
- Length is different: A has 5 tokens, but the table only shows 3 counts —
worryandvoterswere not selected. This foreshadows why the denominator later has to use all tokens. dfm()lowercases by default, soPricesandpricesare the same column.
Interactive: build your own DFM
Supplement (not from the lecture): the tokenisation rule here is simplified (split on spaces and punctuation). For short English sentences it agrees with quanteda, but it does not handle details such as hyphens or contractions.
What a word-count table throws away
The government does not support the opposition.
The opposition does not support the government.
The same bag of words, but who does what to whom is completely reversed. This is also why, after this point, W4 discusses phrases (Chapter 03), negation (Chapter 05) and “sentiment ≠ stance” (Chapter 08). Paste the two sentences into A and B in the interactive component above and clear the features box, and you will see two identical rows.
What is a dictionary?
A dictionary maps “expressions” to categories defined in advance. In quanteda:
library(quanteda)
dic <- dictionary(list(
household_costs = c("inflation", "rent", "energy bills"),
employment = c("unemployment", "job security")
))Slide 12: mentioning household costs does not, by itself, prove economic hardship.
Applying our dictionary
The instructor combined slides 12–13 into one self-contained file, examples/W4_dictionary_simple.R. Local output:
> library(quanteda)
> dic <- dictionary(list(
+ household_costs = c("inflation", "rent", "energy bills"),
+ employment = c("unemployment", "job security")
+ ))
> texts <- c("Rent and energy bills are rising.",
+ "We need job security.")
> example_tokens <- tokens(texts, remove_punct = FALSE)
> matched <- tokens_lookup(example_tokens, dic, capkeys = FALSE)
> counts <- dfm(matched)
> as.matrix(counts)
features
docs household_costs employment
text1 2 0
text2 0 1rent + energy bills give 2 matches; job security gives 1. Note that energy bills is a phrase: tokens_lookup() looks for the two consecutive words in the token sequence and counts them once. This agrees with the table on slide 13.
ntoken() is 5. Why?Finding candidate terms: frequency, KWIC, collocations, keyness
A dictionary can be reused, adapted or built from scratch, but “available” does not mean “suitable”. This chapter runs C03–C06, using four tools to find candidate terms in the 4,950 discovery speeches, and goes back to read the context at every step.
Reuse, adapt, or build?
| Choice | Main question |
|---|---|
| Existing dictionary | Does its original domain fit this corpus? |
| Adapted dictionary | Which changes improve performance here? |
| New dictionary | Can we document the coverage and the exclusion rules? |
| Use another method | Is the category so context-dependent that word rules cannot hold up? |
Slide 14: Availability is not evidence of suitability. Grimmer & Stewart (2013, pp. 274–275) cite the example from Loughran & McDonald (2011): tax, cost, crude (oil) and cancer carry negative connotations in other contexts, but in company financial reports they may carry positive connotations (see the Chapter 12 reading guide).
Four steps to building or adapting a word list
- Write down what should count, with one example of what should not count.
- Read passages that do and do not discuss the issue.
- List the words and phrases that represent the issue.
- Check for false matches and for relevant passages the list misses.
Taking household costs as the example: we need to distinguish energy bills (invoices) from a parliamentary bill (legislation).
C03: frequency — occurrences vs. number of speeches
# C03: Frequency in real speeches (run C01 first)
recap_dfm <- dfm(discovery_tokens)
recap_dfm <- dfm_remove(recap_dfm, stopwords("en"))
# Keep words made of English letters only.
recap_dfm <- dfm_select(recap_dfm, "^[a-z]+$", valuetype = "regex")
freq <- textstat_frequency(recap_dfm)
head(freq, 6)> recap_dfm <- dfm(discovery_tokens)
> recap_dfm <- dfm_remove(recap_dfm, stopwords("en"))
> # Keep words made of English letters only.
> recap_dfm <- dfm_select(recap_dfm, "^[a-z]+$", valuetype = "regex")
> freq <- textstat_frequency(recap_dfm)
> head(freq, 6)
feature frequency rank docfreq group
1 hon 6514 1 2826 all
2 government 3190 2 1320 all
3 right 2762 3 1470 all
4 member 2395 4 1129 all
5 can 2391 5 1221 all
6 people 2273 6 995 allfrequency: total occurrences;docfreq: number of speeches in which the word occurs;rankis ordered by frequency;group = allmeans all speeches are counted together.- The local result is identical to slide 17: hon occurs 6,514 times, in 2,826 speeches.
- Exercise: change 6 to 12. Which words describe parliamentary procedure rather than policy? (hon, right and member come from forms of address such as “the right hon. Member”.)
C04: KWIC — putting words back into context
KWIC = keyword in context. Does security always mean defence?
# C04: Context in real speeches (run C01 first)
live_contexts <- kwic(discovery_tokens, "security", window = 5)
context_table <- as.data.frame(live_contexts)
columns <- c("docname", "pre", "keyword", "post")
head(context_table[, columns], 2)> live_contexts <- kwic(discovery_tokens, "security", window = 5)
> context_table <- as.data.frame(live_contexts)
> columns <- c("docname", "pre", "keyword", "post")
> head(context_table[, columns], 2)
docname pre keyword post
1 speech_0024 as a basis of international security , is essential to the
2 speech_0246 raise the question in the security council . we advanced £Each row is one match; read across from pre → keyword → post, with at most 5 tokens on each side. Row 1 is international security, row 2 is security council — the same word, two meanings.
About the data: exported locally with kwic(discovery_tokens, pattern, window = 8); for words with more than 150 matches, 150 rows were sampled at random (set.seed(4)).
C05: collocations — candidate phrases
Collocation: two adjacent words that are strongly associated statistically. Sorted by lambda from largest to smallest.
# C05: Phrases in real speeches (run C01 first) coll <- textstat_collocations(discovery_tokens, size = 2, min_count = 20) row_order <- order(coll$lambda, decreasing = TRUE) coll <- coll[row_order, ] head(coll, 6) first_phrase <- phrase(coll$collocation[1]) phrase_context <- kwic(discovery_tokens, first_phrase, window = 5) head(phrase_context, 2)
> coll <- textstat_collocations(discovery_tokens, size = 2, min_count = 20)
> row_order <- order(coll$lambda, decreasing = TRUE)
> coll <- coll[row_order, ]
> head(coll, 6)
collocation count count_nested length lambda z
2809 sri lanka 23 0 2 15.65685 10.56449
2692 per cent 718 0 2 15.64201 11.04304
1743 dispatch box 23 0 2 13.23135 15.27786
1283 liberal democrats 37 0 2 12.40680 18.59108
113 northern ireland 334 0 2 12.22301 51.32513
452 united kingdom 300 0 2 11.97618 29.83622
> first_phrase <- phrase(coll$collocation[1])
> phrase_context <- kwic(discovery_tokens, first_phrase, window = 5)
> head(phrase_context, 2)
Keyword-in-context with 2 matches.
[speech_1885, 29:30] the british-owned tea estates in | sri lanka | . there has been considerable
[speech_1885, 80:81] to extend its stay in | sri lanka | to investigate the conditions of- The top one is sri lanka; both matches come from the same speech, speech_1885.
- A strong collocation is only a candidate: a place name by itself cannot measure household costs.
C06: keyness — comparing two groups
# C06: Relative word use (run C01 and C03 first)
party_dfm <- dfm_subset(recap_dfm,
party %in% c("Conservative", "Labour"))
party_dfm <- dfm_group(party_dfm, groups = party)
party_dfm <- dfm_trim(party_dfm, min_termfreq = 1)
keys_con <- textstat_keyness(party_dfm, target = "Conservative")
keys_lab <- textstat_keyness(party_dfm, target = "Labour")
head(keys_con, 3)
head(keys_lab, 3)> party_dfm <- dfm_subset(recap_dfm,
+ party %in% c("Conservative", "Labour"))
> party_dfm <- dfm_group(party_dfm, groups = party)
> party_dfm <- dfm_trim(party_dfm, min_termfreq = 1)
> keys_con <- textstat_keyness(party_dfm, target = "Conservative")
> keys_lab <- textstat_keyness(party_dfm, target = "Labour")
> head(keys_con, 3)
feature chi2 p n_target n_reference
1 aircraft 44.37288 2.714218e-11 116 31
2 cyberstalking 39.62479 3.077519e-10 42 0
3 stalking 33.96359 5.615304e-09 36 0
> head(keys_lab, 3)
feature chi2 p n_target n_reference
1 waste 61.43017 4.551914e-15 124 31
2 tory 49.50067 1.983080e-12 73 11
3 advertising 38.71565 4.902623e-10 64 12| Target: Conservative (slide 23) | Target: Labour | ||||||
|---|---|---|---|---|---|---|---|
| Word | chi2 | Con. | Lab. | Word | chi2 | Con. | Lab. |
| aircraft | 44.37 | 116 | 31 | waste | 61.43 | 31 | 124 |
| cyberstalking | 39.62 | 42 | 0 | tory | 49.50 | 11 | 73 |
| stalking | 33.96 | 36 | 0 | advertising | 38.72 | 12 | 64 |
- Each target is run once; each table shows that party’s top three positive keyness scores.
- Keyness takes into account each group’s total number of tokens — raw counts alone cannot decide it.
- These words are distinctive of this sample; they are not necessarily the most frequent, and they have nothing to do with positive or negative sentiment.
Keep “finding terms” and “evaluation” separate
- Record the dictionary version and the inclusion rules.
- Do not keep tuning on the final evaluation sample.
- Recheck performance when the language or period changes.
In the code: workflow.R removes the 50 test speeches from discovery_tokens, so C03–C06 never see them while finding terms.
Matching rules: phrases and wildcards
The same concept can be written as many different rules: a broad bill*, exact bill/bills, or the phrase energy bills. The broader the rule, the more false matches; the narrower the rule, the more it misses.
A small example you can calculate by hand
| Text | Broad rule bill* | Phrase energy bills |
|---|---|---|
| Energy bills are rising. | 1 | 1 |
| This bill reforms parliament. | 1 | 0 |
| Families cannot afford heating. | 0 | 0 |
Switching to the phrase removes one false positive (legislation), but still misses one relevant passage (cannot afford heating).
C07: phrase matching with quanteda
# C07: A complete phrase-lookup example
library(quanteda)
examples <- c("Energy bills are rising.",
"This bill reforms parliament.",
"Families cannot afford heating.")
example_tokens <- tokens(examples, remove_punct = FALSE)
cost_dict <- dictionary(list(costs = "energy bills"))
matched <- tokens_lookup(example_tokens, cost_dict)
cost_counts <- dfm(matched)
as.matrix(cost_counts)> library(quanteda)
> examples <- c("Energy bills are rising.",
+ "This bill reforms parliament.",
+ "Families cannot afford heating.")
> example_tokens <- tokens(examples, remove_punct = FALSE)
> cost_dict <- dictionary(list(costs = "energy bills"))
> matched <- tokens_lookup(example_tokens, cost_dict)
> cost_counts <- dfm(matched)
> as.matrix(cost_counts)
features
docs costs
text1 1
text2 0
text3 0Was your prediction right? Only the first sentence is matched (1, 0, 0). The exercise on the slide: add "cannot afford heating" to the dictionary — which error changes? (The false negative in the third sentence is fixed, but the phrase is very specific, and a different wording will be missed again.) You can try it directly in the test bench below.
C08: wildcard vs. exact matching
# C08: Wildcards in real speeches (run C01 first)
wild <- kwic(discovery_tokens, "bill*", window = 0)
exact <- kwic(discovery_tokens, c("bill", "bills"),
valuetype = "fixed", window = 0)
c(wildcard = nrow(wild), exact = nrow(exact))
word_counts <- table(wild$keyword)
word_counts <- sort(word_counts, decreasing = TRUE)
head(word_counts, 8)> wild <- kwic(discovery_tokens, "bill*", window = 0)
> exact <- kwic(discovery_tokens, c("bill", "bills"),
+ valuetype = "fixed", window = 0)
> c(wildcard = nrow(wild), exact = nrow(exact))
wildcard exact
1774 1539
> word_counts <- table(wild$keyword)
> word_counts <- sort(word_counts, decreasing = TRUE)
> head(word_counts, 8)
bill billion bills bill's billions billericay bill’s billâ
1470 157 69 24 18 5 3 3 bill*matches bill followed by any suffix, including billion and billericay (a place name).- Exact
bill/bills: 1,470 + 69 = 1,539. - Exact matching still mixes “legislation” and “household bills” — it cannot resolve semantic ambiguity.
- The output shows different apostrophes (bill's and bill’s) as well as what looks like encoding residue (billâ). These are match counts, not numbers of speeches.
Interactive: rule test bench
Supplement (not from the lecture): the matching logic imitates the glob rules of tokens_lookup() (case-insensitive, * stands for any suffix, phrases must occur consecutively, and with punctuation kept a phrase cannot run across a full stop).
Phrase rules keep useful context
- Phrases can separate energy bills from legislative bills.
- Longer n-grams carry more local context.
- But more specific expressions are also rarer.
- Match phrases first, then remove stop words — otherwise phrases such as cannot afford may be broken first.
The figure on slide 29 (Hvitfeldt & Silge 2022): each point is the number of distinct n-grams in one Andersen fairy tale at a given n-gram length; the larger n is, the lower the count of the most frequent n-gram (the more purple the colour).
Denominators, sentiment scores and “zero”
After matching, the results have to become numbers. This chapter covers three things: what to divide by (C09), two sentiment summaries (net tone and coverage), and why a score of zero is not necessarily neutral (C10).
C09: document length and the denominator
Predict: will the top entries be the same when ranked by “count” and by “rate”?
# C09: Rankings on real speeches (run C01 first)
discovery_ids <- docnames(discovery_tokens)
rates <- subset(comparison, doc_id %in% discovery_ids)
rates <- subset(rates, tokens >= 50)
cols <- c("doc_id", "broad", "tokens", "broad_per100")
raw_order <- order(rates$broad, decreasing = TRUE)
rate_order <- order(rates$broad_per100, decreasing = TRUE)
head(rates[raw_order, cols], 3)
head(rates[rate_order, cols], 3)> discovery_ids <- docnames(discovery_tokens)
> rates <- subset(comparison, doc_id %in% discovery_ids)
> rates <- subset(rates, tokens >= 50)
> cols <- c("doc_id", "broad", "tokens", "broad_per100")
> raw_order <- order(rates$broad, decreasing = TRUE)
> rate_order <- order(rates$broad_per100, decreasing = TRUE)
> head(rates[raw_order, cols], 3)
doc_id broad tokens broad_per100
speech_2792 speech_2792 20 1349 1.4825797
speech_1673 speech_1673 19 2655 0.7156309
speech_0743 speech_0743 18 1599 1.1257036
> head(rates[rate_order, cols], 3)
doc_id broad tokens broad_per100
speech_4435 speech_4435 4 69 5.797101
speech_1551 speech_1551 4 78 5.128205
speech_4917 speech_4917 3 59 5.084746- Rate = 100 × broad / tokens; broad is the number of
bill*matches. - 20 / 1,349 → 1.48 per 100 words; 4 / 69 → 5.80 per 100 words. More matches does not mean higher density.
- The six rows of local output are identical to slide 31.
Two simple sentiment summaries
Let P = number of positive matches, N = number of negative matches, L = number of original tokens.
| Summary | Definition | Interpretation |
|---|---|---|
| Net tone | 100 × (P − N) / L | Net matches per 100 tokens |
| Match coverage | 100 × (P + N) / L | Matched sentiment tokens per 100 tokens |
P = 3, N = 1, L = 100: net tone = 2, coverage = 4%. The slide also flags that the Proksch et al. case later uses a different scoring rule (Chapter 08).
C10: zero is not necessarily neutral
check_texts are five teaching examples built by workflow.R; the sentiment dictionary is the ten-word Dictionaries/teaching_affect.dic (positive: good, excellent, success, successful, improve; negative: bad, failure, crisis, harm, harmful).
# C10: Zero, balance and missing matches
check_texts
check_scores[, c("doc_id", "positive", "negative",
"net_per100", "coverage_per100", "balance")]> check_texts
good negated unmatched
"The policy is good." "The policy is not good." "The minister spoke today."
balanced empty
"A good plan with a bad outcome." ""
> check_scores[, c("doc_id", "positive", "negative",
+ "net_per100", "coverage_per100", "balance")]
doc_id positive negative net_per100 coverage_per100 balance
1 good 1 0 25 25.00000 1
2 negated 1 0 20 20.00000 1
3 unmatched 0 0 0 0.00000 NA
4 balanced 1 1 0 28.57143 0
5 empty 0 0 NA NA NA| doc_id | What happens (slide 34) |
|---|---|
| good | 1 positive match / 4 words → 25 per 100 words; all matches are positive, balance = 1. |
| negated | 1 positive match / 5 words → 20. The rule ignores not. |
| unmatched | Has words but P = N = 0; the denominator of balance is 0 → NA. |
| balanced | P = N = 1, 7 words in total: net = 0, coverage = 100 × 2 / 7 = 28.57%. |
| empty | L = 0 and P + N = 0: all three scores are undefined (NA). |
Zero can mean “no matches” or “positives and negatives cancel out”; neither proves neutrality.
When unticked, the calculation is the same as score_sentiment() in workflow.R (punctuation removed, lowercased, the denominator is all tokens; NA when the denominator is 0). The blank last line corresponds to empty. The negation rule you can tick is a supplement (not from the lecture), included for comparison with “the limits of a fixed negation window” in Chapter 05.
Negation, preprocessing and Denny & Spirling
A bag-of-words dictionary does not understand “not good”. Keeping not is only the first step; we also need a rule that uses it. And every preprocessing choice (stop words, word forms) can change the results — the Denny & Spirling manifesto case shows that 128 preprocessing combinations produce 12 different orderings.
C11: a deliberate sentiment failure
Predict: will keeping not make the second sentence negative?
# C11: A deliberate sentiment failure (run C01 first)
negation_tokens <- check_tokens[c("good", "negated")]
as.list(negation_tokens)
negation_dfm <- dfm(negation_tokens)
negation_counts <- dfm_lookup(negation_dfm, toy_sentiment)
as.matrix(negation_counts)
without_stopwords <- tokens_remove(negation_tokens, stopwords("en"))
as.list(without_stopwords)> negation_tokens <- check_tokens[c("good", "negated")]
> as.list(negation_tokens)
$good
[1] "the" "policy" "is" "good"
$negated
[1] "the" "policy" "is" "not" "good"
> negation_dfm <- dfm(negation_tokens)
> negation_counts <- dfm_lookup(negation_dfm, toy_sentiment)
> as.matrix(negation_counts)
features
docs positive negative
good 1 0
negated 1 0
> without_stopwords <- tokens_remove(negation_tokens, stopwords("en"))
> as.list(without_stopwords)
$good
[1] "policy" "good"
$negated
[1] "policy" "good" - Dictionary matching: both sentences match good (positive = 1, negative = 0). The rule does not use not to reverse anything.
- After removing stop words:
notis instopwords("en")and gets deleted; the two sentences’ tokens become identical:"policy" "good".
Keep negation words, then add a rule that handles them.
Interactive: how far can a fixed negation window go?
The sentences are the four difficult cases on slide 37 plus the two sentences from C11. Dictionary = teaching_affect.dic plus reject (negative; added to demonstrate the second sentence, not part of the course dictionary). Rauh (2018) uses “a direct two-word negation rule” (slide 57); a window of 1 here is the closest to it.
Limits of a fixed negation window
- “Not good” differs from “not only good but excellent”.
- “I reject the claim that this is a failure” contains a negative word.
- Quoting someone else’s criticism is not necessarily the speaker’s own view.
- Long-distance negation may fall outside a simple word window.
Rules can improve a baseline, but they cannot solve every sentence.
Preprocessing must fit the dictionary
- Different stop-word lists remove different shares of the words in a text.
- Keep negation words when they matter.
- Dictionary entries must match the word forms you choose (e.g. with or without stemming/lemmatisation).
- Check what each preprocessing choice throws away.
The figure on slide 38 (Hvitfeldt & Silge 2022): three points per story, one for each of three stop-word lists; X = total number of words, Y = percentage of words removed. For the same text, different lists remove different shares.
Case: positioning parties from manifestos (Denny & Spirling 2018)
- Question: can manifesto language place parties on a left–right scale? Data: 8 UK party manifestos, 1983–1997; model: Wordfish (estimates positions from word counts).
- The same 8 manifestos and the same Wordfish model, 128 preprocessing specifications, produce 12 different document orderings; black cells = disagreement with the authors’ prior ordering.
| Research claim | What this case can show (slide 41) |
|---|---|
| Vocabulary can place parties on a scale | Wordfish estimates relative positions from word counts |
| The ordering is robust to reasonable choices | Must be checked: this example produced 12 orderings |
| The model explains why parties change | That is a causal question and needs a different research design |
Back to dictionaries: do substantive comparisons survive reasonable scoring choices? (That is exactly what C12/C15 in the next chapter do.)
tokens_remove(stopwords("en")) to the two sentences?Dictionary revision and sensitivity (C12, C15)
In this chapter the construct switches to energy policy attention (not sentiment). Dictionaries/energy_policy.csv has two versions: v1 is broad and v2 is narrow. Changing the dictionary changes the scores — but whether the change is better can only be answered by human judgement.
C12: did revising the dictionary improve measurement?
Predict first: which version will flag more speeches?
# C12: Dictionary revisions (run C01 first)
policy_entries[, c("version", "category", "pattern")]
dev <- subset(policy_scores,
doc_id %in% docnames(discovery_tokens))
c(v1 = sum(dev$v1 > 0), v2 = sum(dev$v2 > 0))
energy_context <- kwic(discovery_tokens, "energy", window = 5)
head(energy_context, 3)> policy_entries[, c("version", "category", "pattern")]
version category pattern
1 v1 energy energy
2 v1 energy power
3 v1 energy electric*
4 v1 energy gas
5 v1 energy bill*
6 v2 energy energy
7 v2 energy electric*
8 v2 energy gas bill*
9 v2 energy renewab*
10 v2 energy solar*
11 v2 energy wind farm*
12 v2 energy fossil fuel*
> dev <- subset(policy_scores,
+ doc_id %in% docnames(discovery_tokens))
> c(v1 = sum(dev$v1 > 0), v2 = sum(dev$v2 > 0))
v1 v2
899 139
> energy_context <- kwic(discovery_tokens, "energy", window = 5)
> head(energy_context, 3)
Keyword-in-context with 3 matches.
[speech_0103, 105] production and use of atomic | energy | , clause 10 enables him
[speech_0103, 134] , 521 or of atomic | energy | plant. it is thought
[speech_0105, 2610] , the will and the | energy | to push it through, | v1 (broad) | v2 (narrow) |
|---|---|
energy, power, electric*, gas, bill* | energy, electric*, gas bill*, renewab*, solar*, wind farm*, fossil fuel* |
- v2 drops the most ambiguous terms,
power(political power),gas(tear gas) andbill*(legislation), narrows gas to the phrasegas bill*, and adds renewable-energy terms. - The result is in the output below:
v1 = 899 speeches, v2 = 139 speeches (at least one match among the 4,950). The scores changed — but is this closer to human judgement? That is the discussion question on slide 42. - The first 3 rows of the KWIC show directly that
energycan also mean “vigour”.
Interactive: compare the v1 and v2 highlighters on real speeches
Sample: 300 discovery speeches (60–700 tokens) drawn locally with set.seed(719), plus the 40 speeches with the highest v2 matches per 1,000 words (≤ 900 tokens) to make sure there are energy-related speeches; 335 after de-duplication — not a random sample, and it cannot be used to estimate precision for the whole corpus. The matching logic is the same as the Chapter 07 validation bench (JS imitating tokens_lookup()); the denominator of the per-1,000-word rate uses the JS token count, which may differ slightly from R’s tokens column, so R’s token count is also shown below.
C15: visualising dictionary sensitivity
dev is the table built in C12: one row per speech, 4,950 speeches in all; v1_per1000 and v2_per1000 are each version’s matches per 1,000 words.
# C15: Visualizing dictionary sensitivity (run C12 first)
# install.packages("ggplot2") # run once
library(ggplot2)
ggplot(dev, aes(x = v1_per1000, y = v2_per1000)) +
geom_point(size = 1, alpha = 0.4, colour = "#314f4f") +
geom_abline(intercept = 0, slope = 1,
colour = "firebrick", linetype = "dashed") +
labs(x = "v1 matches per 1,000 tokens",
y = "v2 matches per 1,000 tokens") +
theme_minimal()Overlapping points can hide many speeches. Changed scores show sensitivity, not which dictionary is more valid.
Extension: comparing parties with v1/v2 (optional Lab section)
workflow.R also computes party-level rates: sum first, then divide (ratio of group totals), not the average of per-speech rates. Note that party_rates uses all 5,000 speeches (policy_scores), not just the 4,950 discovery speeches.
Human benchmark, kappa, precision/recall
Validation needs human judgement as a benchmark. This chapter first asks whether humans agree with each other (C13, kappa), then whether the dictionary agrees with humans (C14, precision/recall/F1), and finally uses 24 teaching sentences to practise “develop → freeze → test”.
Human benchmark
- Write a codebook with positive, negative and ambiguous examples.
- Where feasible, keep coders blind to the dictionary’s predictions.
- Record disagreements and the adjudication procedure.
- The coding unit should match how the score will be used.
Human labels are evidence to be examined, not unquestionable truth.
Which texts should be validated?
- Include both matched and unmatched passages.
- Cover important dates, groups and documents of different lengths.
- Use an untouched sample for the final performance estimate.
- Check rare or ambiguous cases separately, for diagnosis.
A pile of easy examples cannot establish performance on the whole corpus.
C13: agreement between two human coders
# C13: Human agreement, not model accuracy
# install.packages("irr") # run once
library(irr)
ratings <- data.frame(
coder_A = c(1, 1, 1, 1, 1, 0, 0, 0, 0, 0),
coder_B = c(1, 1, 1, 1, 0, 1, 0, 0, 0, 0))
table(ratings$coder_A, ratings$coder_B)
mean(ratings$coder_A == ratings$coder_B)
agreement <- kappa2(ratings, weight = "unweighted")
agreement$value> library(irr)
Loading required package: lpSolve
> ratings <- data.frame(
+ coder_A = c(1, 1, 1, 1, 1, 0, 0, 0, 0, 0),
+ coder_B = c(1, 1, 1, 1, 0, 1, 0, 0, 0, 0))
> table(ratings$coder_A, ratings$coder_B)
0 1
0 4 1
1 1 4
> mean(ratings$coder_A == ratings$coder_B)
[1] 0.8
> agreement <- kappa2(ratings, weight = "unweighted")
> agreement$value
[1] 0.6Raw agreement is 80% (8 out of 10 the same), and Cohen’s kappa = 0.60. Kappa subtracts the probability that “the two would agree even if both guessed at random”: here each coder labelled 5 1s and 5 0s, so the expected chance agreement is 0.5, and κ = (0.8 − 0.5) / (1 − 0.5) = 0.6.
Supplement (not from the lecture): try making both coders label almost every text 0 (e.g. 0, 1, 1, 18) — agreement is very high, but kappa drops a lot.
Confusion matrix for issue detection
| 20 demonstration passages | Human: relevant | Human: not relevant |
|---|---|---|
| Dictionary: matched | 6 true positives | 2 false positives |
| Dictionary: not matched | 4 false negatives | 8 true negatives |
The unit is the passage, not the words in the dictionary.
C14: precision and recall
Calculate by hand from the table above before running the code.
# C14: Checking validation arithmetic (run C01 first) predicted <- validation$predicted human <- validation$human TP <- sum(predicted == 1 & human == 1) FP <- sum(predicted == 1 & human == 0) FN <- sum(predicted == 0 & human == 1) precision <- TP / (TP + FP) recall <- TP / (TP + FN) F1 <- 2 * TP / (2 * TP + FP + FN) c(precision = precision, recall = recall, F1 = F1)
> predicted <- validation$predicted > human <- validation$human > TP <- sum(predicted == 1 & human == 1) > FP <- sum(predicted == 1 & human == 0) > FN <- sum(predicted == 0 & human == 1) > precision <- TP / (TP + FP) > recall <- TP / (TP + FN) > F1 <- 2 * TP / (2 * TP + FP + FN) > c(precision = precision, recall = recall, F1 = F1) precision recall F1 0.7500000 0.6000000 0.6666667
- Precision = 0.75: of the 8 passages the dictionary flagged, 6 are relevant (6 / 8).
- Recall = 0.60: of the 10 relevant passages, the dictionary found 6 (6 / 10).
- F1 ≈ 0.667: 2 × 6 / (2 × 6 + 2 + 4).
Missed cases matter: reading only the passages the dictionary matched cannot tell us recall.
Try the question on slide 49: if you read only the TP + FP passages that the dictionary matched, can you work out FN?
Interactive: develop → freeze → test (24 teaching sentences)
Data/synthetic_validation.csv contains 24 teaching sentences written by the instructor with labels (12 development, 12 test; 1 = relevant to energy policy). These are not real parliamentary speeches, nor independently observed human labels (per the comments in workflow.R). The steps on slide 95:
- Develop: use the 12 development sentences to see where v1 and v2 go wrong.
- Freeze: keep v2 unchanged on the next 12 sentences.
- Test: compare predictions with labels, including the sentences with no match.
- Result: precision 0.80, recall 0.667, F1 0.727. This is only demonstration arithmetic, not a performance estimate on the parliamentary corpus.
print(synthetic_results): results of the same v1/v2 on development and test from workflow.R)n tp fp fn tn precision recall f1 accuracy split version 1 12 3 4 3 2 0.4285714 0.5000000 0.4615385 0.4166667 development v1 2 12 6 1 0 5 0.8571429 1.0000000 0.9230769 0.9166667 development v2 3 12 4 4 2 2 0.5000000 0.6666667 0.5714286 0.5000000 test v1 4 12 4 1 2 5 0.8000000 0.6666667 0.7272727 0.7500000 test v2
Matching logic: punctuation kept, case-insensitive, glob wildcards, phrases must be consecutive (imitating policy_counts()); when v1/v2 is loaded, each sentence’s prediction is checked against the actual R run, and the rightmost column of the table shows the “R” prediction.
Evaluating continuous sentiment scores
- Plot scores against human ratings.
- Check group means and individual disagreements.
- Check unmatched texts, compressed ranges and extreme values.
- Compare performance across groups and genres.
Validation must match the level of the claim
| Claim | Evidence needed |
|---|---|
| This sentence is negative | Sentence-level agreement |
| This group is relatively more positive | Group-level measurement validity |
| Sentiment changes over time | Measurement that is stable across periods |
| Countries differ in level of conflict | Comparable measurement and institutional context |
Cases: Boyle, Rauh, Proksch
Three published studies, each illustrating one step of dictionary measurement: a custom dictionary + held-out testing (Boyle et al. 2025), an adapted dictionary + human validation (Rauh 2018), and a translated dictionary + group-level validation + substantive analysis (Proksch et al. 2019). Everything below is based on the slides (the full texts of the three papers are not in the repo; see Chapter 12).
Policy relevance in energy research (Boyle et al. 2025)
- Question: which abstracts communicate policy relevance? Data: 270,537 abstracts, 100 journals, 2010–2023; a custom dictionary identifies relevance statements. Expressed relevance ≠ actual policy uptake.
- Unit: one abstract (does it contain a policy-relevance statement?). Development: start from policy terms and read 400 double-coded abstracts to find more terms; refinement: keep only added terms that improve positive-class F1 on the development set; test: evaluate on another 200 human-coded abstracts kept out of tuning.
- Reported average F1: development 0.90 / held-out 0.86. The instructor’s research-process note: fine-tuning transformers was tried first and did not work well.
- About 15% of abstracts are classified as policy-relevant; only 8% explicitly mention policy/policies. Journals whose aims explicitly mention policy: 26.7%; those that do not: 3.7%. This is a descriptive textual pattern, not evidence of policy uptake.
Compare with slide 24 in Chapter 02: this is the real-research version of “discovery → freeze → held-out”. A development-set F1 higher than the held-out F1 is expected.
A sentiment dictionary for German political language (Rauh 2018)
| Step | What the study did (slide 57) |
|---|---|
| Dictionary | Combined SentiWS and GermanPolarityClues; manually reviewed the entries |
| Context | Added a direct two-word negation rule |
| Score | Positive minus negative matches, divided by retained terms |
| Validation | Three coders coded 1,500 sampled Bundestag sentences |
- Coder agreement: 3 coders, 1,500 sentences; exact agreement 59.1%; ordinal alpha .675. Agreement is not validity.
- The scores of three dictionaries are compared across human-rated categories; the positive category separates better. The intervals show uncertainty in group means, not classification accuracy.
- Result: positive evaluations are easier to recover than negative ones. Use: a tested measure for comparing evaluative language in political texts. Limitation: scores cluster near 0 and have no self-evident numeric unit. The study validates the measurement; it does not explain why politicians became more positive.
Sentiment and legislative consensus (Proksch et al. 2019)
Question: does opposition tone reflect cross-party consensus? Is more positive opposition language associated with bills passing unanimously?
- Collect about 26,000 speeches on 871 German government bills, 2005–2017.
- Match positive and negative words with a translated Lexicoder sentiment dictionary.
- Aggregate by party and bill: log((P + 0.5) / (N + 0.5)).
- Put bill-level sentiment into a logistic regression of unanimous passage.
- Human validation: 300 passages, two human ratings each; standardized scores are compared by speaker group; the reported group-level correlation is about 0.9 — this is not 90% classification accuracy.
- Translation is itself a measurement decision: translated words may be used differently in politics, may have several equivalents, and word forms and tokenization affect matching; each language must be validated separately. The same category name does not guarantee comparable numeric scales.
- Regression: 814 bills; the coefficients are positive in all three models, but only model (3) is significant. This is an association, not a causal effect of tone.
Supplement (not from the lecture): the +0.5 keeps the logarithm defined when P or N is 0; the log ratio does not use L as a denominator, so when “length doubles and matches double too” the score is unchanged, and so is net tone; but when only length grows without more matches, net tone shrinks while the log ratio stays the same. Try it.
Sentiment, stance and conflict
| Concept | What the evidence must establish |
|---|---|
| Sentiment | Evaluative language in a defined unit |
| Stance | Support for or opposition to a specific target |
| Conflict | A substantive relation between actors or positions |
Negative words can describe a social problem rather than attack another party.
Flip cards: key numbers from the three cases
LIWC, custom dictionaries and campaign promises
LIWC is the most common “category percentage” tool, but the software, its official dictionary and our own quanteda dictionary are three different things. Next, we use the concepts of Eichorst & Lin (2019) for a two-sentence “specific vs vague” example, and finally look at two Chinese LIWC studies.
LIWC: what does it measure?
- LIWC = Linguistic Inquiry and Word Count: maps language to predefined dictionary categories.
- Categories include pronouns, emotion, social processes, etc.; most category scores are percentages of total words. Example: 4 category matches in 100 words = 4%.
- Category percentages measure word use; interpretation still requires validation.
LIWC and quanteda: separate roles
| Resource | Role | Access |
|---|---|---|
| LIWC application | Runs built-in or custom dictionaries | Licensed software |
| Official LIWC dictionary | Proprietary word–category resource | Restricted by license terms |
| quanteda + our dictionary | Matching with our own rules in R | No LIWC purchase needed |
Importing a file does not grant a license to use its dictionary. This week’s teaching_affect.dic only borrows LIWC’s file format (category numbers enclosed by %, followed by one “word + category number” per line).
C16: applying our dictionary with quanteda
# C16: Custom dictionary (run C01; stay in W4/classroom)
library(quanteda)
own <- dictionary(file = "Dictionaries/teaching_affect.dic", format = "LIWC")
mini <- tokens(c("Good policy.", "A bad crisis."), remove_punct = TRUE)
matched <- tokens_lookup(mini, own, capkeys = FALSE)
hits <- dfm(matched)
counts <- as.matrix(hits)
counts
word_count <- ntoken(mini)
100 * counts / word_count> library(quanteda)
> own <- dictionary(file = "Dictionaries/teaching_affect.dic", format = "LIWC")
> mini <- tokens(c("Good policy.", "A bad crisis."), remove_punct = TRUE)
> matched <- tokens_lookup(mini, own, capkeys = FALSE)
> hits <- dfm(matched)
> counts <- as.matrix(hits)
> counts
features
docs positive negative
text1 1 0
text2 0 2
> word_count <- ntoken(mini)
> 100 * counts / word_count
features
docs positive negative
text1 50 0.00000
text2 0 66.66667“Good policy.”: 1 of 2 words is positive → 50%; “A bad crisis.”: 2 of 3 words are negative → 66.67%. Discussion: why divide by all tokens rather than only by the number of matches? (Dividing by matches would only give 0 or 100% and lose the information about “how many emotion words were used”; this is also the difference between coverage and balance in Chapter 04.)
Campaign statements: vague or specific? (Eichorst & Lin 2019)
- Question: when do parties make specific campaign statements? Texts: English party manifestos; compares incumbency status and economic performance.
- Word-density plot: each column is a party manifesto, each row a dictionary term; darker colour = larger log count, white = 0.
A two-sentence dictionary example
The instructor’s examples/W4_campaign_simple.R, run locally:
> library(quanteda)
> text <- c("We may improve public services.",
+ "We guarantee better public services.")
> dict <- dictionary(list(vague = "may", concrete = "guarantee"))
> toks <- tokens(text, remove_punct = TRUE)
> counts <- dfm(toks)
> hits <- dfm_lookup(counts, dictionary = dict)
> as.matrix(hits)
features
docs vague concrete
text1 1 0
text2 0 1
> m <- as.matrix(hits)
> 100 * (m[, "concrete"] - m[, "vague"]) / ntoken(toks)
text1 text2
-20 20 - text1:
maymatches vague once; text2:guaranteematches concrete once. - Teaching score = 100 × (C − V) / L, i.e. “concrete percentage − vague percentage”, in percentage points: text1 = 100 × (0 − 1) / 5 = −20; text2 = +20.
- Adapted from Eichorst & Lin (2019): the original paper’s denominator excludes stop words and the difference is rescaled to 0–1; this example does neither.
The third sentence corresponds to “Try: Add not before guarantee” on slide 73: the count is unchanged (still concrete 1), but L becomes 7.
Chinese LIWC: two studies
- Lin (2023): a review article in Chinese that introduces dictionary categories and word-use rates and reviews studies of sports injury, self-efficacy and sports communication. Discussion: what can language reveal about a team?
- Lin et al. (2020): can categories distinguish emotional contexts? Data: 50 Hate and 50 Sad posts from PTT; anger words 2.00% vs 0.88%, Cohen’s d = 0.61. A group difference is not an individual diagnosis.
format = "LIWC" means?Beyond dictionaries: POS, TextRank, NER, LLMs
These tools help us find candidate terms or find names, but none of them validates a dictionary automatically. The optional extensions (O01, TextRank, Flair) require downloading models; where they ran locally the output is shown as is, and where they could not run we say so.
POS tagging (UDPipe)
Optional extension: back to “finding candidate terms”, now as POS → candidate terms → human review.
# Standalone POS example. No C01 or workflow.R required.
# The model is saved in udpipe_models under your current working directory.
# O01: POS candidates (model download on first run)
# install.packages("udpipe") # run once before class
library(udpipe)
dir.create("udpipe_models", showWarnings = FALSE)
info <- udpipe_download_model("english-ewt",
model_dir = "udpipe_models", overwrite = FALSE)
model <- udpipe_load_model(info$file_model)
text <- "Housing costs are unaffordable."
annotation <- udpipe_annotate(model, x = text, parser = "none")
ann <- as.data.frame(annotation)
ann[, c("token", "lemma", "upos")]
# Optional: retain candidate nouns, adjectives and verbs.
candidates <- subset(ann, upos %in% c("NOUN", "ADJ", "VERB"))
candidates[, c("token", "lemma", "upos")]> library(udpipe)
> dir.create("udpipe_models", showWarnings = FALSE)
> info <- udpipe_download_model("english-ewt",
+ model_dir = "udpipe_models", overwrite = FALSE)
Downloading udpipe model from https://raw.githubusercontent.com/jwijffels/udpipe.models.ud.2.5/master/inst/udpipe-ud-2.5-191206/english-ewt-ud-2.5-191206.udpipe to udpipe_models/english-ewt-ud-2.5-191206.udpipe
- This model has been trained on version 2.5 of data from https://universaldependencies.org
- The model is distributed under the CC-BY-SA-NC license: https://creativecommons.org/licenses/by-nc-sa/4.0
- Visit https://github.com/jwijffels/udpipe.models.ud.2.5 for model license details.
- For a list of all models and their licenses (most models you can download with this package have either a CC-BY-SA or a CC-BY-SA-NC license) read the documentation at ?udpipe_download_model. For building your own models: visit the documentation by typing vignette('udpipe-train', package = 'udpipe')
trying URL 'https://raw.githubusercontent.com/jwijffels/udpipe.models.ud.2.5/master/inst/udpipe-ud-2.5-191206/english-ewt-ud-2.5-191206.udpipe'
Content type 'application/octet-stream' length 16309608 bytes (15.6 MB)
==================================================
downloaded 15.6 MB
Downloading finished, model stored at 'udpipe_models/english-ewt-ud-2.5-191206.udpipe'
> model <- udpipe_load_model(info$file_model)
> text <- "Housing costs are unaffordable."
> annotation <- udpipe_annotate(model, x = text, parser = "none")
> ann <- as.data.frame(annotation)
> ann[, c("token", "lemma", "upos")]
token lemma upos
1 Housing housing ADJ
2 costs cost NOUN
3 are be AUX
4 unaffordable unaffordable ADJ
5 . . PUNCT
> candidates <- subset(ann, upos %in% c("NOUN", "ADJ", "VERB"))
> candidates[, c("token", "lemma", "upos")]
token lemma upos
1 Housing housing ADJ
2 costs cost NOUN
4 unaffordable unaffordable ADJ| Code | What it does (slide 78) |
|---|---|
library(udpipe) | Loads the installed R package |
dir.create(...) | Creates a folder for the model file |
udpipe_download_model | Downloads the model; keeps an existing file |
udpipe_load_model | Reads the model into memory |
udpipe_annotate | Applies the model to our sentence |
as.data.frame(annotation) | Converts the result into a table |
Output on slide 79: Housing → ADJ, costs → NOUN (lemma cost), are → AUX, unaffordable → ADJ. The token is the observed form, the lemma is the predicted base form, and upos is the predicted part of speech. The local O01 output matches this exactly. Discussion: do you accept Housing → ADJ?
| Method | Role of POS and token relations (slide 80) |
|---|---|
| Candidate filtering | Keep nouns or adjectives for human review |
| TextRank | Filter candidates by POS; rank them in a co-occurrence network |
| Dependency extraction | Find words along grammatical links (e.g. a noun and its modifiers); requires turning on the parser |
TextRank: ranking candidate terms
Data: Obama’s 2013 inaugural address, built into quanteda (examples/W4_keywords_real.R, no C01 needed). Nodes = candidate lemmas; edges = adjacent noun/adjective pairs; PageRank uses pair counts and neighbour scores. Actual output on slide 82: new 0.0161, same 0.0096, endure 0.0095, nation 0.0094, common 0.0092, hard 0.0083; with the caveat that new is generic and some endure tokens are tagged as nouns.
# Real political speech: Obama 2013 inaugural address. No C01 required.
# Source: https://quanteda.io/reference/data_corpus_inaugural.html
# install.packages(c("quanteda", "udpipe", "textrank", "igraph"))
# The model is saved in udpipe_models under your current working directory.
# O01: POS candidates (model download on first run)
# install.packages("udpipe") # run once before class
library(udpipe)
dir.create("udpipe_models", showWarnings = FALSE)
info <- udpipe_download_model("english-ewt",
model_dir = "udpipe_models", overwrite = FALSE)
model <- udpipe_load_model(info$file_model)
library(quanteda)
library(textrank)
speech <- corpus_subset(data_corpus_inaugural, Year == 2013)
text <- as.character(speech)
ann <- as.data.frame(udpipe_annotate(model, x = text,
parser = "none"))
# Mark candidates, retaining punctuation and other tokens as separators.
keep <- ann$upos %in% c("NOUN", "ADJ")
# This implementation connects immediately adjacent eligible tokens.
# ngram_max controls output phrase length, not the co-occurrence window.
result <- textrank_keywords(ann$lemma, relevant = keep,
ngram_max = 2, sep = " ")
scores <- sort(result$pagerank$vector, decreasing = TRUE)
print(round(head(scores, 6), 4))
# Inspect observed adjacent pairs. cooc is the pair occurrence count.
pairs <- cooccurrence(ann$lemma, relevant = keep)
print(head(pairs, 3))
print(pairs[pairs$term1 == "new" | pairs$term2 == "new", ])
# TextRank (3/3): print the top five and draw their neighbours.
# Scores come from the full TextRank network; we show a smaller part here.
print(round(head(scores, 5), 4))
library(igraph)
top5 <- names(head(scores, 5))
links <- subset(pairs,
term1 %in% top5 | term2 %in% top5)
g <- graph_from_data_frame(links, directed = FALSE)
set.seed(4)
plot(g, layout = layout_with_fr(g),
vertex.size = 6, vertex.color = "#7cae96",
vertex.label.color = "#314f4f",
vertex.label.cex = 1.5,
edge.width = E(g)$cooc)
# Each line is an observed adjacent noun/adjective pair.
# A thicker line means that pair occurs more often.
# Try head(scores, 10), rerun from top5 onwards, and compare the network.
# We do not recompute PageRank on this smaller graph.
# Inspect model predictions before accepting a candidate.
print(ann[ann$lemma == "endure", c("token", "lemma", "upos")])
# Phrase output: freq counts occurrences; it is NOT the PageRank score.
print(head(result$keywords))
# High centrality does not establish relevance or negative evaluation.> library(udpipe)
> dir.create("udpipe_models", showWarnings = FALSE)
> info <- udpipe_download_model("english-ewt",
+ model_dir = "udpipe_models", overwrite = FALSE)
> model <- udpipe_load_model(info$file_model)
> library(quanteda)
Package version: 4.5.1
Unicode version: 17.0
ICU version: 78.3
Parallel computing: 2 of 2 threads used.
See https://quanteda.io for tutorials and examples.
> library(textrank)
> speech <- corpus_subset(data_corpus_inaugural, Year == 2013)
> text <- as.character(speech)
> ann <- as.data.frame(udpipe_annotate(model, x = text,
+ parser = "none"))
> keep <- ann$upos %in% c("NOUN", "ADJ")
> result <- textrank_keywords(ann$lemma, relevant = keep,
+ ngram_max = 2, sep = " ")
> scores <- sort(result$pagerank$vector, decreasing = TRUE)
> print(round(head(scores, 6), 4))
new we require nation common these
0.0125 0.0122 0.0112 0.0090 0.0089 0.0083
> pairs <- cooccurrence(ann$lemma, relevant = keep)
> print(head(pairs, 3))
term1 term2 cooc
1 individual freedom 2
2 new job 2
3 fellow citizen 1
> print(pairs[pairs$term1 == "new" | pairs$term2 == "new", ])
term1 term2 cooc
2 new job 2
30 require new 1
31 new response 1
57 new idea 1
79 new industries 1
> print(round(head(scores, 5), 4))
new we require nation common
0.0125 0.0122 0.0112 0.0090 0.0089
> library(igraph)
Attaching package: ‘igraph’
The following objects are masked from ‘package:stats’:
decompose, spectrum
The following object is masked from ‘package:base’:
union
> top5 <- names(head(scores, 5))
> links <- subset(pairs,
+ term1 %in% top5 | term2 %in% top5)
> g <- graph_from_data_frame(links, directed = FALSE)
> set.seed(4)
> plot(g, layout = layout_with_fr(g),
+ vertex.size = 6, vertex.color = "#7cae96",
+ vertex.label.color = "#314f4f",
+ vertex.label.cex = 1.5,
+ edge.width = E(g)$cooc)
>
> print(ann[ann$lemma == "endure", c("token", "lemma", "upos")])
token lemma upos
872 endures endure VERB
1303 enduring endure VERB
2281 enduring endure VERB
> print(head(result$keywords))
keyword ngram freq
1 we 1 148
2 be 1 57
3 nation 1 8
4 these 1 8
5 citizen 1 7
6 we be 2 6| Rank | Slide 82 (instructor’s run) | Local (udpipe 0.8.16, textrank 0.3.1, english-ewt 2.5) |
|---|---|---|
| 1 | new 0.0161 | new 0.0125 |
| 2 | same 0.0096 | we 0.0122 |
| 3 | endure 0.0095 | require 0.0112 |
| 4 | nation 0.0094 | nation 0.0090 |
| 5 | common 0.0092 | common 0.0089 |
| 6 | hard 0.0083 | these 0.0083 |
The first two co-occurrence pairs (individual–freedom 2, new–job 2) match the slides; the third differs (slides: other–nation 2; local: fellow–citizen 1). The local POS tagging looks faulty: diagnostics showed the pronoun we tagged as NOUN 5 times and as NUM 8 times, so it was treated as a candidate; all three forms of endure were tagged as VERB (the slides say some were tagged as nouns). Possible causes (unverified): on this aarch64 machine the first udpipe compilation was aborted for lack of memory and it was recompiled with -O0; or the package/model versions differ from the instructor’s. The same model gives exactly the slide-79 result for the single O01 sentence (Housing costs are unaffordable.). Please treat the numbers on slides 82–83 as authoritative; the local output only illustrates that “POS-tagging errors directly change the TextRank candidates” — which is exactly why slide 82 asks you to review them by hand.
Named entities (Flair, optional Python)
POS tags word classes; NER finds names and their types. Result on slide 85: Barack Obama → PER, United Nations → ORG, New York → LOC; United Nations is one entity span.
examples/W4_flair_ner.py requires pip install flair (including PyTorch) and downloads the ner-fast model on first run; Flair is not installed on this build machine, so these notes did not rerun it, and the results above are quoted from slide 85.
Slide 86: “The minister praised the NHS but criticized its funding.” — mentioning an organization does not mean the speaker supports it; an entity mention is not a stance.
Embeddings and LLMs can propose candidate terms
Seed concept → suggested terms → examples in the corpus → researcher review. Embeddings can suggest related expressions; LLMs can propose variants or organize candidate lists; but antonyms and unrelated associations may also appear. Keep an independent human benchmark: these tools assist dictionary development; they cannot certify validity.
Extending to Chinese text
| Choice | Example |
|---|---|
| Segmentation | Are relevant expressions split incorrectly? |
| Character normalization | Are traditional/simplified and variant characters merged appropriately? |
| Entity aliases | Do abbreviations link to the correct institution? |
| Negation and context | Does the phrase express support, criticism or a quotation? |
Validate within the language and political domain of the project. Supplement (not from the lecture): for example, 「不」, 「沒有」 and 「未必」 (not / not have / not necessarily) often sit right before the evaluative word in Chinese; whether the segmenter cuts 「不好」 (not good) into one word or two directly determines whether the dictionary can match 「好」 (good).
Five sentences, three labelling methods
Label them yourself first, then see how the dictionary labels them:
> library(quanteda)
> dictionary_path <- "Dictionaries/teaching_affect.dic"
> sentences <- c(
+ "This policy is good.",
+ "This policy is bad.",
+ "This policy is not good.",
+ "Excellent, another tax increase.",
+ "The committee met on Tuesday."
+ )
> own_dictionary <- dictionary(file = dictionary_path, format = "LIWC")
> sentence_tokens <- tokens(sentences, remove_punct = TRUE)
> matched_tokens <- tokens_lookup(sentence_tokens, own_dictionary, capkeys = FALSE)
> matched_dfm <- dfm(matched_tokens)
> matched <- as.matrix(matched_dfm)
> net <- matched[, "positive"] - matched[, "negative"]
> total_matches <- rowSums(matched)
> status <- rep("balanced", length(sentences))
> status[net > 0] <- "positive"
> status[net < 0] <- "negative"
> status[total_matches == 0] <- "unmatched"
> dictionary_result <- data.frame(
+ id = seq_along(sentences), sentence = sentences,
+ positive = matched[, "positive"], negative = matched[, "negative"],
+ dictionary_status = status, row.names = NULL
+ )
> print(dictionary_result, row.names = FALSE)
id sentence positive negative dictionary_status
1 This policy is good. 1 0 positive
2 This policy is bad. 0 1 negative
3 This policy is not good. 1 0 positive
4 Excellent, another tax increase. 1 0 positive
5 The committee met on Tuesday. 0 0 unmatched
> assumed_latency <- data.frame(
+ method = c("Dictionary", "Transformer classifier", "Prompted LLM"),
+ sentences_per_batch = 5L,
+ assumed_seconds = c(0.02, 0.30, 3.00)
+ )
> cat("\nFICTIONAL batch times, not measurements. No Transformer or LLM was run.\n")
FICTIONAL batch times, not measurements. No Transformer or LLM was run.
> print(assumed_latency, row.names = FALSE)
method sentences_per_batch assumed_seconds
Dictionary 5 0.02
Transformer classifier 5 0.30
Prompted LLM 5 3.00
> cat("\nCheck negation and possible irony; unmatched does not establish neutral sentiment.\n")
Check negation and possible irony; unmatched does not establish neutral sentiment.The timing comparison on slide 90 is hypothetical (dictionary 0.02 s, transformer 0.30 s, LLM 3.00 s), and the instructor’s script says so explicitly: “FICTIONAL batch times, not measurements. No Transformer or LLM was run.” Can faster labelling answer the research question? What validation is still needed?
Back to your project + the four after-class Lab tasks
The final part of the slides brings all the concepts back to “writing the methods section” and “your own project”. Then come the four tasks of the after-class Lab (45–60 minutes, ungraded, no submission); all output below is from local runs of W4/lab/Lab_Session_W4.R and answers/Lab_Session_W4_Answers.R.
What the methods section should report
- Corpus scope, source and unit of analysis.
- Dictionary source, version, language and modifications.
- Rules for matching, preprocessing, the denominator and zeros.
- Design and results of human validation, and the remaining errors.
- Code and access information sufficient to audit the whole workflow.
Applying the concepts to your project
Sentence frames on slide 92: I want to measure …, not just count …; my unit of analysis is …; one possible false positive is …; one possible false negative is …; I will validate this measure with …. Extending the opening question: what further rules are needed to identify negative evaluations of household conditions? Slide 93: is a dictionary right for your project? List two strengths and two limitations; how do you trade off speed, transparency and context sensitivity?
Chapter 14 has a research plan builder that turns these sentence frames into Markdown.
O02: your own policy dictionary (optional challenge)
Add one justified energy-policy term, then work in pairs: find one passage that supports it and one possible false positive.
my_dict <- dictionary(list(energy = c("energy", "gas bills")))
matched <- tokens_lookup(discovery_tokens, my_dict)
my_dfm <- dfm(matched)
my_counts <- as.numeric(my_dfm[, "energy"])
sum(my_counts > 0)
my_context <- kwic(discovery_tokens, "energy", window = 6)
head(my_context, 3)The KWIC reading exercise in Chapter 02 and the dictionary validation bench in Chapter 07 can serve as an online version of O02.
Lab task 1: read the dictionary, inspect the matches
After the Setup block (same as C01; it runs source("workflow.R")), first read the raw .dic file:
> readLines("Dictionaries/teaching_affect.dic")
[1] "%" "1 positive" "2 negative" "%" "good 1" "excellent 1" "success 1"
[8] "successful 1" "improve 1" "bad 2" "failure 2" "crisis 2" "harm 2" "harmful 2"
> toy_sentiment <- dictionary(file = "Dictionaries/teaching_affect.dic",
+ format = "LIWC")
> toy_sentiment
Dictionary object with 2 key entries.
- [positive]:
- excellent, good, improve, success, successful
- [negative]:
- bad, crisis, failure, harm, harmful> texts <- c("The policy is good.", "The policy is not good.")
> example_tokens <- tokens(texts, remove_punct = TRUE)
> example_dfm <- dfm(example_tokens)
> example_hits <- dfm_lookup(example_dfm, toy_sentiment)
> counts <- convert(example_hits, to = "data.frame")
> counts
doc_id positive negative
1 text1 1 0
2 text2 1 0> word_count <- ntoken(example_tokens) > positive <- counts$positive > negative <- counts$negative > net_score <- 100 * (positive - negative) / word_count > net_score text1 text2 25 20
25 and 20: one positive match divided by 4 words and by 5 words. The second sentence scores lower because not adds to the denominator, not because the rule recognized the negation.
> # The setup above created these five named examples.
> check_texts
good negated unmatched
"The policy is good." "The policy is not good." "The minister spoke today."
balanced empty
"A good plan with a bad outcome." ""
> check_tokens <- tokens(check_texts, remove_punct = TRUE)
> check_dfm <- dfm(check_tokens)
> check_hits <- dfm_lookup(check_dfm, toy_sentiment)
> convert(check_hits, to = "data.frame")
doc_id positive negative
1 good 1 0
2 negated 1 0
3 unmatched 0 0
4 balanced 1 1
5 empty 0 0
> # Prepared by workflow.R using the three formulas in the table above.
> check_scores
doc_id tokens positive negative net_per100 coverage_per100 balance no_match
1 good 4 1 0 25 25.00000 1 FALSE
2 negated 5 1 0 20 20.00000 1 FALSE
3 unmatched 4 0 0 0 0.00000 NA TRUE
4 balanced 7 1 1 0 28.57143 0 FALSE
5 empty 0 0 0 NA NA NA TRUELab task 2: change one energy-policy rule
- 1 — relevant: discusses energy production, supply, prices, affordability or transition (e.g. electricity bills, heating costs, renewables, coal-mine closures). One substantive passage is enough; the speaker need not support the policy.
- 0 — not relevant: political
power, an unrelated legislativebill, personalenergyand teargasdo not count. General climate discussion counts only when it is linked to energy. - Unsure: leave blank, write down why, and discuss before scoring. Do not treat unsure as 0.
> policy_entries <- read.csv("Dictionaries/energy_policy.csv")
> head(policy_entries)
version category pattern
1 v1 energy energy
2 v1 energy power
3 v1 energy electric*
4 v1 energy gas
5 v1 energy bill*
6 v2 energy energy
> # Read the v1 patterns, then put them in a dictionary category.
> v1_entries <- subset(policy_entries, version == "v1")
> energy_v1 <- dictionary(list(energy = v1_entries$pattern))
> v2_entries <- subset(policy_entries, version == "v2")
> energy_v2 <- dictionary(list(energy = v2_entries$pattern))
> energy_v1
Dictionary object with 1 key entry.
- [energy]:
- energy, power, electric*, gas, bill*
> energy_v2
Dictionary object with 1 key entry.
- [energy]:
- energy, electric*, gas bill*, renewab*, solar*, wind farm*, fossil fuel*
> contexts <- kwic(discovery_tokens, pattern = c("power", "gas", "bill*"),
+ valuetype = "glob", window = 8)
> head(contexts, 10)
Keyword-in-context with 10 matches.
[speech_0006, 32] opinion. on the question whether any additional | power |
[speech_0006, 37] whether any additional power is given by the | bill |
[speech_0006, 233] the case. the third object of the | bill |
[speech_0006, 254] acquired for public purposes. in effect the | bill |
[speech_0008, 24] special act undertakers will be over-ridden by this | bill |
[speech_0019, 38] were very widely published and there was a | power |
[speech_0019, 165] considered these proposals very carefully. he had | power |
[speech_0021, 36] it would facilitate the further progress of the | bill |
[speech_0021, 61] to avoid lengthening the committee stage. this | bill |
[speech_0021, 426] to remove them. there are in the | bill |
is given by the bill to local authorities
to local authorities in blighted areas—not war-damaged areas—i
is to regulate the compensation payable in respect
provides that where land is compulsorily acquired for
, particularly as regards special provisions which may
, which we can be quite certain was
under the act to submit them to the
if we were to have a reply to
is a very drastic measure. the housing
at present no default powers. if a > first_id <- contexts$docname[1] > original <- subset(speeches, doc_id == first_id) > original$text [1] "I will try again, but I repudiate the idea that I had any irritation at all: that is a matter of opinion. On the question whether any additional power is given by the Bill to local authorities in blighted areas—not war-damaged areas—I say the answer is, \"Yes.\" To start with, it affords greater expedition in acquisition. It absolves them from personal notifications and allows them to give bl … [truncated]
> energy_revised <- dictionary(list(
+ energy = c("energy", "wind farm*", "electric*", "gas", "bill*")
+ ))
> revision_texts <- c(
+ wind = "The government should approve new wind farms.",
+ authority = "Parliament must retain the power to question ministers."
+ )
> revision_tokens <- tokens(revision_texts, remove_punct = FALSE)
> before_tokens <- tokens_lookup(revision_tokens, energy_v1, capkeys = FALSE)
> before_counts <- convert(dfm(before_tokens), to = "data.frame")
> after_tokens <- tokens_lookup(revision_tokens, energy_revised, capkeys = FALSE)
> after_counts <- convert(dfm(after_tokens), to = "data.frame")
> data.frame(sentence = before_counts$doc_id,
+ before = before_counts$energy,
+ after = after_counts$energy)
sentence before after
1 wind 0 1
2 authority 1 0The answers’ reading: wind goes from 0 to 1 and authority from 1 to 0 — this change fixes two examples. Next, check which errors remain in the other sentences.
> matched_tokens <- tokens_lookup(discovery_tokens, energy_v2, capkeys = FALSE)
> match_dfm <- dfm(matched_tokens)
> head(match_dfm, 6)
dfm of 6 documents x 1 feature (0 occurrences, 100.00% sparsity) and 12 docvars.
features
docs energy
speech_0001 0
speech_0002 0
speech_0003 0
speech_0004 0
speech_0005 0
speech_0006 0Lab task 3: inspect development-set errors
> # Read the labelled teaching examples and generate predictions explicitly.
> synthetic <- read.csv("Data/synthetic_validation.csv")
> example_corpus <- corpus(synthetic, text_field = "text", docid_field = "doc_id")
> example_tokens <- tokens(example_corpus, remove_punct = FALSE)
> # Apply v1, then v2. Each matched phrase counts once.
> v1_matches <- tokens_lookup(example_tokens, energy_v1, capkeys = FALSE)
> v1_dfm <- dfm(v1_matches)
> v1_binary <- dfm_weight(v1_dfm, scheme = "boolean")
> v1_predictions <- convert(v1_binary, to = "data.frame")
> synthetic$v1 <- v1_predictions$energy
> v2_matches <- tokens_lookup(example_tokens, energy_v2, capkeys = FALSE)
> v2_dfm <- dfm(v2_matches)
> v2_binary <- dfm_weight(v2_dfm, scheme = "boolean")
> v2_predictions <- convert(v2_binary, to = "data.frame")
> synthetic$v2 <- v2_predictions$energy> dev <- subset(synthetic, split == "development")
> dev[, c("doc_id", "text", "human", "v1", "v2")]
doc_id text human v1 v2
1 dev01 We must address rising energy prices. 1 1 1
2 dev02 Electricity supply needs public investment. 1 1 1
3 dev03 Families cannot afford their gas bills. 1 1 1
4 dev04 Subsidies should support solar panels. 1 0 1
5 dev05 The government should approve new wind farms. 1 0 1
6 dev06 We should reduce fossil fuel imports. 1 0 1
7 dev07 Parliament must retain the power to question ministers. 0 1 0
8 dev08 This bill reforms criminal sentencing. 0 1 0
9 dev09 Police used tear gas at the protest. 0 1 0
10 dev10 The minister brought energy to the debate. 0 1 1
11 dev11 Schools need a larger budget. 0 0 0
12 dev12 The committee discussed train timetables. 0 0 0The worked answers list only the development sentences that v1 gets wrong:
> errors <- subset(dev, v1 != human)
> errors[, c("doc_id", "text", "human", "v1", "v2")]
doc_id text human v1 v2
4 dev04 Subsidies should support solar panels. 1 0 1
5 dev05 The government should approve new wind farms. 1 0 1
6 dev06 We should reduce fossil fuel imports. 1 0 1
7 dev07 Parliament must retain the power to question ministers. 0 1 0
8 dev08 This bill reforms criminal sentencing. 0 1 0
9 dev09 Police used tear gas at the protest. 0 1 0
10 dev10 The minister brought energy to the debate. 0 1 1The answers’ explanation: the development sentences show why one might drop bare power, gas and bill* and add expressions for renewables, solar panels, wind farms and fossil fuels. The “dictionary validation bench” in Chapter 07 lets you do this step interactively.
Lab task 4: freeze v2 and compute precision/recall/F1 on the test sentences
> test <- subset(synthetic, split == "test")
> # 0 = not relevant; 1 = relevant. Keep both categories in the table.
> predicted <- factor(test$v2, levels = c(0, 1))
> human <- factor(test$human, levels = c(0, 1))
> table(predicted, human)
human
predicted 0 1
0 5 2
1 1 4> # Compare each dictionary prediction with its teaching label. > TP <- sum(test$v2 == 1 & test$human == 1) > FP <- sum(test$v2 == 1 & test$human == 0) > FN <- sum(test$v2 == 0 & test$human == 1) > TN <- sum(test$v2 == 0 & test$human == 0) > precision <- TP / (TP + FP) > recall <- TP / (TP + FN) > F1 <- 2 * TP / (2 * TP + FP + FN) > c(TP = TP, FP = FP, FN = FN, TN = TN) TP FP FN TN 4 1 2 5 > c(precision = precision, recall = recall, F1 = F1) precision recall F1 0.8000000 0.6666667 0.7272727
> errors <- subset(test, v2 != human)
> errors[, c("doc_id", "text", "human", "v2")]
doc_id text human v2
17 test05 The closure of coal mines requires a transition plan. 1 0
18 test06 Heating tariffs must remain affordable. 1 0
22 test10 Her energy transformed the committee. 0 1- v2: TP = 4, FP = 1, FN = 2, TN = 5; precision 0.80, recall 0.667, F1 0.727, matching slide 95.
- answers: v1 finds the same 4 relevant sentences but also flags 4 irrelevant ones.
- Adding
coalorheatingnow would be revising the dictionary with information from the test sentences; evaluating the new version needs a new test set. - These results describe only the 12 test sentences; evaluating parliamentary speeches requires human labels for those speeches.
W6 preview: five texts, one hard decision
W5 (October 9) is a holiday; W6 (October 16) covers human coding and classification. For now, label five texts with a short codebook, explain one uncertain decision, and keep the dictionary predictions separate; about 10 minutes, no model training and no upload.
> development_texts <- subset(coding_template, split == "development")
> preview <- head(development_texts, 5)
> preview[, c("doc_id", "text")]
doc_id
1 speech_3484
2 speech_0299
3 speech_3560
4 speech_1238
5 speech_0963
… [truncated]
1 That is why I have appealed to the Disraeli wing of the Conservative party, which formed a radical, reforming Government who addressed some of the abuses of power of previous Governments. In appealing to Conservative Members to support the amendments, I draw their attention to the congruity between the intent and content of the amendments and the policies set out in their party's manifesto at th … [truncated]
2 … [truncated]
3 This petition is signed by more … [truncated]
4 … [truncated]
5 … [truncated]Optional: party comparison
> # quanteda adds counts within each party.
> party_matches <- tokens_lookup(policy_tokens, energy_v2, capkeys = FALSE)
> party_dfm <- dfm(party_matches)
> party_dfm <- dfm_group(party_dfm, groups = party)
> # Group original word counts separately to preserve the denominator.
> party_words <- dfm(toks)
> party_words <- dfm_group(party_words, groups = party)
> party_summary <- convert(party_dfm, to = "data.frame")
> party_summary$tokens <- ntoken(party_words)
> party_summary$per1000 <- 1000 * party_summary$energy / party_summary$tokens
> head(party_summary, 6)
doc_id energy tokens per1000
1 Alliance Party of Northern Ireland 0 44 0.00000000
2 Communist Party of Great Britain 0 36 0.00000000
3 Conservative 151 447158 0.33768824
4 Democratic Unionist Party 1 11814 0.08464534
5 Green Party of England and Wales 2 217 9.21658986
6 Independent 1 1394 0.71736011Note that the Lab version aggregates with dfm_group(); the result should match v2 in party_rates from Chapter 06 (likewise aggregating first, then dividing).
Run checklist
Reading guide
Three required readings (slide 98). None of their full texts is in the course repo, so the cards below only summarize what the slides say (with slide numbers) and do not cite paper pages. The only relevant full text legitimately in the repo is Grimmer & Stewart (2013) from W1; its dictionary passages are cited with paper page numbers.
Denny & Spirling (2018)
Rauh (2018)
Proksch, Lowe, Wäckerle & Soroka (2019)
Grimmer & Stewart (2013) (repo: W1/papers/Grimmer2013.pdf)
Further reading and software (slide 99)
- Grimmer, Roberts & Stewart (2022). Text as Data. Chapters 5 and 16.
- Hvitfeldt & Silge. Supervised Machine Learning for Text Analysis in R. Chapters on tokenization and stopwords (online).
- Eichorst & Lin (2019). “Resist to Commit.” The Journal of Politics 81(1): 15–32.
- Boyle et al. (2025). “Catalysts for progress? Mapping policy insights from energy research.” Energy Research & Social Science 121: 103955.
- Software: quanteda (dictionaries, KWIC, matching), quanteda.textstats (frequencies, collocations, keyness), UDPipe/TextRank, ggplot2, Flair (Python NER), irr (coder agreement), LIWC.
The full texts of the further readings above are not in the repo either; for close reading, they are available through the NTU Library or the university VPN.
Common pitfalls and glossary
Ten common pitfalls
Treating a “mention” as an “evaluation”
Mentioning inflation is not a negative evaluation of household conditions (slide 3). Topic words measure attention, evaluative words measure sentiment, and the two must be tied to the same target.
Treating sentiment as stance
Negative language can describe a problem while supporting a policy (slides 4, 66).
Comparing counts without dividing by length
speech_2792 has 20 bill* matches but 1.48 per 100 words; speech_4435 has only 4 but scores 5.80 (slide 31).
Treating 0 as neutral
No matches and offsetting positives and negatives both give 0; an empty text is NA (slide 34).
Removing stop words before matching negation or phrases
not is in stopwords("en") and gets deleted (slide 36); phrases must be matched before stop words are removed (slide 29).
Wildcards that are too broad
bill* catches billion and billericay (slide 28).
Claiming recall after reading only matched passages
False negatives can only be found among unmatched passages (slide 50).
Continuing to tune the dictionary on the test set
Test only after freezing; once test information is used, a new test set is needed (slides 24, 95; Lab answers).
Treating a group-level correlation as classification accuracy
The 0.9 in Proksch et al. is a group-level correlation (slide 63).
Assuming an off-the-shelf dictionary is suitable / licensed
Availability is not evidence of suitability (slide 14); importing a file is not obtaining a license (slide 68).
Flip cards: formulas and definitions
Glossary
Final review, research plan and references
My progress
Final review (20 questions)
Research plan builder
References (per slides 98–99 and citations on individual slides)
- Boyle et al. (2025). “Catalysts for progress? Mapping policy insights from energy research.” Energy Research & Social Science 121: 103955.
- Denny, M. J., and A. Spirling (2018). Political Analysis 26(2): 168–189.
- Eichorst, J., and N. C. N. Lin (2019). “Resist to Commit.” The Journal of Politics 81(1): 15–32.
- Grimmer, J., M. E. Roberts, and B. M. Stewart (2022). Text as Data. Princeton University Press. Chapters 5 and 16.
- Grimmer, J., and B. M. Stewart (2013). “Text as Data.” Political Analysis 21(3): 267–297.
- Hvitfeldt, E., and J. Silge (2022). Supervised Machine Learning for Text Analysis in R.
- Lin, W.-F. (2023). “Linguistic inquiry and word count in sport and exercise.” Physical Education Journal 56(1): 1–16. doi:10.6222/pej.202303_56(1).0001 (slide 75)
- Lin, W.-F., C.-L. Huang, Y.-C. Lin, C.-L. Lee, and J. W. Pennebaker (2020). “The Revision of the Chinese Linguistic Inquiry and Word Count Dictionary 2015.” Survey Research – Method and Application 45: 73–118. doi:10.7014/SRMA.2020100004 (slide 76)
- Proksch, S.-O., W. Lowe, J. Wäckerle, and S. Soroka (2019). Legislative Studies Quarterly 44(1): 97–131.
- Rauh, C. (2018). Journal of Information Technology & Politics 15(4): 319–343.