W2: Text Preparation in R and Python: Collaborative Workflow
W1 argued that "text can be treated as data"; in W2 we actually turn text into data: selecting documents, cleaning, tokenizing, and building a DFM (document-feature matrix), asking at every step: "What does this choice make my measurement lose?"
Learning objectives for this week
Slide 2 lists four objectives; the last one (clean and tokenize text, build a DFM, and evaluate preprocessing choices) is the backbone of these notes. The instructor also points out that this is Week 4 content introduced early; W4 builds on it with dictionaries, sentiment analysis, and validation.
- Set up RStudio and Positron for text analysis with R and Python.
- Organize code with GitHub and submit written coursework through shared Overleaf projects.
- Inspect supplied corpora and check project data feasibility: coverage, metadata, and access.
- Clean and tokenize text, build a DFM, and evaluate preprocessing choices.
After finishing a chapter, come back and tick the objectives you feel you can now achieve (saved only in this browser):
The GitHub / Overleaf collaboration part of the slides appears only in the learning objectives and has no slides of its own, so these notes do not add operational details for it. Steps for installing and opening R, Python, RStudio, and Positron are in Chapters 02 and 10.
Concept map: from a pile of text to a matrix
Click a box to see its explanation. The workflow is compiled from slide 14 (the analysis-steps figure from Welbers et al. 2017) and slide 15 (the objects used in this course).
Static summary: research question and population → select documents (the observed corpus) → import and encoding checks → string cleaning (stringr) → corpus (text + metadata) → tokens (tokenization, phrases, stopwords) → DFM (counts, binary, TF-IDF; trimming) → analysis (dictionaries, classification, topic models, scaling, similarity); KWIC lets you go back to the original text at any time.
The two practice datasets
- d1: Health workers need health services.
- d2: The government supports health services.
- d3: Workers do not support the policy.
- d4: The government supports the policy.
Deliberately tiny so that you can inspect every token and verify every count. Chapters 05, 06, and 08 all use it.
lab/Data/hc_sample_1945_2025.rds: 5,000 House of Commons speech contributions, 1945–2025.- 13 columns: date, agenda, speechnumber, speaker, party, party.facts.id, chair, terms, text, speech_url, parliament, iso3country, party_raw.
- The sampling seed recorded in the data file's attributes is 20260706; the sampling frame excluded speeches by the chair (Speaker) and speeches with a missing speaker, party, or text (checked with R
str(hoc)). - 5,000 is the number of speeches, not the number of MPs: the same MP can speak many times.
How to use these notes
- The left side lists 15 chapters; on the right (wide screens) is the slide panel, which turns to the matching page automatically when you scroll to a passage marked "Slide N"; you can also click the badge.
- The R code and output in Chapters 10–12 come from actually running
Lab_Session_W2_Answers.Rlocally (R 4.5.3, quanteda 4.5.1, quanteda.textstats 0.97.2, quanteda.textplots 0.96.1, stringr 1.6.0, dplyr 1.2.1, ggplot2 4.0.3; Linux aarch64), compared line by line against the output in the instructor's answer HTML. - Passages and toy demos marked "Supplement (not from the lecture)" are additional explanations, not slide content.
- There are three kinds of interactive components: real-data (exported directly from the Lab's 5,000 speeches), toy-intuition (small examples), and practice (answer boxes, flip cards, judgment questions, fill-in forms).
- The instructor's self-study advice: run the Lab section by section and read every output; when you have a question, bring the exercise number, the relevant code, and the output or error message.
Self-check
nrow(hoc) is the number of speeches, not the number of MPs.Five QTA principles and selecting documents
Bias begins before preprocessing. This chapter covers where texts come from, whose texts are more likely to be preserved, and what a "document" is.
Five principles of quantitative text analysis
- Domain knowledge defines the research problem and relevant evidence.
- Human judgment guides interpretation and validation.
- Discovery and testing require distinct stages.
- The task determines which methods are useful.
- Validation evaluates whether the measure fits the claim.
Sources: Schoonvelde (2026); Grimmer et al. (2022).
Computers only count; what to count, how to interpret it, and whether the counts can support your conclusion are the researcher's responsibility. These five principles come back at every preprocessing choice.
Selecting documents: Chapter 4 of Grimmer et al. (2022)
Classroom example: measuring expressed preference for coffee.
| Design choice | Example |
|---|---|
| Target population | Thai-language public posts about coffee in a specified month |
| Quantity of interest | Share of those posts expressing positive preference for coffee |
| Observed corpus | Posts returned by one platform API and a specified keyword search |
Found data: document how the texts were produced, preserved and retrieved. The next step is to examine what the collection process leaves out.
Selection bias begins before preprocessing
| Source of bias | Example | Research consequence |
|---|---|---|
| Resources | Well-funded groups archive more documents | Available texts overrepresent some actors |
| Incentives | Politicians publish strategically | Public statements differ from private beliefs |
| Medium | A platform limits length or visibility | The medium shapes expression |
| Retrieval | Searching only for “economy” | Relevant texts with other words disappear |
Interactive: which kind of selection bias is this?
The scenarios below are exercises written for these notes (Supplement (not from the lecture)); the categories follow the four sources on slide 5. Pick an answer to see the explanation.
Corpus boundaries and document units
| Decision | Example | What to record |
|---|---|---|
| Population | Parliamentary speech contributions | Chamber, actors, dates |
| Inclusion | All contributions in selected debates | Rule and exclusions |
| Document unit | One contribution per row | How segments were defined |
| Identifier | A persistent doc_id | Links to source and metadata |
Changing the unit to "speaker-day" or "party-year" changes the comparison itself. The Lab in Chapter 10 demonstrates this: 81 Engagements speeches become 364 "documents" once the unit is changed to sentences.
Sources and import routes
| Source | Typical route (R packages) | First check |
|---|---|---|
| Existing corpus | Download plus codebook | Coverage and sampling |
| TXT, CSV, TSV | readr, data.table, base R | Encoding and columns |
| JSON or API | jsonlite, httr2 | Pagination and identifiers |
| HTML or XML | rvest, xml2 | Boilerplate and structure |
| PDF or DOCX | pdftools, readtext | Reading order and document boundaries |
Scanned PDFs may need OCR before they contain usable text.
Self-check
The tool landscape: quanteda, UDPipe, spaCy, Flair, and R + Python
R can prepare text, call these tools, and analyze the returned annotations or vectors. The tools overlap, and their capabilities depend on the language, model, and task.
The R text-analysis toolkit in 2017
Slide 8 reproduces Table 1 of Welbers, Van Atteveldt & Benoit (2017) (text-analysis operations and the corresponding R packages) and notes that this is a historical package overview (2017); package responsibilities and APIs have since changed. The original Table 1 groups the operations into three parts: data preparation (importing text, string operations, preprocessing, DTM, filtering and weighting), analysis (dictionary, supervised / unsupervised machine learning, text statistics), and advanced topics (advanced NLP, word positions and syntax). (Welbers et al. 2017, p. 247)
| Operation (Welbers et al. 2017, Table 1) | Package used in the article | Alternatives (excerpt) |
|---|---|---|
| importing text | readtext | jsonlite, XML, antiword, readxl, pdftools |
| string operations | stringi | stringr |
| preprocessing / DTM / filtering and weighting | quanteda | tm, tidytext, Matrix, etc. |
| unsupervised machine learning | topicmodels | quanteda, stm, austin, text2vec |
| advanced NLP | spacyr | coreNLP, cleanNLP, koRpus |
Beyond 2017: annotation and embeddings
| Tool / access from R | Model type | Output and use |
|---|---|---|
| UDPipe 1: R udpipe | Supervised annotation pipeline trained on a treebank | Tokens, lemmas, POS, dependency labels |
| UDPipe 2: R + REST API | Neural annotation with contextual embeddings | Linguistic annotations; current models use BERT-based representations |
| Flair: R reticulate + Python (flaiR; Liao et al., 2023) | Contextual string embeddings or Transformer embeddings | Word/document vectors; models for NER, tagging and classification |
FlairEmbeddings uses character language models; TransformerWordEmbeddings uses models such as BERT.
quanteda, UDPipe, spaCy, and Flair
| Tool / access | Main emphasis | Typical output |
|---|---|---|
| quanteda (R) | Corpus management and feature analysis | Corpus, tokens, DFM; KWIC and TF-IDF |
| UDPipe (R / API) | Linguistic annotation using trained models | Tokens, lemmas, POS, UD dependency labels |
| spaCy (Python) | Configurable NLP pipelines | Tokens, POS, dependencies, named entities |
| Flair (Python; flaiR is an R wrapper) | Embeddings and neural task models | Vectors; entity labels, POS, text categories |
The tools can work together: for example, lemmas or selected annotations can become features in a quanteda DFM (slide 44 in Chapter 07 sketches the code).
Flip cards: what does this tool / function do?
The backs of the cards follow slides 9–10, 19, 15 and the Lab's function tables; slide numbers are shown on each card.
R and Python in one workflow
One possible application on slide 11: compare the meanings of policy statements.
Static version: Prepare in R (stringr, quanteda: clean text and preserve document IDs) → Represent in Python (sentence-transformers: encode texts as semantic vectors) → Evaluate in R (statistical models and plots: validate similarities and interpret patterns). Each stage follows the research question.
- R's
reticulatepackage imports Python modules and calls their functions. - The instructor frequently used reticulate during their PhD studies (2018–2022).
- It converts supported objects between R and Python.
- Record the Python environment as well as R packages.
- R and Python scripts exchange files such as CSV or Parquet.
- A stable document ID connects inputs and outputs.
- Check row order, encoding and data types at each handoff.
The takeaway of slide 12: an IDE organizes the work; object or file exchange connects the languages.
Positron: one IDE for R and Python
- In 2022, RStudio the company became Posit, reflecting its broader support for data science across languages.
- Posit developed Positron for multilingual data science; R and Python have built-in support, with consoles and data exploration.
- The RStudio IDE remains a separate, maintained product.
- Our classroom examples use R.
Self-check
Text-analysis steps, four objects, and import checks
Analysis can take the "matrix" route (DFM), or it can keep token positions or other representations. First be clear about which kind of object you are holding.
The sequence of text-analysis operations
Slide 14 reproduces Figure 1 of Welbers et al. (2017) (Order of text analysis operations for data preparation and analysis, p. 247). The slide's reminder: the branch matters—analysis can use a matrix, token positions, or other representations. Welbers et al. focus mainly on bag-of-words, i.e., using only the word frequencies of each text and ignoring word positions (p. 246), and discuss approaches that keep word positions and syntax under advanced topics (pp. 258–261).
Objects used in this session
| Object | Contents | Use |
|---|---|---|
| Data frame | Text, identifiers, metadata | Import checks and joins |
corpus | Text with document variables (docvars) | Subsets and metadata access |
tokens | Sequences of tokens (order preserved) | Phrase matching and context inspection (KWIC) |
dfm | Documents × features | Counts and weighted representations |
stringr handles strings. quanteda provides the corpus → tokens → DFM workflow.
- data.frame: the Lab's
hoc, one row per speech; text and metadata are all columns. - corpus:
corpus(hoc, text_field = "text"); the other columns become docvars, still 5,000 documents. - tokens: each document becomes a sequence of words; you can use
tokens_compound()andkwic(). - dfm: only counts remain and order is gone; you can use
dfm_group(),dfm_trim(),textstat_keyness().
Import checks and encoding
texts <- readLines("data/speeches.txt", encoding = "UTF-8")
length(texts)
head(texts)- Confirm the source encoding rather than guessing from appearance.
- Inspect accented characters and Chinese text after import.
- Count missing texts and duplicated identifiers.
- Check whether a row is a line, paragraph, or whole document.
Adding an encoding = "UTF-8" argument does not repair text whose source encoding was wrongly identified.
The Lab's collocation output contains sinn fã (count 15), and the same table also has sinn fein (count 17). The é in "Féin" was most likely decoded with the wrong encoding somewhere upstream in the data processing and turned into garbled text (mojibake), so the same party name was split into two features. This is exactly why slide 16 asks you to "inspect accented characters" after import. (Output in Chapter 11, find_collocations; the diagnosis of the cause is an inference made in these notes, not from the lecture.)
A parliamentary example
| Field | Value in the source slide |
|---|---|
| Date | 1997-01-20 |
| Speaker | William Hague |
| Party | Conservative |
| Agenda | Public Expenditure [Oral Answers To Questions > Wales] |
Text includes [Interruption.], DRAMATICALLY, and !!!. The slide asks: which elements are metadata, meaningful language, or recording conventions?
Interactive: metadata, language, or recording convention?
Choose one category for each element. After you choose, the treatment suggested on slide 18 and the "information that may be lost" are shown. Note: for some elements the answer depends on the research question.
| Element | Possible treatment | Information at stake |
|---|---|---|
| Speaker and party | Store as metadata | Who speaks |
[Interruption.] | Remove or extract into an indicator | Parliamentary interaction |
| Capitalization | Preserve or lowercase | Names and emphasis |
| Numbers | Keep, normalize, or remove | Years, budgets, percentages |
| Repeated punctuation | Preserve or simplify | Rhetorical emphasis |
Keep an untouched copy of the raw text.
Self-check
[Interruption.]?Cleaning depends on the research question: stringr and regular expressions
Cleaning is not neutral. Every rule keeps some information and throws some away; that is why you need an audit trail.
String operations with stringr
| Function | Purpose | Example use |
|---|---|---|
str_detect() | Test whether a pattern appears (TRUE / FALSE) | Flag bracketed annotations |
str_extract() | Retrieve the first match | Extract a year |
str_remove_all() | Remove all matches | Delete selected annotations |
str_replace_all() | Replace matches | Standardize separators |
str_squish() | Normalize whitespace | Remove repeated spaces and leading/trailing whitespace |
str_to_lower() | Change case | Merge case variants |
The Lab also uses str_which() (which positions match), str_locate() / str_locate_all() (start and end character positions of matches), str_extract_all(), and str_to_title(); see Chapter 10.
Bracket patterns and unintended deletion
s <- "Trade [Commons] and jobs [Wales]" str_remove_all(s, "\\[.*\\]") str_remove_all(s, "\\[[^\\[\\]]*\\]") |> str_squish()
> s <- "Trade [Commons] and jobs [Wales]" > str_remove_all(s, "\\[.*\\]") [1] "Trade " > str_remove_all(s, "\\[[^\\[\\]]*\\]") |> str_squish() [1] "Trade and jobs"
The slide: the second pattern handles separate, non-nested bracket groups.
Interactive: greedy vs. non-greedy bracket removal
| Rule | Result |
|---|---|
str_remove_all(s, "\\[.*\\]") | |
str_remove_all(s, "\\[[^\\[\\]]*\\]") |> str_squish() | |
The Lab's rule str_replace_all(s, "\\s*\\[.*\\]", "") |
A cleaning example with an audit trail
agenda_raw <- " Export Trade [Commons] -- vol. 407 "
agenda_clean <- agenda_raw |>
str_remove_all("\\[[^\\[\\]]*\\]") |>
str_to_lower() |>
str_replace_all("[^[:alnum:][:space:]]", " ") |>
str_squish()
agenda_clean> agenda_raw <- " Export Trade [Commons] -- vol. 407 "
> agenda_clean <- agenda_raw |>
+ str_remove_all("\\[[^\\[\\]]*\\]") |>
+ str_to_lower() |>
+ str_replace_all("[^[:alnum:][:space:]]", " ") |>
+ str_squish()
> agenda_clean
[1] "export trade vol 407"This rule preserves numbers and removes punctuation; another task may need a different rule. An "audit trail" means storing the cleaned result in a new column (the Lab uses agenda_clean) while keeping the original column, so you can compare them at any time.
Interactive: regex playground (real Lab agenda labels)
The data are the Lab's hoc$agenda (4,000+ distinct labels with their counts, exported from R; plus 206 NA). Enter a pattern to see how many speeches match, with the top 12 labels listed (matches highlighted). JS regex is broadly similar to R/stringr (ICU) but not identical (for example, the POSIX class [:alnum:] is not supported in JS); R gives the authoritative result. Type a single backslash here (JS style); in an R string you need two.
Try it: compare war and \bwar\b. Which labels are the extra ones?
war also matches words that contain these three letters, such as “warfare”, “towards”, “award”, and “Stewart”; \bwar\b matches only the standalone word, but “post-war” still counts because the hyphen is treated as a word boundary. The Lab's word_boundary_examples demonstrates exactly this (Chapter 10). Whether post-war should count depends on the research question.
Self-check
str_remove_all("Trade [Commons] and jobs [Wales]", "\\[.*\\]")?.* consumes everything from the first [ to the last ]." Export Trade [Commons] -- vol. 407 "?agenda_clean instead of overwriting agenda?A four-sentence toy corpus: corpus, tokens, and types
Using four sentences short enough to check word by word, we look closely at what R does at each step. All R output in this chapter comes from actually running the slides' source code (the setup chunk of week2.qmd) locally.
Creating a corpus
library(quanteda)
library(stringr)
raw <- data.frame(
doc_id = c("d1", "d2", "d3", "d4"),
text = c("Health workers need health services.",
"The government supports health services.",
"Workers do not support the policy.",
"The government supports the policy."),
stringsAsFactors = FALSE
)
corp <- corpus(raw, docid_field = "doc_id", text_field = "text")
docnames(corp)> 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(stringr)
> raw <- data.frame(
+ doc_id = c("d1", "d2", "d3", "d4"),
+ text = c("Health workers need health services.",
+ "The government supports health services.",
+ "Workers do not support the policy.",
+ "The government supports the policy."),
+ stringsAsFactors = FALSE
+ )
> corp <- corpus(raw, docid_field = "doc_id", text_field = "text")
> docnames(corp)
[1] "d1" "d2" "d3" "d4"Each row supplies one text. The remaining columns become document variables (docvars). Here docid_field = "doc_id" makes the document names d1–d4 instead of the default text1–text4.
The Lab's corpus(hoc, text_field = "text") does not specify docid_field, so the document names are text1…text5000 (see the summary output in Chapter 10). If you later hand data to Python or other files, slide 12 recommends a stable document ID.
Tokens, types, and vocabulary
Text: “Health services need health workers.”
| Representation | Tokens | Distinct types |
|---|---|---|
| Case and punctuation retained | 6 | 6 |
| Lowercase, punctuation removed | 5 | 4 |
After normalization: health, services, need, health, workers. A token is an occurrence. A type is a distinct form under the chosen representation.
t24 <- "Health services need health workers." t_keep <- tokens(t24) t_norm <- tokens(t24, remove_punct = TRUE) |> tokens_tolower() c(tokens = ntoken(t_keep), types = ntype(t_keep)) c(tokens = ntoken(t_norm), types = ntype(t_norm)) as.character(t_norm)
> t24 <- "Health services need health workers."
> t_keep <- tokens(t24)
> t_norm <- tokens(t24, remove_punct = TRUE) |> tokens_tolower()
> c(tokens = ntoken(t_keep), types = ntype(t_keep))
tokens.text1 types.text1
6 6
> c(tokens = ntoken(t_norm), types = ntype(t_norm))
tokens.text1 types.text1
5 4
> as.character(t_norm)
[1] "health" "services" "need" "health" "workers" Verified locally in R: ntoken() / ntype() give 6 / 6 and 5 / 4, matching slide 24. With case retained, “Health” and “health” are two types, and the period is also a token.
Interactive: token / type counter
The JS uses a simplified tokenization rule (splitting on whitespace and punctuation; hyphens and abbreviations are handled differently from quanteda), meant only to build intuition. Neither box ticked = 6 / 6; both ticked = 5 / 4.
Tokens in R text analysis and LLMs
| Comparison | Common R text-analysis workflow | Typical LLM workflow |
|---|---|---|
| Common units | Words; optionally characters or sentences | Often subwords; can include whole words, characters or byte units |
| Segmentation depends on | Package, tokenizer and your settings | The model’s tokenizer and vocabulary |
| Main use | Word counts, DFM, TF-IDF, topic models | Token IDs used for model input and text generation |
One word can become several LLM tokens. R can call either kind of tokenizer; the workflow determines the unit.
Tokenizing with explicit choices
toks <- tokens(corp, remove_punct = TRUE) |> tokens_tolower() as.list(toks)[[1]]
> toks <- tokens(corp, remove_punct = TRUE) |> + tokens_tolower() > as.list(toks)[[1]] [1] "health" "workers" "need" "health" "services"
The five tokens of d1: health, workers, need, health, services. When texts contain hyphens, URLs, abbreviations, or non-Latin scripts, always inspect the output. (An example from the Lab: “right hon.”, common in parliamentary text, makes sentence splitting go wrong; see Chapter 10.)
Self-check
Preprocessing choices and information loss
The key question on slide 27: how does the choice affect the intended measure? Not "what is the standard practice?"
Preprocessing choices and information loss
| Choice | Possible benefit | Possible loss |
|---|---|---|
| Lowercase | Merge Health and health | Proper-name distinctions |
| Remove stopwords | Reduce frequent function words | Negation or writing style |
| Stem or lemmatize | Merge some word forms | Differences in meaning |
| Trim rare features | Reduce vocabulary size | Rare but important concepts |
Stopwords and negation
sw <- setdiff(stopwords("en"), c("not", "no", "nor"))
toks_content <- tokens_remove(toks, pattern = sw)
as.character(tokens_remove(toks, pattern = stopwords("en"))["d3"])
as.character(toks_content["d3"])
length(stopwords("en"))> sw <- setdiff(stopwords("en"), c("not", "no", "nor"))
> toks_content <- tokens_remove(toks, pattern = sw)
> as.character(tokens_remove(toks, pattern = stopwords("en"))["d3"])
[1] "workers" "support" "policy"
> as.character(toks_content["d3"])
[1] "workers" "not" "support" "policy"
> length(stopwords("en"))
[1] 175| Rule applied to document d3 | Remaining tokens |
|---|---|
| Standard English stopword list | workers support policy |
| List that retains negation | workers not support policy |
Retaining not preserves a clue; but a unigram model still needs a way to use its scope. The local output confirms that stopwords("en") has 175 words and that not, no, and nor are all in it.
The bag-of-words representation
A DFM stores one row per document and one column per feature. Below are selected columns from the count DFM built from the "negation-retaining" tokens:
x <- dfm(toks_content)
as.matrix(x[, c("health", "workers", "government", "policy", "not")])> x <- dfm(toks_content)
> as.matrix(x[, c("health", "workers", "government", "policy", "not")])
features
docs health workers government policy not
d1 2 1 0 0 0
d2 1 0 1 0 0
d3 0 1 0 1 1
d4 0 0 1 1 0Identical to the table on slide 29 (health = 2 for d1). Features can also represent phrases or other categories.
What word counts cannot recover
After lowercasing, “Workers support government.” and “Government support workers.” have exactly the same unigram counts:
wo <- tokens(c(a = "Workers support government.", b = "Government support workers."),
remove_punct = TRUE) |> tokens_tolower() |> dfm()
as.matrix(wo)> wo <- tokens(c(a = "Workers support government.", b = "Government support workers."),
+ remove_punct = TRUE) |> tokens_tolower() |> dfm()
> as.matrix(wo)
features
docs workers support government
a 1 1 1
b 1 1 1- Word order tells you who supports whom.
- Negation requires relations between words.
- Ambiguous words need context.
- Irony may depend on context beyond the sentence.
N-grams and syntax can preserve some additional information. (The R check that the two rows above have identical counts was run additionally for these notes.)
Multiword expressions
phrase_toks <- tokens(
"We support the armed forces.",
remove_punct = TRUE
) |> tokens_tolower()
tokens_compound(
phrase_toks,
pattern = phrase("armed forces")
)> phrase_toks <- tokens(
+ "We support the armed forces.",
+ remove_punct = TRUE
+ ) |> tokens_tolower()
> tokens_compound(
+ phrase_toks,
+ pattern = phrase("armed forces")
+ )
tokens of 1 document (4 tokens, 4 types).
text1 :
[1] "we" "support" "the" "armed_forces"armed_forces becomes a single feature. Detect phrases before deleting words that may be part of them. The Lab uses the same method to merge “Prime Minister”, “House of Commons”, “European Union”, and “National Health Service” (Chapter 11).
Bigrams and the order of operations
tokens("Workers do not support the policy.",
remove_punct = TRUE) |>
tokens_tolower() |>
tokens_ngrams(n = 2)
tokens("Workers do not support the policy.",
remove_punct = TRUE) |>
tokens_tolower() |>
tokens_remove(stopwords("en")) |>
tokens_ngrams(n = 2)> tokens("Workers do not support the policy.",
+ remove_punct = TRUE) |>
+ tokens_tolower() |>
+ tokens_ngrams(n = 2)
tokens of 1 document (5 tokens, 5 types).
text1 :
[1] "workers_do" "do_not" "not_support" "support_the" "the_policy"
> tokens("Workers do not support the policy.",
+ remove_punct = TRUE) |>
+ tokens_tolower() |>
+ tokens_remove(stopwords("en")) |>
+ tokens_ngrams(n = 2)
tokens of 1 document (2 tokens, 2 types).
text1 :
[1] "workers_support" "support_policy" The bigrams on the slide: workers_do, do_not, not_support, support_the, the_policy. If the original adjacency matters, create bigrams before removing stopwords. Deleting words first creates pairs that were not originally adjacent. The second output above (run additionally for these notes) shows the consequence of doing it the other way round: after the standard stopword list deletes do, not, and the, a workers_support that does not exist in the original text is produced, and the negation disappears entirely.
Collocations and grammatical features
| Feature strategy | Example | Judgment needed |
|---|---|---|
| Known phrase | armed_forces | Which phrases matter? |
| Statistical collocation | Candidates such as northern_ireland | Is the association substantively useful? |
| Selection by part of speech (POS) | Nouns, verbs, adjectives | Which grammatical roles fit the task? |
Frequent or strongly associated word pairs are only candidate features; inspect their usage before adding them to a measurement rule. In the Lab's real output, northern ireland occurs 338 times with λ ≈ 12.41 (Chapter 11).
Stemming and lemmatization
| Method | Example | Limitation |
|---|---|---|
| Stemming | studies → studi | A stem may not be a dictionary word |
| Lemmatization | studies may → study | Accuracy depends on language and context |
| Explicit replacement | Map forces to force | Only handles the mappings you provide |
Neither method guarantees correct semantic grouping. A dictionary built from full words may fail to match stemmed features. Welbers et al. (2017, p. 252) also point out an ordering issue: if you stem before removing stopwords, “during” becomes “dure” and no longer matches “during” in the stopword list.
Interactive: preprocessing switchboard (four-sentence toy corpus)
Each switch corresponds to one quanteda step. The default settings = the settings of slides 26–28 and 46 (remove punctuation, lowercase, remove the "negation-retaining" stopword list), which should give a 4 × 9 DFM. The stopword list is stopwords("en") (175 words) exported from R. The JS only reproduces the demo; R gives the authoritative result.
Self-check
Multilingual text: English whitespace is not a universal word boundary
Chinese, Japanese, and Thai need segmentation models; stopwords and word-form tools are tied to a language. UDPipe gives you tokens, parts of speech (POS), and dependency relations.
The UDPipe output on slides 38–42 consists of model predictions that the instructor transcribed from an earlier presentation HTML into the slide source (week2.qmd); slide 36 also notes that it is a "speaker demonstration: interpreting prepared model output". These notes did not rerun UDPipe (that requires downloading language models, and Thai also requires calling the UDPipe 2 REST API); the interactive components below use these slide outputs, each labeled with its slide number.
Language and model requirements
- English whitespace is not a universal word boundary.
- Chinese segmentation needs inspection.
- Stopwords and word-form tools are language-specific.
- A DFM can use word or phrase features.
- Pretrained models expect their own tokenizer.
- Preserve the input distinctions that the model needs.
A BoW preprocessing recipe should not automatically become an LLM input recipe.
UDPipe models: Japanese, Chinese, Thai
| Input language | Access from R | Model |
|---|---|---|
| Japanese | udpipe: local UDPipe 1 | japanese-gsd (UD 2.5) |
| Traditional Chinese | udpipe: local UDPipe 1 | chinese-gsd (UD 2.5) |
| Thai | httr2: UDPipe 2 API | thai-tud (UD 2.17) |
- All three provide segmented
tokens and predictedupos(POS). - Dependency parsing adds heads and relation labels.
lemmais the predicted base form; this Thai model returns_(not available).
Annotating UTF-8 text with UDPipe
library(udpipe)
# Set model_path to a downloaded Chinese-GSD model.
zh_model <- udpipe_load_model(model_path)
ann_zh <- udpipe_annotate(zh_model, x = "我喜歡咖啡。",
doc_id = "zh_coffee", parser = "default") |> as.data.frame()
ann_zh[c("token_id", "token", "upos",
"head_token_id", "dep_rel")]parser = "default"adds dependency syntax on top of tokens and POS.head_token_ididentifies the head;dep_rellabels the relation. Head 0 marks the sentence root.- Chinese uses chinese-gsd; English uses english-ewt; Thai uses R + the UDPipe 2 API.
Interactive: segmentation and dependency viewer (output from slides 38–42)
The segmentation comparison on slide 38 (excluding punctuation): Thai has 3 tokens (ฉัน PRON / ชอบ VERB / กาแฟ NOUN), so the Thai model finds word boundaries; Japanese has 6 tokens (私 PRON / は ADP / コーヒー NOUN / が ADP / 好き ADJ / です AUX), so particles and auxiliaries remain separate tokens; Chinese has 3 tokens (我 PRON / 喜歡 VERB / 咖啡 NOUN), so multi-character words can form single tokens. Slide 39: "I like coffee" in all three languages is nsubj / root / obj, with head IDs 2 / 0 / 2 in each case.
Model errors and negation
- Japanese “政府は医療従事者を支援する。”: 政府 (NOUN, nsubj → 6), 医療 (compound → 4), 従事者 (obj → 6), 支援 (VERB, root), する (AUX).
- Traditional Chinese “政府支持醫療工作者。”: a model error—
支持is tagged NOUN, and者(PART) is predicted as root. The slide's reminder: inspect the original sentence before interpreting these outputs. - Negation “政府不支持刪減醫療預算。”:
不(ADV) attaches to支持(ID 3) as advmod. Keeping only NOUN and VERB removes “不”, so the feature list loses the negation. (Pick this sentence in the viewer above and try unticking ADV.)
From Thai syntax to research measurement
Static version: POS marks word classes, and dependency relations link the subject to the predicate and its object → link the subject to “like” and its object, and confirm the statement is affirmative → this example: positive preference for coffee = 1 → research question: which objects receive more expressions of positive preference? Corpus-level measurement: the share of documents mentioning an object that express positive preference. Arrows point from head to dependent. This also echoes the “coffee preference” research design from Chapter 01, slide 4.
Turning UDPipe annotations into quanteda tokens and a DFM
# Assume ann_multi contains an annotation table.
a <- subset(ann_multi, upos != "PUNCT")
a <- a[order(a$doc_id, a$sentence_id,
as.integer(a$token_id)), ]
ja_tokens <- split(a$token[a$doc_id == "ja_01"],
a$doc_id[a$doc_id == "ja_01"])
ja_dfm <- dfm(as.tokens(ja_tokens), tolower = FALSE)Use as.tokens() to keep the existing segmentation; a Chinese DFM is built the same way.
A: workers (NOUN) / support (VERB) / reform (NOUN); B: workers (NOUN) / oppose (VERB) / reform (NOUN). The POS tags are the illustrative tags shown on the slide.
Rows = documents; columns = the features you chose; cells = counts. Noun filtering loses the stance contrast; dictionary counts still need validation.
Self-check
Build a DFM, look at term and document frequencies, TF-IDF, back to context
The DFM is the common input to every later method (dictionaries, classification, topic models, scaling). Every number in this chapter can be verified by hand.
Build and inspect a DFM
dim(x) topfeatures(x, 6) featnames(x)
> dim(x)
[1] 4 9
> topfeatures(x, 6)
health workers services government supports policy
3 2 2 2 2 2
> featnames(x)
[1] "health" "workers" "need" "services" "government"
[6] "supports" "not" "support" "policy" 4 documents × 9 features; the most frequent are health 3, workers 2, services 2, government 2, supports 2, policy 2. Rows keep the document IDs; the full DFM contains features beyond the 5 columns from Chapter 06 (need, supports, support, services).
Among the 9 features, supports (d2, d4) and support (d3) are two different features. Merging them requires stemming, lemmatization or an explicit replacement (Chapter 06, slide 34)—and each method has a cost.
Term frequency and document frequency
colSums(x)[c("health", "workers", "not")]
docfreq(x)[c("health", "workers", "not")]
x_trim <- dfm_trim(x, min_docfreq = 2,
docfreq_type = "count")
featnames(x_trim)> colSums(x)[c("health", "workers", "not")]
health workers not
3 2 1
> docfreq(x)[c("health", "workers", "not")]
health workers not
2 2 1
> x_trim <- dfm_trim(x, min_docfreq = 2,
+ docfreq_type = "count")
> featnames(x_trim)
[1] "health" "workers" "services" "government" "supports"
[6] "policy" | Feature | Total occurrences | Documents containing it |
|---|---|---|
| health | 3 | 2 |
| workers | 2 | 2 |
| not | 1 | 1 |
The threshold min_docfreq = 2 removes not. Rare features can still carry crucial meaning. The local output (featnames(x_trim) above) shows 6 features left after trimming: health, workers, services, government, supports, policy; need, not and support with df = 1 are dropped—even support (the only verb in d3) disappears.
Counts, binary indicators and TF-IDF
| Representation | What a cell means | Possible use |
|---|---|---|
| Count | Number of occurrences | Frequency-based measurement |
| Binary | Whether the feature appears | Comparison by presence/absence |
| TF-IDF | Count adjusted by how common the feature is in the corpus | Document retrieval or comparison |
The choice changes how much repeated words contribute. Model requirements may restrict which representation is appropriate.
Writing out the TF-IDF formula
This course uses raw counts and base-10 logarithms:
TF-IDF(d, t) = count(d, t) × log10(N / df(t))
- N is the number of documents in the reference corpus; df(t) is the number of documents containing feature t.
- A feature that appears in every document has IDF = 0 under this formula.
- Different normalization and smoothing rules produce different weights.
x_weighted <- dfm_tfidf(x, scheme_tf = "count",
scheme_df = "inverse", base = 10)
round(as.matrix(x_weighted[, "health"]), 4)
round(as.matrix(x_weighted), 4)> x_weighted <- dfm_tfidf(x, scheme_tf = "count",
+ scheme_df = "inverse", base = 10)
> round(as.matrix(x_weighted[, "health"]), 4)
features
docs health
d1 0.6021
d2 0.3010
d3 0.0000
d4 0.0000
> round(as.matrix(x_weighted), 4)
features
docs health workers need services government supports not support policy
d1 0.6021 0.301 0.6021 0.301 0.000 0.000 0.0000 0.0000 0.000
d2 0.3010 0.000 0.0000 0.301 0.301 0.301 0.0000 0.0000 0.000
d3 0.0000 0.301 0.0000 0.000 0.000 0.000 0.6021 0.6021 0.301
d4 0.0000 0.000 0.0000 0.000 0.301 0.301 0.0000 0.0000 0.301health: N = 4, df = 2, so IDF = log10(2) ≈ 0.3010; d1 count 2 → 0.6021, d2 count 1 → 0.3010, d3 and d4 are 0. Local R matches slide 50 exactly.
Interactive: TF-IDF calculator
Pick a feature to see N, df, IDF and each document's weight. You can also add a 5th document to the reference corpus and see how the weight of the same word changes when N changes (the 5th document is a supplement, not from the lecture).
Checking context with KWIC
kwic(toks, pattern = "support*", window = 3)
> kwic(toks, pattern = "support*", window = 3)
Keyword-in-context with 3 matches.
[d2, 3] the government | supports | health services
[d3, 4] workers do not | support | the policy
[d4, 3] the government | supports | the policy Three matches: d2 “the government supports health services”, d3 “workers do not support the policy”, d4 “the government supports the policy”. Before treating a word count as evidence of “support for a policy”, read the words around it—in d3, support is directly preceded by not.
Note: KWIC uses toks (tokens before stopword removal), so not and the are visible. The pattern "support*" is a glob wildcard that matches support and supports.
Self-check
dfm_trim(x, min_docfreq = 2, docfreq_type = "count") removes not because?What is a DFM used for? And: how sensitive are results to preprocessing?
The same DFM can feed many methods, but each method has different input requirements: Wordfish and topic models need counts, classification needs training labels, Wordscores needs reference scores, and similarity can use TF-IDF.
Wrap-up: DFM, KWIC, TF-IDF
| Tool | What it lets you do |
|---|---|
| DFM | Represent document features for comparison and modelling |
| KWIC | Read words in context to check what feature counts mean |
| TF-IDF | Emphasize distinctive words for retrieval and similarity |
Wordfish is an unsupervised method that places texts on one dimension: word-count DFM → Wordfish → relative positions of documents. Use: comparing party manifestos or speeches. Input: counts, not TF-IDF weights. Interpret and validate the scale before calling it “ideology”.
Research applications of a DFM
| Research goal | Method | Output |
|---|---|---|
| Estimate positions | Wordfish / Wordscores | Relative positions of documents |
| Predict categories | Supervised classifier | Issue or stance labels |
| Study issue attention | LDA / STM / keyATM | Topics and topic proportions |
| Measure a concept | Dictionary | Category counts or proportions |
| Compare documents | Cosine similarity / clustering | Similarity or document clusters |
Inputs matter: Wordfish and these topic models use counts; classification needs training labels; Wordscores needs reference scores; similarity can use TF-IDF. These methods are covered in depth in W4 (dictionaries), W7 (scaling), W8 (topic models) and other weeks.
Interactive: method matching
Pick one method for each item; after answering, the input that method needs (counts, labels, reference scores or TF-IDF) is shown. The scenarios were written for these notes (supplement).
Applied studies introduced in the slides
| Category | Study | One-line summary on the slides |
|---|---|---|
| Topic models | STM: Roberts et al. (2014) | Compare topics in survey responses across respondent groups. |
| Topic models | keyATM: Eshima et al. (2024) | Guide topics with selected keywords to study policy attention. |
| Text scaling | Wordfish: Slapin & Proksch (2008) | Estimate relative party positions from word counts in manifestos. Corpus: 25 German party manifestos from five parties over five elections (1990–2005); finding: the Greens moved toward the centre over time; reading the axis: higher values mean left, and the sign is a convention (Figure 1A, p. 714). |
| Text scaling | Wordscores: Lowe (2008); Laver et al. (2003) | Position new texts using reference texts with known scores. Irish confidence debate: 3 reference speeches (+1 / −1) → score the other 55 speeches; higher scores mean more pro-government (Laver et al. 2003, Figure 3, p. 328). |
| TF-IDF | Text similarity: Blumenau (2021) | Track whose language later speakers use in House of Commons debates. |
| TF-IDF | Stance classification: Bestvater & Monroe (2023) | Classify political support or opposition with TF-IDF plus SVM. |
TF-IDF provides weighted features; the analysis determines what we measure. The full texts of these papers are not in the course repo; these notes only restate what is on the slides (see Chapter 13).
Sensitivity to preprocessing
| Comparison | Check | Interpretation |
|---|---|---|
| With / without stopwords | Negation and grammatical context | Which distinctions disappear? |
| Unigrams / phrases | Compound concepts | Which matches change? |
| Full / trimmed vocabulary | Dropped features and empty rows | Which documents lose evidence? |
| Counts / TF-IDF | Relative contribution of features | Do results depend on weighting? |
Keep the corpus and research question fixed while comparing a chosen rule. The “preprocessing switch lab” in Chapter 06 and the “trimming threshold” and “keyness explorer” in Chapter 11 can all be used to carry out these four comparisons.
Self-check
Lab sections 1–2: strings, regex, cleaning agenda labels, building a corpus
The code below comes from W2/lab/answers/Lab_Session_W2_Answers.R (the example parts are identical to the student version Lab_Session_W2.R); the output is from an actual local run (R 4.5.3, quanteda 4.5.1, quanteda.textstats 0.97.2, quanteda.textplots 0.96.1, stringr 1.6.0, dplyr 1.2.1, ggplot2 4.0.3; Linux aarch64).
Class setup: install, open, run
- Download and install R and Python 3, then install RStudio Desktop and Positron.
- Try the console: type
1 + 1in R andprint(1 + 1)in Python; both return 2. - Open
Lab_Session_W2.Rinlab/and install the packages in the R console (only once):
install.packages(c("dplyr", "stringr", "ggplot2",
"quanteda", "quanteda.textstats", "quanteda.textplots"))Set the working directory to W2/lab/, with the Data/ folder next to the script. Take-home skill: open a .R file in RStudio or Positron and run the Lab yourself. The Lab is not graded and nothing is submitted; no Python, language models or APIs are needed.
# First use only: uncomment these lines to install the packages.
# install.packages(c("dplyr", "stringr", "ggplot2", "quanteda",
# "quanteda.textstats", "quanteda.textplots"))
library(dplyr)
library(stringr)
library(ggplot2)
library(quanteda)
library(quanteda.textstats)
library(quanteda.textplots)> # First use only: uncomment these lines to install the packages.
> # install.packages(c("dplyr", "stringr", "ggplot2", "quanteda",
> # "quanteda.textstats", "quanteda.textplots"))
> library(dplyr)
Attaching package: ‘dplyr’
The following objects are masked from ‘package:stats’:
filter, lag
The following objects are masked from ‘package:base’:
intersect, setdiff, setequal, union
> library(stringr)
> library(ggplot2)
> library(quanteda)
> library(quanteda.textstats)
> library(quanteda.textplots)The “masked” messages when loading dplyr are normal: dplyr's filter() masks the stats function of the same name. (The instructor's HTML hides these messages with message: false.)
Local output vs. the instructor's answer HTML
We compared the local output chunk by chunk with the instructor's output in answers/Lab_Session_W2_Answers.html (after whitespace normalization; the log is in tad/labs/W2/compare_with_instructor_html.txt):
- All numbers and table contents match: 5000, 271, 81, 364, 368, 2995, 279, 23 × 30640, 23 × 5474, 23 × 3424, all collocation λ and z values, and all keyness χ² values.
- The only textual difference: the
summary()header, which prints “corpus of 5,000 documents” locally (quanteda 4.5.1) and “Corpus consisting of 5000 documents” in the instructor's HTML. This is a print-format difference between package versions; the content is the same. - The slides themselves contain no Lab numbers (only 5,000 records and 1945–2025), so there are no discrepancies that need to be shown side by side.
Read the data and create the year variable
# Find the supplied data. If asked, choose the .rds file in W2/lab/Data.
paths <- c("W2/lab/Data/hc_sample_1945_2025.rds",
"lab/Data/hc_sample_1945_2025.rds",
"../Data/hc_sample_1945_2025.rds",
"Data/hc_sample_1945_2025.rds")
found <- paths[file.exists(paths)]
if (length(found) == 0) found <- file.choose()
data_path <- normalizePath(found[1])
setwd(dirname(dirname(data_path)))
hoc <- readRDS(data_path)
nrow(hoc)> # Find the supplied data. If asked, choose the .rds file in W2/lab/Data.
> paths <- c("W2/lab/Data/hc_sample_1945_2025.rds",
+ "lab/Data/hc_sample_1945_2025.rds",
+ "../Data/hc_sample_1945_2025.rds",
+ "Data/hc_sample_1945_2025.rds")
> found <- paths[file.exists(paths)]
> if (length(found) == 0) found <- file.choose()
> data_path <- normalizePath(found[1])
> setwd(dirname(dirname(data_path)))
> hoc <- readRDS(data_path)
> nrow(hoc)
[1] 5000hoc <- hoc |> mutate(year = as.integer(format(date, "%Y"))) hoc |> select(date, year, speaker, party, agenda, terms) |> head(5)
> hoc <- hoc |>
+ mutate(year = as.integer(format(date, "%Y")))
> hoc |>
+ select(date, year, speaker, party, agenda, terms) |>
+ head(5)
date year speaker party
1 1945-01-16 1945 Mr. Johnstone Liberal
2 1945-01-16 1945 Mr. Woodburn Labour
3 1945-01-24 1945 Mr. Eden Conservative
4 1945-01-30 1945 Vice-Admiral Taylor Conservative
5 1945-01-31 1945 Sir M. Sueter Conservative
agenda terms
1 Export Trade 72
2 Fruit and Vegetables (Short Weight) 53
3 BRITISH PRISONERS OF WAR, FAR EAST 29
4 FIGHTING SERVICES (PAY) 30
5 ROYAL NAVY (GERMAN SUBMARINE WARFARE) 50terms is the number of terms in each speech (computed by the data provider). The sampling frame excluded very short speeches, yet the first five rows still have only 29–72 terms.
String operations: extract, which, locate
agenda_labels <- hoc$agenda[1:8] agenda_labels str(agenda_labels)
> agenda_labels <- hoc$agenda[1:8] > agenda_labels [1] "Export Trade" [2] "Fruit and Vegetables (Short Weight)" [3] "BRITISH PRISONERS OF WAR, FAR EAST" [4] "FIGHTING SERVICES (PAY)" [5] "ROYAL NAVY (GERMAN SUBMARINE WARFARE)" [6] "TOWN AND COUNTRY PLANNING (SCOTLAND) BILL" [7] "WAR GRATUITIES" [8] "WATER BILL" > str(agenda_labels) chr [1:8] "Export Trade" "Fruit and Vegetables (Short Weight)" ...
str_extract(agenda_labels, "Trade") str_extract(agenda_labels, "WAR")
> str_extract(agenda_labels, "Trade") [1] "Trade" NA NA NA NA NA NA NA > str_extract(agenda_labels, "WAR") [1] NA NA "WAR" NA "WAR" NA "WAR" NA
str_extract(agenda_labels, "war") str_extract(str_to_lower(agenda_labels), "war")
> str_extract(agenda_labels, "war") [1] NA NA NA NA NA NA NA NA > str_extract(str_to_lower(agenda_labels), "war") [1] NA NA "war" NA "war" NA "war" NA
NAmeans the pattern was not found in that label, not that the whole document is missing.- Patterns are case-sensitive by default:
"war"matches none of the original labels; afterstr_to_lower(), labels 3, 5 and 7 all match. - Note that label 5 is “ROYAL NAVY (GERMAN SUBMARINE WARFARE)”—the match is part of warfare. Word boundaries in the next section deal with exactly this.
str_which(str_to_lower(agenda_labels), "war") str_which(str_to_lower(agenda_labels), "trade")
> str_which(str_to_lower(agenda_labels), "war") [1] 3 5 7 > str_which(str_to_lower(agenda_labels), "trade") [1] 1
str_locate(str_to_lower(agenda_labels), "war")
> str_locate(str_to_lower(agenda_labels), "war")
start end
[1,] NA NA
[2,] NA NA
[3,] 22 24
[4,] NA NA
[5,] 30 32
[6,] NA NA
[7,] 1 3
[8,] NA NAstr_which() returns positions (3, 5, 7; trade only at 1); str_locate() returns the start and end character positions of the first match (e.g., 1–3 for label 7, “war gratuities”). str_locate_all() returns every match (long output; see the full run_output.txt).
Regular expressions and word boundaries
speech_urls <- hoc$speech_url[1:5] speech_urls
> speech_urls <- hoc$speech_url[1:5] > speech_urls [1] "https://api.parliament.uk/historic-hansard/written_answers/1945/jan/16/export-trade#S5CV0407P0_19450116_CWA_118" [2] "https://api.parliament.uk/historic-hansard/commons/1945/jan/16/fruit-and-vegetables-short-weight#S5CV0407P0_19450116_HOC_181" [3] "https://api.parliament.uk/historic-hansard/written_answers/1945/jan/24/british-prisoners-of-war-far-east#S5CV0407P0_19450124_CWA_14" [4] "https://api.parliament.uk/historic-hansard/commons/1945/jan/30/fighting-services-pay#S5CV0407P0_19450130_HOC_309" [5] "https://api.parliament.uk/historic-hansard/written_answers/1945/jan/31/royal-navy-german-submarine-warfare#S5CV0407P0_19450131_CWA_91"
str_extract(speech_urls, "\\d") str_extract(speech_urls, "\\d+") str_extract_all(speech_urls, "\\d+")
> str_extract(speech_urls, "\\d") [1] "1" "1" "1" "1" "1" > str_extract(speech_urls, "\\d+") [1] "1945" "1945" "1945" "1945" "1945" > str_extract_all(speech_urls, "\\d+") [[1]] [1] "1945" "16" "5" "0407" "0" "19450116" "118" [[2]] [1] "1945" "16" "5" "0407" "0" "19450116" "181" [[3]] [1] "1945" "24" "5" "0407" "0" "19450124" "14" [[4]] [1] "1945" "30" "5" "0407" "0" "19450130" "309" [[5]] [1] "1945" "31" "5" "0407" "0" "19450131" "91"
str_extract(speech_urls, "\\d{4}/[a-z]{3}/\\d{2}")> str_extract(speech_urls, "\\d{4}/[a-z]{3}/\\d{2}")
[1] "1945/jan/16" "1945/jan/16" "1945/jan/24" "1945/jan/30" "1945/jan/31"example_text <- c( "The war changed British politics.", "The committee moved towards a compromise.", "Post-war trade was discussed." ) str_detect(str_to_lower(example_text), "war") str_detect(str_to_lower(example_text), "\\bwar\\b")
> example_text <- c( + "The war changed British politics.", + "The committee moved towards a compromise.", + "Post-war trade was discussed." + ) > str_detect(str_to_lower(example_text), "war") [1] TRUE TRUE TRUE > str_detect(str_to_lower(example_text), "\\bwar\\b") [1] TRUE FALSE TRUE
The loose pattern matches all three sentences; \\bwar\\b excludes towards but still matches post-war, because the hyphen counts as a word boundary. Choose the rule that matches the meaning you want. (Lab notes)
str_replace(agenda_labels, "Trade", "TRADE") str_replace_all(agenda_labels, "[aeiou]", "-")
> str_replace(agenda_labels, "Trade", "TRADE") [1] "Export TRADE" [2] "Fruit and Vegetables (Short Weight)" [3] "BRITISH PRISONERS OF WAR, FAR EAST" [4] "FIGHTING SERVICES (PAY)" [5] "ROYAL NAVY (GERMAN SUBMARINE WARFARE)" [6] "TOWN AND COUNTRY PLANNING (SCOTLAND) BILL" [7] "WAR GRATUITIES" [8] "WATER BILL" > str_replace_all(agenda_labels, "[aeiou]", "-") [1] "Exp-rt Tr-d-" [2] "Fr--t -nd V-g-t-bl-s (Sh-rt W--ght)" [3] "BRITISH PRISONERS OF WAR, FAR EAST" [4] "FIGHTING SERVICES (PAY)" [5] "ROYAL NAVY (GERMAN SUBMARINE WARFARE)" [6] "TOWN AND COUNTRY PLANNING (SCOTLAND) BILL" [7] "WAR GRATUITIES" [8] "WATER BILL"
Cleaning agenda labels
hoc |> filter(str_detect(str_to_lower(agenda), "business of the house")) |> count(agenda, sort = TRUE) |> head(10)
> hoc |>
+ filter(str_detect(str_to_lower(agenda), "business of the house")) |>
+ count(agenda, sort = TRUE) |>
+ head(10)
agenda
1 BUSINESS OF THE HOUSE
2 Business of the House
3 Business Of The House
4 BUSINESS OF THE HOUSE (FINANCE BILL)
5 Business Of The House [Defence Policy]
6 Business Of The House [Modernisation Of The House]
7 Business Of The House [Orders Of The Day > Child Support, Pensions And Social Security Bill > New Clause 9]
8 Business Of The House [Orders Of The Day > Security Service Bill]
9 Business Of The House [Orders Of The Day]
10 Business Of The House [Prayers > Bills Presented]
n
1 56
2 54
3 34
4 1
5 1
6 1
7 1
8 1
9 1
10 1The same agenda, “Business of the House”, has at least three capitalizations (56 + 54 + 34 records), plus many variants with bracketed context.
hoc <- hoc |>
mutate(
agenda_clean = agenda |>
str_to_lower() |>
str_squish() |>
str_replace_all("\\s*\\[.*\\]", ""),
agenda_clean = case_when(
agenda_clean == "business of the house" ~ "Business of the House",
agenda_clean == "points of order" ~ "Points of Order",
agenda_clean == "topical questions" ~ "Topical Questions",
str_detect(agenda_clean, "^engagements") ~ "Engagements",
TRUE ~ str_to_title(agenda_clean)
)
)
hoc |>
count(agenda_clean, sort = TRUE) |>
head(15)> hoc <- hoc |>
+ mutate(
+ agenda_clean = agenda |>
+ str_to_lower() |>
+ str_squish() |>
+ str_replace_all("\\s*\\[.*\\]", ""),
+ agenda_clean = case_when(
+ agenda_clean == "business of the house" ~ "Business of the House",
+ agenda_clean == "points of order" ~ "Points of Order",
+ agenda_clean == "topical questions" ~ "Topical Questions",
+ str_detect(agenda_clean, "^engagements") ~ "Engagements",
+ TRUE ~ str_to_title(agenda_clean)
+ )
+ )
> hoc |>
+ count(agenda_clean, sort = TRUE) |>
+ head(15)
agenda_clean n
1 <NA> 206
2 Business of the House 151
3 Engagements 81
4 Topical Questions 69
5 Finance Bill 18
6 Points of Order 15
7 European Economic Community 14
8 Debate On The Address 12
9 Budget Resolutions And Economic Situation 11
10 Northern Ireland 11
11 European Council 9
12 Housing 9
13 Local Government Finance 9
14 National Health Service 9
15 Amendment Of The Law 8Merging all labels that begin with Engagements may help a descriptive plot, but it also removes detail. Record your cleaning choices. Also note the first row of the output: 206 agendas are NA, and cleaning does not fill anything in for them.
Interactive: agenda cleaning pipeline (real 5,000 records)
Data: hoc$agenda exported from R (4,083 distinct non-NA labels + 206 NA). Toggle one step at a time and watch how the top 15 and the “number of distinct labels” change. All on = the Lab's clean_agenda_labels; the top 15 should match the R output above (checked automatically below). str_to_title() is approximated in JS.
Build and inspect a corpus
hoc_corpus <- corpus( hoc, text_field = "text" )
summary(hoc_corpus, n = 10)
> summary(hoc_corpus, n = 10)
corpus of 5,000 documents, showing 10 documents:
Text Types Tokens Sentences date
text1 53 76 2 1945-01-16
text2 40 55 1 1945-01-16
text3 26 30 1 1945-01-24
text4 30 35 3 1945-01-30
text5 43 54 1 1945-01-31
text6 236 529 16 1945-02-14
text7 81 132 3 1945-02-20
text8 43 52 1 1945-02-21
text9 26 32 1 1945-02-22
text10 58 78 3 1945-02-23
agenda speechnumber speaker
Export Trade 1164121 Mr. Johnstone
Fruit and Vegetables (Short Weight) 1164131 Mr. Woodburn
BRITISH PRISONERS OF WAR, FAR EAST 1166439 Mr. Eden
FIGHTING SERVICES (PAY) 1167553 Vice-Admiral Taylor
ROYAL NAVY (GERMAN SUBMARINE WARFARE) 1168346 Sir M. Sueter
TOWN AND COUNTRY PLANNING (SCOTLAND) BILL 1171770 Mr. Johnston
WAR GRATUITIES 1172870 Sir J. Anderson
WATER BILL 1173225 Major Mills
Committee of Inquiry 1173549 Mr. Viant
MINISTRY OF FUEL AND POWER BILL 1173930 Earl Winterton
party party.facts.id chair terms
Liberal NA FALSE 72
Labour NA FALSE 53
Conservative NA FALSE 29
Conservative NA FALSE 30
Conservative NA FALSE 50
Labour NA FALSE 489
National NA FALSE 116
Conservative NA FALSE 49
Labour NA FALSE 31
Conservative NA FALSE 64
speech_url
https://api.parliament.uk/historic-hansard/written_answers/1945/jan/16/export-trade#S5CV0407P0_19450116_CWA_118
https://api.parliament.uk/historic-hansard/commons/1945/jan/16/fruit-and-vegetables-short-weight#S5CV0407P0_19450116_HOC_181
https://api.parliament.uk/historic-hansard/written_answers/1945/jan/24/british-prisoners-of-war-far-east#S5CV0407P0_19450124_CWA_14
https://api.parliament.uk/historic-hansard/commons/1945/jan/30/fighting-services-pay#S5CV0407P0_19450130_HOC_309
https://api.parliament.uk/historic-hansard/written_answers/1945/jan/31/royal-navy-german-submarine-warfare#S5CV0407P0_19450131_CWA_91
https://api.parliament.uk/historic-hansard/commons/1945/feb/14/town-and-country-planning-scotland-bill#S5CV0408P0_19450214_HOC_306
https://api.parliament.uk/historic-hansard/commons/1945/feb/20/war-gratuities#S5CV0408P0_19450220_HOC_225
https://api.parliament.uk/historic-hansard/commons/1945/feb/21/water-bill#S5CV0408P0_19450221_HOC_266
https://api.parliament.uk/historic-hansard/commons/1945/feb/22/committee-of-inquiry#S5CV0408P0_19450222_HOC_119
https://api.parliament.uk/historic-hansard/commons/1945/feb/23/ministry-of-fuel-and-power-bill#S5CV0408P0_19450223_HOC_69
parliament iso3country party_raw year
UK-HouseOfCommons GBR Liberal 1945
UK-HouseOfCommons GBR Labour 1945
UK-HouseOfCommons GBR Conservative 1945
UK-HouseOfCommons GBR Conservative 1945
UK-HouseOfCommons GBR Conservative 1945
UK-HouseOfCommons GBR Labour 1945
UK-HouseOfCommons GBR National 1945
UK-HouseOfCommons GBR Conservative 1945
UK-HouseOfCommons GBR Labour 1945
UK-HouseOfCommons GBR Conservative 1945
agenda_clean
Export Trade
Fruit And Vegetables (Short Weight)
British Prisoners Of War, Far East
Fighting Services (Pay)
Royal Navy (German Submarine Warfare)
Town And Country Planning (Scotland) Bill
War Gratuities
Water Bill
Committee Of Inquiry
Ministry Of Fuel And Power BillThe Types / Tokens / Sentences in summary are computed on the fly by quanteda (including punctuation); e.g., text6 has 529 tokens and 16 sentences. This is defined differently from the terms column in the data (489).
ndoc(hoc_corpus)
> ndoc(hoc_corpus) [1] 5000
Still 5,000 documents: building a corpus only changes how the data are stored; it does not select or classify speeches. (Lab notes)
names(docvars(hoc_corpus)) head(docvars(hoc_corpus, "party"), 10) head(docvars(hoc_corpus, "agenda_clean"), 10)
> names(docvars(hoc_corpus)) [1] "date" "agenda" "speechnumber" "speaker" [5] "party" "party.facts.id" "chair" "terms" [9] "speech_url" "parliament" "iso3country" "party_raw" [13] "year" "agenda_clean" > head(docvars(hoc_corpus, "party"), 10) [1] "Liberal" "Labour" "Conservative" "Conservative" "Conservative" [6] "Labour" "National" "Conservative" "Labour" "Conservative" > head(docvars(hoc_corpus, "agenda_clean"), 10) [1] "Export Trade" [2] "Fruit And Vegetables (Short Weight)" [3] "British Prisoners Of War, Far East" [4] "Fighting Services (Pay)" [5] "Royal Navy (German Submarine Warfare)" [6] "Town And Country Planning (Scotland) Bill" [7] "War Gratuities" [8] "Water Bill" [9] "Committee Of Inquiry" [10] "Ministry Of Fuel And Power Bill"
as.character(hoc_corpus)[1]
> as.character(hoc_corpus)[1] text1 "In addition to discussions with a large number of individual merchants and merchant bankers, many meetings connected with our post-war trade have taken place between my Department and Export Groups, a number of which include merchants among their members. The Consultative Committee which advised my Department on its future practice and procedure included a merchant among its members, and I have invited a merchant to … [truncated; full output in tad/labs/W2/run_output.txt]
Subsetting and changing the document unit
labour_since_2010 <- corpus_subset( hoc_corpus, party == "Labour" & year >= 2010 ) ndoc(labour_since_2010) summary(labour_since_2010, n = 5)
> labour_since_2010 <- corpus_subset(
+ hoc_corpus,
+ party == "Labour" & year >= 2010
+ )
> ndoc(labour_since_2010)
[1] 271
> summary(labour_since_2010, n = 5)
corpus of 271 documents, showing 5 documents:
Text Types Tokens Sentences date
text4015 77 131 7 2010-01-12
text4017 98 163 6 2010-01-28
text4019 93 137 7 2010-02-10
text4021 53 73 3 2010-02-25
text4022 181 345 13 2010-03-03
agenda
NHS Funding [Oral Answers to Questions > Oral Answers to Questions > Health > Health]
UK Arrest Warrants (Alleged War Crimes)
Armed Forces Compensation Scheme
Topical Questions [Oral Answers to Questions > Energy and Climate Change]
Communications Allowance
speechnumber speaker party party.facts.id chair terms speech_url
81 Mike O'Brien Labour 1516 FALSE 123 <NA>
377 Barry Gardiner Labour 1516 FALSE 146 <NA>
193 Bob Ainsworth Labour 1516 FALSE 126 <NA>
117 Jim McGovern Labour 1516 FALSE 68 <NA>
293 Keith Hill Labour 1516 FALSE 301 <NA>
parliament iso3country party_raw year
UK-HouseOfCommons GBR Lab 2010
UK-HouseOfCommons GBR Lab 2010
UK-HouseOfCommons GBR Lab 2010
UK-HouseOfCommons GBR Lab 2010
UK-HouseOfCommons GBR Lab 2010
agenda_clean
Nhs Funding
Uk Arrest Warrants (Alleged War Crimes)
Armed Forces Compensation Scheme
Topical Questions
Communications Allowance271 Labour speeches from 2010 onward; hoc_corpus is still the full 5,000 speeches.
engagements_corpus <- corpus_subset( hoc_corpus, agenda_clean == "Engagements" ) ndoc(engagements_corpus) summary(engagements_corpus, n = 5)
> engagements_corpus <- corpus_subset(
+ hoc_corpus,
+ agenda_clean == "Engagements"
+ )
> ndoc(engagements_corpus)
[1] 81
> summary(engagements_corpus, n = 5)
corpus of 81 documents, showing 5 documents:
Text Types Tokens Sentences date agenda speechnumber
text2238 91 153 7 1981-03-05 Engagements 155289
text2303 30 35 2 1982-04-06 Engagements 279256
text2350 92 151 10 1983-01-27 Engagements 369787
text2390 44 51 1 1983-11-03 Engagements 439481
text2424 31 53 1 1984-03-20 Engagements 505077
speaker party party.facts.id chair terms
The Prime Minister Conservative NA FALSE 139
The Prime Minister Conservative NA FALSE 33
The Prime Minister Conservative NA FALSE 130
Mr. Steel Liberal NA FALSE 49
Mr. Dobson Labour NA FALSE 48
speech_url
https://api.parliament.uk/historic-hansard/commons/1981/mar/05/engagements#S5CV1000P0_19810305_HOC_140
https://api.parliament.uk/historic-hansard/written_answers/1982/apr/06/engagements#S6CV0021P0_19820406_CWA_91
https://api.parliament.uk/historic-hansard/commons/1983/jan/27/engagements#S6CV0035P0_19830127_HOC_125
https://api.parliament.uk/historic-hansard/commons/1983/nov/03/engagements#S6CV0047P0_19831103_HOC_153
https://api.parliament.uk/historic-hansard/commons/1984/mar/20/engagements#S6CV0056P0_19840320_HOC_154
parliament iso3country party_raw year agenda_clean
UK-HouseOfCommons GBR Conservative Party 1981 Engagements
UK-HouseOfCommons GBR Conservative Party 1982 Engagements
UK-HouseOfCommons GBR Conservative Party 1983 Engagements
UK-HouseOfCommons GBR Liberal Party 1983 Engagements
UK-HouseOfCommons GBR Labour Party 1984 Engagementsengagements_sentences <- corpus_reshape( engagements_corpus, to = "sentences" ) ndoc(engagements_corpus) ndoc(engagements_sentences)
> engagements_sentences <- corpus_reshape( + engagements_corpus, + to = "sentences" + ) > ndoc(engagements_corpus) [1] 81 > ndoc(engagements_sentences) [1] 364
81 speeches → 364 sentence documents. Each sentence is now treated as a document—a major research-design choice; changing the unit of analysis can change the conclusions. (Lab notes; slide 6)
as.character(engagements_sentences)[1:5]
> as.character(engagements_sentences)[1:5]
text2238.1
"With regard to the right hon."
text2238.2
"Gentleman's question on Northern Ireland, I shall, of course, be repeating and emphasising my personal commitment to the guarantee to the people of Northern Ireland, which is enshrined in law in this country."
text2238.3
"With regard to what the right hon."
text2238.4
"Gentleman said about pensioners, I usually see delegations of pensioners in my own constituency."
text2238.5
"I stress that the Government have kept 413 the pension slightly ahead of the rise in the cost of living, and our first increase actually provided an additional amount to make up for the shortfall of the previous Government." - text2238.1 is only “With regard to the right hon.”, and the next sentence starts with “Gentleman's question…”: the period in
hon.is an abbreviation, not the end of a sentence. This is exactly what the Lab warns about. - text2238.5 contains “the Government have kept 413 the pension”: this 413 looks like a Hansard column number that slipped into the text (our observation, not from the lecture)—the “recording conventions” discussed in Chapter 03; it becomes a number token.
R run checklist
Self-check
str_extract(agenda_labels, "war") returns NA everywhere, but after str_to_lower() it matches 3. Why?corpus_reshape(engagements_corpus, to = "sentences") turns 81 documents into 364. Which statement is false?agenda_clean is <NA> (206 records). What does this mean?agenda is already NA 206 (output of Exercise 7).Lab sections 3–4: tokens, phrases, KWIC, collocations, DFM, keyness, time trends
The Lab builds two sets of tokens: one kept as-is so KWIC can show context, and another lowercased with stopwords removed for DFM counts. This is exactly the “branching” described on slide 14.
Tokenizing and compounding multiword expressions
hoc_tokens <- tokens( hoc_corpus, remove_punct = TRUE, remove_symbols = TRUE, remove_numbers = FALSE )
hoc_tokens <- tokens_compound(
hoc_tokens,
pattern = phrase(c(
"Prime Minister",
"House of Commons",
"European Union",
"National Health Service"
))
)This hoc_tokens keeps case and stopwords (only punctuation and symbols are removed), so KWIC reads like the original text.
KWIC: reading words in context
kwic(
hoc_tokens,
pattern = phrase("European_Union"),
window = 8
) |>
head(10)> kwic(
+ hoc_tokens,
+ pattern = phrase("European_Union"),
+ window = 8
+ ) |>
+ head(10)
Keyword-in-context with 10 matches.
[text1971, 121] Hull Central Mr McNamara is at the Western |
[text2832, 297] CSCE context beyond that available in the Western |
[text2984, 155] Chancellor Kohl to impose their blueprint of a |
[text3048, 41] is that he wishes Britain to leave the |
[text3058, 23] proposal under title VI of the treaty on |
[text3103, 34] a significant loosening in our relations with the |
[text3103, 63] right to trade with the countries in the |
[text3144, 28] not to contributions by national Governments to the |
[text3257, 760] of our continued and deepening membership of the |
[text3356, 15] in Berlin demonstrated by the fact that the |
European_Union | in Paris It is all very well making
European_Union | His points were echoed to some extent by
European_union | on Europe before it realises what has happened
European_Union | Is that what he is saying
European_Union | to combat serious fraud against the Community budget
European_Union | We hope that we will be able to
European_Union | The hill farmers in my hon Friend's constituency
European_Union | but to money spent by national Governments on
European_Union | We have heard much about national sovereignty What
European_Union | development budget for the next seven years was kwic( hoc_tokens, pattern = "economy", window = 8, valuetype = "fixed", case_insensitive = TRUE ) |> head(10)
> kwic(
+ hoc_tokens,
+ pattern = "economy",
+ window = 8,
+ valuetype = "fixed",
+ case_insensitive = TRUE
+ ) |>
+ head(10)
Keyword-in-context with 10 matches.
[text96, 980] a quadripartite agreement to the administration of the |
[text105, 209] must be a major thing in our national |
[text147, 318] serious matters of the readjustment of our national |
[text405, 305] considered would be absorbed in the normal peace-time |
[text472, 450] there has been a very real practice of |
[text537, 987] time it must have been the result of |
[text539, 629] unless we maintain a firm control upon our |
[text705, 2326] inflation by monetary means which depresses the whole |
[text729, 6] and secondly the efficiency and |
[text737, 390] of the world Oil is vital to our |
economy | of Germany as a single unit there will
economy | from now on As has been pointed out
economy | to peace conditions I see no advantage in
economy | of the countries to which they are exported
economy | in the Royal Household If I may say
economy | in the last Government I can assure hon
economy | inflation and excessive public spending and increased taxation
economy | The Economic Secretary who I understand will reply
economy | of its operation I know the difficulties that
economy | and our Commonwealth should help to provide it Read the words before and after each match. A single occurrence of economy does not tell you whether the speaker evaluates the economy positively or negatively. (Lab notes) For example, in text472, “a very real practice of economy in the Royal Household”, economy means “thrift”, not the national economy—polysemy is exactly the “ambiguity requires context” point of slide 30. Also look at the European_Union output: in text1971 and text2832 the preceding word is Western, i.e., a different organization, the Western European Union; text2984 has the lowercase European_union. Even after compounding phrases, use KWIC to check what they matched (our observation).
Interactive: KWIC explorer (sample of 700 real speeches)
To keep the file size down, this embeds 700 speeches drawn from the 5,000 with a fixed seed (20261106), each truncated to at most its first 1,400 characters (exported from R). Tokenization is a simplified JS version (splitting on whitespace and punctuation); the results are only for practising “reading context”, and the counts do not equal R's results on all 5,000 speeches.
A second set of tokens for the DFM
hoc_tokens_dfm <- tokens(
hoc_corpus,
what = "word",
remove_punct = TRUE,
padding = TRUE,
remove_symbols = TRUE,
remove_numbers = FALSE,
remove_url = TRUE,
remove_separators = TRUE,
split_hyphens = FALSE
) |>
tokens_tolower() |>
tokens_remove(stopwords("en"), padding = TRUE)Collocations
hoc_collocations <- textstat_collocations( hoc_tokens_dfm, min_count = 10 ) |> arrange(desc(lambda)) head(hoc_collocations, 20)
> hoc_collocations <- textstat_collocations(
+ hoc_tokens_dfm,
+ min_count = 10
+ ) |>
+ arrange(desc(lambda))
> head(hoc_collocations, 20)
collocation count count_nested length lambda z
975 hong kong 15 0 2 18.01655 8.936495
933 sri lanka 23 0 2 15.86775 10.706798
924 per cent 724 0 2 15.86141 11.197966
951 sinn fein 17 0 2 14.58255 10.028858
957 belle isle 12 0 2 14.08785 9.655601
785 sulphur dioxide 10 0 2 13.96352 14.591709
652 ad hoc 12 0 2 13.79410 16.956018
779 slum clearance 11 0 2 13.48395 14.707109
965 antisocial behaviour 18 0 2 13.43125 9.332776
756 sinn fã 15 0 2 13.25436 14.983942
586 saddam hussein 15 0 2 13.11126 17.865491
521 liberal democrats 37 0 2 12.56315 18.846379
410 dispatch box 23 0 2 12.55494 20.710735
13 northern ireland 338 0 2 12.41462 52.601297
821 lifelong learning 11 0 2 12.30193 13.926595
331 mentally handicapped 14 0 2 12.29736 22.174040
100 united kingdom 307 0 2 12.18297 30.368548
507 thames gateway 13 0 2 12.12581 19.071920
385 privy seal 13 0 2 12.11320 21.252571
306 raw materials 18 0 2 12.03436 22.646568lambda(λ) is the strength of association andzits standardized value; the list is sorted by λ. hong kong (λ ≈ 18.02), sri lanka and per cent (724 times) come first.northern irelandoccurs 338 times with λ ≈ 12.41—the “statistical collocation candidate” example on slide 33.sinn fein(17) andsinn fã(15) both appear: the same party name is split into two features by an encoding problem (Chapter 03).- High association does not mean useful: slide 33 asks you to inspect usage before adding it to a measurement rule.
hoc_collocation_phrases <- hoc_collocations |> filter(lambda > 10) |> pull(collocation) |> phrase() hoc_tokens_dfm <- tokens_compound( hoc_tokens_dfm, pattern = hoc_collocation_phrases ) hoc_tokens_dfm <- tokens_remove(hoc_tokens_dfm, "")
Collocations with λ > 10 are glued into a single token, and tokens_remove(hoc_tokens_dfm, "") then removes the empty strings left by padding.
See the top 40 collocations (real R output)
Exported from R: head(hoc_collocations, 40).
Building a party-level DFM
hoc_dfm_party <- dfm(hoc_tokens_dfm) hoc_dfm_party <- dfm_group( hoc_dfm_party, groups = docvars(hoc_dfm_party, "party") ) dim(hoc_dfm_party)
> hoc_dfm_party <- dfm(hoc_tokens_dfm) > hoc_dfm_party <- dfm_group( + hoc_dfm_party, + groups = docvars(hoc_dfm_party, "party") + ) > dim(hoc_dfm_party) [1] 23 30640
dim() gives rows then columns: after grouping, the rows are 23 parties (not 5,000 speeches) and the columns are 30,640 features; each cell is the total count across all speeches by that party. (Lab notes)
topfeatures(hoc_dfm_party, 25)
> topfeatures(hoc_dfm_party, 25)
hon government right member can people one
6569 3213 2780 2428 2423 2296 2288
friend minister house made many members time
2279 2049 2000 1600 1537 1515 1503
bill said gentleman may make secretary now
1484 1484 1372 1351 1343 1340 1322
state mr us say
1314 1310 1247 1237 The most frequent are hon (6,569), government, right, member, friend… many of them parliamentary courtesy terms (“my right hon. Friend”). The W8 topic models build a separate list of “parliamentary stopwords” to remove them—stopword lists depend on the corpus.
Trimming rare features
hoc_dfm_party_trimmed <- dfm_trim( hoc_dfm_party, min_termfreq = 10 ) dim(hoc_dfm_party) dim(hoc_dfm_party_trimmed)
> hoc_dfm_party_trimmed <- dfm_trim( + hoc_dfm_party, + min_termfreq = 10 + ) > dim(hoc_dfm_party) [1] 23 30640 > dim(hoc_dfm_party_trimmed) [1] 23 5474
30,640 → 5,474 features (min_termfreq = 10: at least 10 occurrences in the whole corpus). Trimming removes features below the threshold; it does not turn the remaining counts into percentages. Trimming is not neutral: rare words may be noise, or they may be important. (Lab notes)
Interactive: how many features does a trimming threshold keep? (real counts)
R exported the distribution of total counts for the 30,640 features before trimming. Drag the threshold to see how many features and tokens are kept. A threshold of 10 should give 5,474 (Lab example), and 20 should give 3,424 (Exercise 10).
Word cloud and frequency plot
set.seed(719102) # keep the layout reproducible textplot_wordcloud(hoc_dfm_party_trimmed, max_words = 50)
textplot_wordcloud(hoc_dfm_party_trimmed, max_words = 50) generated locally in R (set.seed(719102)). Click to enlarge.A word cloud is fine for a quick look, but it is usually not the best final figure for research. (Lab notes)
hoc_feature_frequency <- textstat_frequency(
hoc_dfm_party_trimmed,
n = 25
)
hoc_feature_frequency <- hoc_feature_frequency |>
mutate(feature = reorder(feature, frequency))
ggplot(
hoc_feature_frequency,
aes(x = feature, y = frequency)
) +
geom_point() +
coord_flip() +
labs(
x = NULL,
y = "Frequency",
title = "Most frequent features in the party-level DFM"
) +
theme_minimal()Comparing parties with keyness
conservative_keyness <- textstat_keyness( hoc_dfm_party_trimmed, target = docnames(hoc_dfm_party_trimmed) == "Conservative" ) head(conservative_keyness, 20) textplot_keyness(conservative_keyness, n = 20)
> conservative_keyness <- textstat_keyness(
+ hoc_dfm_party_trimmed,
+ target = docnames(hoc_dfm_party_trimmed) == "Conservative"
+ )
> head(conservative_keyness, 20)
feature chi2 p n_target n_reference
1 hon 59.60149 1.165734e-14 3303 3266
2 friend 55.94153 7.460699e-14 1216 1063
3 aircraft 54.96878 1.224576e-13 116 38
4 cyberstalking 50.16056 1.416645e-12 42 0
5 stalking 42.99415 5.490386e-11 36 0
6 drug 38.84916 4.578508e-10 54 10
7 right 35.99095 1.982363e-09 1424 1356
8 parking 31.82940 1.683252e-08 36 4
9 icmp 29.85626 4.652923e-08 25 0
10 research 28.26946 1.055484e-07 117 62
11 misuse 26.81702 2.236585e-07 25 1
12 air 25.09368 5.461162e-07 110 60
13 badger 24.44132 7.660780e-07 23 1
14 bail 23.87148 1.029863e-06 27 3
15 medicines 23.85041 1.041196e-06 31 5
16 tyne 23.85041 1.041196e-06 31 5
17 training 20.28065 6.687365e-06 125 79
18 badgers 19.10759 1.235523e-05 16 0
19 businesses 18.61571 1.598976e-05 113 71
20 iran 18.51407 1.686546e-05 18 1
> textplot_keyness(conservative_keyness, n = 20)textplot_keyness(conservative_keyness, n = 20) (generated locally in R).- Keyness compares the word use of a “target group” (Conservative) with a “reference group” (the other 22 parties combined). A positive χ² = relatively over-represented in Conservative speeches; negative = leaning toward the reference group. This is a comparison of word use, not a sentiment score. (Lab notes)
- hon (3,303 vs. 3,266) and friend are at the top: these two words come mainly from parliamentary forms of address such as “my hon. Friend”, and may reflect speaking roles and parliamentary conventions rather than issue positions (our interpretation).
- Words like cyberstalking (42 vs. 0), stalking, icmp (25 vs. 0) and badger shoot to the top on the strength of just a few speeches—in a sample of 5,000, one or two long speeches can dominate keyness. Before reading them, use KWIC to see which speeches they come from.
Interactive: keyness explorer (real party DFM)
The data are the trimmed party DFM exported from R (23 × 5,474). Choose a target party; JS computes each feature's keyness as the χ² of a 2 × 2 contingency table (no continuity correction); for both Conservative and Labour this matches the output of R's textstat_keyness() (checked automatically below).
Try it: set the “minimum target count” to 20 and look at Conservative's top 15 again.
Words that appear in only a few speeches and are 0 in the reference group (e.g., cyberstalking, icmp) are partly filtered out, leaving more “general” differences. This is a sensitivity check (Full / trimmed vocabulary on slide 59): if a conclusion rests on only a few rare words, it is not robust. Note: the minimum-count filter is an exploration option added by these notes; textstat_keyness() itself has no such argument.
Tracking a feature over time
hoc_dfm_year_conservative <- dfm(hoc_tokens_dfm)
hoc_dfm_year_conservative <- dfm_subset(
hoc_dfm_year_conservative,
party == "Conservative"
)
hoc_dfm_year_conservative <- dfm_group(
hoc_dfm_year_conservative,
groups = docvars(hoc_dfm_year_conservative, "year")
)
docvars(hoc_dfm_year_conservative, "economy") <- as.numeric(
hoc_dfm_year_conservative[, "economy"]
)
economy_by_year <- docvars(hoc_dfm_year_conservative)
ggplot(economy_by_year, aes(x = as.integer(year), y = economy)) +
geom_line() +
geom_point(size = 1) +
labs(
x = NULL,
y = "Frequency of 'economy'",
title = "Conservative mentions of economy in the teaching sample"
) +
theme_minimal()These are raw counts in the sample. A higher point in a given year may simply mean more speeches were sampled that year, not that economy was used more often; nor does it mean more concern or more support. (Lab notes) The interactive below lets you convert raw counts into “per 1,000 tokens”.
Interactive: feature time series (raw counts vs. per 1,000 tokens)
R exported yearly token totals and speech counts for Conservative and Labour, plus yearly counts for – features (the tokens used for the DFM, including compounded collocations). With “Raw counts” selected, Conservative's economy should match the figure above.
Self-check
dim(hoc_dfm_party) is 23 × 30640. What is 23?padding = TRUE?Exercises 1–11: write it yourself first, then check the answers
The Lab's 11 exercises reuse the example blocks above. Change one input at a time and explain what the output means. Exercise 5 follows 4; 10–11 follow 9. (Lab notes)
How to use this chapter
- Each exercise has an answer box (saved automatically in this browser). When done, press “Copy as R comment” to paste it straight into your .R file.
- “Show reference answer” expands the code from
answers/Lab_Session_W2_Answers.Rand the actual local output (identical to the instructor's HTML). - The instructor's reminder: merely getting the script to run does not count as completing an exercise; you should be able to explain what your code changed and how it affects the evidence.
The 11 exercises
str_detect()Create a character vector speaker_names containing the first 20 speaker names in hoc. Use str_detect() to find which contain Sir.
Show reference answer (code + local output)
speaker_names <- hoc$speaker[1:20] speaker_names str_detect(speaker_names, "Sir") speaker_names[str_detect(speaker_names, "Sir")]
> speaker_names <- hoc$speaker[1:20] > speaker_names [1] "Mr. Johnstone" "Mr. Woodburn" "Mr. Eden" [4] "Vice-Admiral Taylor" "Sir M. Sueter" "Mr. Johnston" [7] "Sir J. Anderson" "Major Mills" "Mr. Viant" [10] "Earl Winterton" "Mr. Sorensen" "Sir J. Anderson" [13] "Mr. Kendall" "Sir M. Sueter" "The Prime Minister" [16] "Mr. McNeil" "Mr. H. Morrison" "Mr. Turton" [19] "Sir D. Somervell" "Mr. Loftus" > str_detect(speaker_names, "Sir") [1] FALSE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE FALSE FALSE TRUE [13] FALSE TRUE FALSE FALSE FALSE FALSE TRUE FALSE > speaker_names[str_detect(speaker_names, "Sir")] [1] "Sir M. Sueter" "Sir J. Anderson" "Sir J. Anderson" "Sir M. Sueter" [5] "Sir D. Somervell"
5 matches (speakers 5, 7, 12, 14 and 19); Sir J. Anderson and Sir M. Sueter each appear twice—the same person speaking more than once.
str_extract_all()Use str_extract_all() to extract all four-digit years from the first 20 speech_url values.
Show reference answer
speech_urls_20 <- hoc$speech_url[1:20]
str_extract_all(speech_urls_20, "\\b\\d{4}\\b")> speech_urls_20 <- hoc$speech_url[1:20]
> str_extract_all(speech_urls_20, "\\b\\d{4}\\b")
[[1]]
[1] "1945"
[[2]]
[1] "1945"
[[3]]
[1] "1945"
[[4]]
[1] "1945"
[[5]]
[1] "1945"
[[6]]
[1] "1945"
[[7]]
[1] "1945"
[[8]]
[1] "1945"
[[9]]
[1] "1945"
[[10]]
[1] "1945"
[[11]]
[1] "1945"
[[12]]
[1] "1945" "1914"
[[13]]
[1] "1945" "1945"
[[14]]
[1] "1945"
[[15]]
[1] "1945"
[[16]]
[1] "1945"
[[17]]
[1] "1945"
[[18]]
[1] "1945"
[[19]]
[1] "1945"
[[20]]
[1] "1945"With \\b added, long numbers in the URL anchor such as 19450116 are no longer picked up by mistake. But URL 12 also yields “1914” and URL 13 yields two “1945”s—they come from the agenda title in the URL: URL 12 is …/1945/mar/06/war-gratuities-1914-18#… (agenda “WAR GRATUITIES, 1914–18”), and URL 13 is navy-estimates-1945-1; they are not speech dates (verified locally in R). “Four digits” does not equal “a year”; look at the context.
Create a new variable mentions_prime_minister that detects whether the speech text contains Prime Minister. How many speeches mention it?
Show reference answer
hoc <- hoc |>
mutate(
mentions_prime_minister = str_detect(
str_to_lower(text),
"\\bprime minister\\b"
)
)
sum(hoc$mentions_prime_minister)> hoc <- hoc |> + mutate( + mentions_prime_minister = str_detect( + str_to_lower(text), + "\\bprime minister\\b" + ) + ) > sum(hoc$mentions_prime_minister) [1] 279
279 speeches (case-insensitive, with word boundaries). Note that this is the number of speeches that mention it at least once, not the total number of mentions.
corpus_subset()Use corpus_subset() to build a corpus of Conservative speeches from 2016 onward. How many documents are there?
Show reference answer
conservative_since_2016 <- corpus_subset( hoc_corpus, party == "Conservative" & year >= 2016 ) ndoc(conservative_since_2016) summary(conservative_since_2016, n = 5)
> conservative_since_2016 <- corpus_subset(
+ hoc_corpus,
+ party == "Conservative" & year >= 2016
+ )
> ndoc(conservative_since_2016)
[1] 368
> summary(conservative_since_2016, n = 5)
corpus of 368 documents, showing 5 documents:
Text Types Tokens Sentences date
text4383 53 68 3 2016-01-11
text4384 95 143 7 2016-01-18
text4385 66 80 5 2016-01-18
text4387 81 133 8 2016-01-28
text4388 34 39 2 2016-01-28
agenda
Contraband: Entry into UK [Oral Answers to Questions > Home Department]
Soft Power [Oral Answers to Questions > Defence]
Nuclear Deterrent [Oral Answers to Questions > Defence]
Arms Sales to Saudi Arabia
NHS and Social Care Commission
speechnumber speaker party party.facts.id chair terms
43 James Brokenshire Conservative 1567 FALSE 64
75 Edward Leigh Conservative 1567 FALSE 129
100 Michael Fallon Conservative 1567 FALSE 73
266 Tobias Ellwood Conservative 1567 FALSE 116
410 Chris Davies Conservative 1567 FALSE 34
speech_url parliament iso3country party_raw year
<NA> UK-HouseOfCommons GBR Con 2016
<NA> UK-HouseOfCommons GBR Con 2016
<NA> UK-HouseOfCommons GBR Con 2016
<NA> UK-HouseOfCommons GBR Con 2016
<NA> UK-HouseOfCommons GBR Con 2016
agenda_clean
Contraband: Entry Into Uk
Soft Power
Nuclear Deterrent
Arms Sales To Saudi Arabia
Nhs And Social Care Commission368.
corpus_reshape() (follows Exercise 4)Reshape the corpus from Exercise 4 into sentences. How many sentence-level documents are there?
Show reference answer
conservative_sentences <- corpus_reshape( conservative_since_2016, to = "sentences" ) ndoc(conservative_sentences) as.character(conservative_sentences)[1:5]
> conservative_sentences <- corpus_reshape( + conservative_since_2016, + to = "sentences" + ) > ndoc(conservative_sentences) [1] 2995 > as.character(conservative_sentences)[1:5] text4383.1 "We are taking this forward at a European level." text4383.2 "My right hon." text4383.3 "Friend the Home Secretary is in discussions with other European leaders on how best we can co-ordinate with and lobby Governments beyond Europe as well, to share the focus that we as a Government have on confronting the smuggling of weapons and ensuring that this issue is dealt with even more firmly." text4384.1 "Will the Minister make a comment about increasing our security in the Baltic region in relation to soft power?" text4384.2 "In the context of soft power, may I apologise on behalf of my right hon."
368 speeches → 2,995 sentences, about 8 sentences per speech on average.
Tokenize while keeping the three multiword expressions Prime Minister, European Union and House of Commons, then inspect Prime_Minister with kwic().
Show reference answer
hoc_tokens_exercise <- tokens(
hoc_corpus,
remove_punct = TRUE,
remove_symbols = TRUE,
remove_numbers = FALSE
)
hoc_tokens_exercise <- tokens_compound(
hoc_tokens_exercise,
pattern = phrase(c(
"Prime Minister",
"European Union",
"House of Commons"
))
)
kwic(
hoc_tokens_exercise,
pattern = phrase("Prime_Minister"),
window = 8
) |>
head(10)> hoc_tokens_exercise <- tokens(
+ hoc_corpus,
+ remove_punct = TRUE,
+ remove_symbols = TRUE,
+ remove_numbers = FALSE
+ )
> hoc_tokens_exercise <- tokens_compound(
+ hoc_tokens_exercise,
+ pattern = phrase(c(
+ "Prime Minister",
+ "European Union",
+ "House of Commons"
+ ))
+ )
> kwic(
+ hoc_tokens_exercise,
+ pattern = phrase("Prime_Minister"),
+ window = 8
+ ) |>
+ head(10)
Keyword-in-context with 10 matches.
[text16, 30] to say that he could answer for the |
[text43, 239] very strong and public support from the then |
[text52, 41] appropriateness In fact my right hon Friend the |
[text52, 49] Prime_Minister has lately been in touch with the |
[text156, 363] a letter from my right hon Friend the |
[text278, 7] At least he can consult the |
[text280, 16] for the words that have fallen from the |
[text424, 3] asked the |
[text544, 3] asked the |
[text544, 27] of the United States of America and the |
Prime_Minister | but I can say that when the Home
Prime_Minister | and the Government of this country When the
Prime_Minister | has lately been in touch with the Prime_Minister
Prime_Minister | of Canada on this and other matters
Prime_Minister | that this matter is being considered at the
Prime_Minister | over this matter and see whether it cannot
Prime_Minister | of Northern Ireland and from his Minister of
Prime_Minister | if the speech of the Secretary of State
Prime_Minister | whether in view of his welcome restoration to
Prime_Minister | of France to resume the arrangements for the Many are “asked the Prime_Minister” or “my right hon Friend the Prime_Minister”—mentioning the Prime Minister is often just the parliamentary question format, not “talking about” the Prime Minister.
Count the 10 most common values of agenda and of agenda_clean. What changed after cleaning?
Show reference answer
hoc |> count(agenda, sort = TRUE) |> head(10) hoc |> count(agenda_clean, sort = TRUE) |> head(10) # Cleaning collapses capitalization differences such as "BUSINESS OF THE HOUSE", # "Business of the House", and "Business Of The House" into one label. It also # collapses agenda labels beginning with "Engagements" into a common # "Engagements" category.
> hoc |>
+ count(agenda, sort = TRUE) |>
+ head(10)
agenda
1 <NA>
2 BUSINESS OF THE HOUSE
3 Business of the House
4 Business Of The House
5 Topical Questions
6 Engagements [Oral Answers to Questions > Prime Minister]
7 Engagements
8 Engagements [Oral Answers To Questions > Prime Minister > Prime Minister]
9 Finance Bill
10 European Council
n
1 206
2 56
3 54
4 34
5 24
6 23
7 18
8 18
9 12
10 9
> hoc |>
+ count(agenda_clean, sort = TRUE) |>
+ head(10)
agenda_clean n
1 <NA> 206
2 Business of the House 151
3 Engagements 81
4 Topical Questions 69
5 Finance Bill 18
6 Points of Order 15
7 European Economic Community 14
8 Debate On The Address 12
9 Budget Resolutions And Economic Situation 11
10 Northern Ireland 11
> # Cleaning collapses capitalization differences such as "BUSINESS OF THE HOUSE",
> # "Business of the House", and "Business Of The House" into one label. It also
> # collapses agenda labels beginning with "Engagements" into a common
> # "Engagements" category.Cleaning merges “BUSINESS OF THE HOUSE” (56), “Business of the House” (54), “Business Of The House” (34) and others into one label (151), and merges the variants beginning with Engagements into 81 records. The 206 NA records are unchanged.
Show the strongest three-feature collocations in hoc_tokens_dfm (sorted by lambda). Some features are already compounded words, so they are not necessarily three original words.
Show reference answer
textstat_collocations( hoc_tokens_dfm, size = 3, min_count = 5 ) |> arrange(desc(lambda)) |> head(20)
> textstat_collocations(
+ hoc_tokens_dfm,
+ size = 3,
+ min_count = 5
+ ) |>
+ arrange(desc(lambda)) |>
+ head(20)
collocation count count_nested length lambda z
34 transport general workers 7 0 3 8.119809 3.275857
22 european economic community 9 0 3 8.026347 3.671224
51 state commonwealth relations 5 0 3 7.126365 2.861315
3 state home department 28 0 3 7.099060 5.618443
35 lords said amendment 5 0 3 6.967612 3.249923
39 national farmers union 11 0 3 6.925794 3.171465
45 general workers union 6 0 3 6.641970 3.021601
42 department work pensions 7 0 3 6.549383 3.148884
46 general needs housing 6 0 3 6.343273 3.007404
12 private members time 8 0 3 6.288444 3.986629
44 national coal board 14 0 3 6.277167 3.039486
43 greater london council 12 0 3 6.241621 3.057219
81 lord chief justice 9 0 3 6.119386 2.472207
82 environment food rural 13 0 3 6.042873 2.446875
65 town country planning 5 0 3 5.879678 2.664581
52 home department whether 6 0 3 5.865489 2.861206
30 bill now read 6 0 3 5.864393 3.445057
55 asked president board 29 0 3 5.768125 2.852030
9 minister pensions national 10 0 3 5.610909 4.647448
38 hold government account 5 0 3 5.527632 3.193026transport general workers, european economic community, state home department… Note that “state home department” is very likely what remains of “Secretary of State for the Home Department” after stopword removal: by Exercise 8, hoc_tokens_dfm has already had its padding removed by tokens_remove(hoc_tokens_dfm, "") in the compound_collocations_for_dfm step, so words originally separated by for and the became adjacent—exactly the situation slide 32 warns about (our interpretation, not from the lecture).
Build a DFM from hoc_tokens_dfm grouped by party, named hoc_dfm_exercise. How many documents and features does it have?
Show reference answer
hoc_dfm_exercise <- dfm(hoc_tokens_dfm) hoc_dfm_exercise <- dfm_group( hoc_dfm_exercise, groups = docvars(hoc_dfm_exercise, "party") ) dim(hoc_dfm_exercise) topfeatures(hoc_dfm_exercise, 20)
> hoc_dfm_exercise <- dfm(hoc_tokens_dfm)
> hoc_dfm_exercise <- dfm_group(
+ hoc_dfm_exercise,
+ groups = docvars(hoc_dfm_exercise, "party")
+ )
> dim(hoc_dfm_exercise)
[1] 23 30640
> topfeatures(hoc_dfm_exercise, 20)
hon government right member can people one
6569 3213 2780 2428 2423 2296 2288
friend minister house made many members time
2279 2049 2000 1600 1537 1515 1503
bill said gentleman may make secretary
1484 1484 1372 1351 1343 1340 23 × 30,640, the same as hoc_dfm_party in the Lab example.
Trim hoc_dfm_exercise to keep only features that occur at least 20 times. Look at the new dimensions.
Show reference answer
hoc_dfm_exercise_trimmed <- dfm_trim( hoc_dfm_exercise, min_termfreq = 20 ) dim(hoc_dfm_exercise) dim(hoc_dfm_exercise_trimmed)
> hoc_dfm_exercise_trimmed <- dfm_trim( + hoc_dfm_exercise, + min_termfreq = 20 + ) > dim(hoc_dfm_exercise) [1] 23 30640 > dim(hoc_dfm_exercise_trimmed) [1] 23 3424
30,640 → 3,424. You can verify this by dragging the trimming interactive in Chapter 11 to 20.
Use textstat_keyness() to show the features that most distinguish Labour from all other parties.
Show reference answer
labour_keyness <- textstat_keyness( hoc_dfm_exercise_trimmed, target = docnames(hoc_dfm_exercise_trimmed) == "Labour" ) head(labour_keyness, 10) textplot_keyness(labour_keyness, n = 10)
> labour_keyness <- textstat_keyness(
+ hoc_dfm_exercise_trimmed,
+ target = docnames(hoc_dfm_exercise_trimmed) == "Labour"
+ )
> head(labour_keyness, 10)
feature chi2 p n_target n_reference
1 waste 73.18169 0.000000e+00 124 38
2 advertising 51.95577 5.676570e-13 64 12
3 giro 44.03569 3.224421e-11 36 1
4 tory 43.68173 3.863621e-11 73 22
5 glc 42.34350 7.657031e-11 37 2
6 child 34.35619 4.589373e-09 165 106
7 conservative 34.18764 5.004582e-09 203 142
8 lottery 33.09979 8.754839e-09 32 3
9 nuclear 32.45001 1.222982e-08 120 68
10 illegitimate 29.64764 5.181577e-08 25 1
> textplot_keyness(labour_keyness, n = 10)textplot_keyness(labour_keyness, n = 10) (generated locally in R).waste, advertising, giro, tory, glc… tory and conservative appear near the top of Labour's keyness; one possible reading is that Labour MPs often name their opponents in debate (our interpretation; confirm with KWIC)—keyness may be capturing “who talks about whom”, not policy positions. This uses the DFM with threshold 20, unlike the Conservative example (threshold 10); keep that in mind when comparing the two.
Answer summary table (local output)
| Exercise | Key numbers |
|---|---|
| 1 | 5 of the first 20 speakers contain Sir |
| 3 | 279 speeches mention prime minister |
| 4 / 5 | Conservative since 2016: 368 speeches → 2,995 sentences |
| 7 | Business of the House: scattered as 56 / 54 / 34… before cleaning, 151 after |
| 9 / 10 | 23 × 30,640 → 23 × 3,424 (min_termfreq = 20) |
| 11 | Labour top three: waste (χ² 73.18), advertising (51.96), giro (44.04) |
Self-check
"\\b\\d{4}\\b", and URL 12 yields “1945” and “1914”. What is the correct reading?Reading guide and class discussion
The course repo's W2/papers/ has two full texts: Welbers, Van Atteveldt & Benoit (2017) and Benoit et al. (2018). The reading cards are based only on these two PDFs; page numbers are journal page numbers. For other studies mentioned in the slides, these notes have no full text and only restate the slides.
Welbers, K., Van Atteveldt, W., & Benoit, K. (2017). Text Analysis in R. Communication Methods and Measures 11(4): 245–265.
Source: course repo W2/papers/Welbers2017.pdf (Taylor & Francis version, 22-page PDF; page numbers are journal page numbers). doi:10.1080/19312458.2017.1387238.
Benoit, K., Watanabe, K., Wang, H., Nulty, P., Obeng, A., Müller, S., & Matsuo, A. (2018). quanteda: An R package for the quantitative analysis of textual data. Journal of Open Source Software 3(30): 774.
textmodel_* implements Wordscores, Wordfish, class affinity scaling, correspondence analysis, Naive Bayes and LSA; text statistics include frequencies, keyness, lexical diversity, readability, similarity and distance (p. 2).corpus(), tokens(), dfm() create objects; corpus_*(), tokens_*(), dfm_*() return modified objects), ease of use, performance, transparency and reproducibility, and compatibility with packages such as stm, text2vec and spacyr (p. 3).tokens_compound, dfm_group, dfm_trim, textstat_keyness, textplot_keyness. The prefix tells you what object goes in and comes out.Source: course repo W2/papers/Benoit2018.pdf (JOSS, 4 pages, CC BY 4.0). doi:10.21105/joss.00774.
Studies mentioned in the slides without full text in these notes
The PDFs of the following studies are not in the course repo; these notes have not read the full texts and only restate slides 54–58 and 63 (see the table in Chapter 09). Readers who want the full texts can get them through the NTU Library or the university VPN:
- Roberts et al. (2014) STM; Eshima et al. (2024) keyATM.
- Slapin & Proksch (2008) Wordfish; Lowe (2008), Laver et al. (2003) Wordscores.
- Blumenau (2021); Bestvater & Monroe (2023).
- Grimmer, Roberts & Stewart (2022) Text as Data, Chapter 4 (book).
- Schoonvelde (2026) Essex Summer School slides (called the “main lecture source” on slide 64; 38 pages).
Class discussion
Pick one of the applied papers introduced earlier, and first look at its research question and one main figure or table:
- What is the research question? What counts as a document?
- How might removing words, aggregating documents or weighting affect this measurement?
- Beyond “preprocessing worked”, what evidence supports the authors' interpretation?
Candidates: topic models Roberts et al. (2014), Eshima et al. (2024); text scaling Slapin & Proksch (2008), Laver et al. (2003); TF-IDF applications Blumenau (2021), Bestvater & Monroe (2023).
Interactive: judging claims—does this statement hold up?
Each sentence is a claim that might appear in a report (written for these notes). Judge whether it “holds up”, “needs more evidence” or is “wrong”, then read the explanation.
Interactive: discussion prep card
Self-check
Common pitfalls, glossary, final review and references
Write this week's choices up as a “preprocessing decision log” that you can reuse directly in your project later.
Ten common pitfalls
| Pitfall | Why it is a problem | Evidence from this week |
|---|---|---|
| Treating available texts as the population | Resources, incentives, media and retrieval all introduce bias | Slides 4–5 |
| Overwriting the original text | You cannot check what cleaning changed | The Lab saves agenda_clean separately |
| Greedy regex | \[.*\] deletes all the way to the last ] | “Trade ” |
| No word boundaries | war matches warfare and towards | Lab word_boundary_examples |
| A standard stopword list removes negation | The meaning of d3 is reversed | workers support policy |
| Removing words before building bigrams | Creates pairs that never existed | workers_support |
| Keeping only NOUN / VERB | The negation “不” (ADV) disappears | Slide 42 |
| Trimming away rare but crucial words | min_docfreq = 2 removes not | Slide 47 |
| Treating raw counts as attention | The denominator (speeches, tokens) differs from year to year | Yearly economy plot (Chapter 11) |
| Treating keyness as position or sentiment | It is only a comparison of word use, often dominated by parliamentary language and a few long speeches | hon, friend, cyberstalking (Chapter 11) |
Glossary (searchable)
Final review
Preprocessing decision log (for your project)
Goal 3 on slide 2 asks you to check the feasibility of your project data (coverage, metadata, access); slide 59 asks you to run sensitivity comparisons on chosen rules. Write down your answers so you can put them straight into the data and methods section of your project.
My progress
Only the records for these W2 notes are cleared.
References and software
Listed on slide 64
- Schoonvelde, M. (2026). Quantitative text analysis – Essex Summer School: Principles of QTA, cleaning text, and preprocessing text. Supplied slides, 38 pages. (Main lecture source)
- Welbers, K., Van Atteveldt, W., & Benoit, K. (2017). Text Analysis in R. Communication Methods and Measures, 11(4), 245–265. doi:10.1080/19312458.2017.1387238. (Reading and reproduced figures/tables)
- Grimmer, J., Roberts, M. E., & Stewart, B. M. (2022). Text as Data: A New Framework for Machine Learning and the Social Sciences. Princeton University Press. Chapter 4: “Selecting Documents.”
- Software documentation: quanteda (tokens, TF-IDF, KWIC), stringr (pattern removal); UDPipe guide, Japanese GSD, Chinese GSD.
- The English, Thai, Japanese and Chinese example sentences in the slides are synthetic teaching examples.
Cited on other slides
- Benoit, K., et al. (2018). quanteda: An R package for the quantitative analysis of textual data. JOSS 3(30): 774. doi:10.21105/joss.00774.
- Straka, M., & Straková, J. (2017); Straka, M. (2018) (UDPipe); Wijffels, J., & Straka, M. (2026) (R udpipe); Universal Dependencies contributors (n.d.).
- Akbik, A., et al. (2018, 2019) (Flair); Liao, Y.-C., et al. (2023) (flaiR); Wolf, T., et al. (2020) (Transformers); Sentence Transformers contributors (n.d.); Explosion (n.d.) (spaCy).
- Ushey, K., et al. (2026) (reticulate); Posit (2022, n.d.); Altman (2025); R Core Team (n.d.); Python Software Foundation (n.d.); Wickham, H. (2025) (stringr).
- Roberts, M. E., et al. (2014); Eshima, S., et al. (2024); Slapin, J. B., & Proksch, S.-O. (2008); Laver, M., Benoit, K., & Garry, J. (2003); Lowe, W. (2008); Lowe & Benoit (2013); Blei, Ng & Jordan (2003); Roberts et al. (2019); Blumenau, J. (2021); Bestvater, S., & Monroe, B. (2023).
Lab source
- Adapted from Martijn Schoonvelde (2026), QTA Lab 02: String Operations and Inspecting the House of Commons Corpus, with thanks to Stefan Müller for earlier materials; the original analysis examples and 11 exercises are retained.