⌂ Course index
🐞 Feedback
中文
Interactive features failed to initialize, so the page has switched to a static version with all chapters expanded in order; just scroll down to read. (The interactive labs, quiz scoring, progress tracking, and the slide panel need JavaScript. If an in-app preview shows no interactivity, use "Share → Open in Safari" or open the file in a desktop browser.)
00 · Week overview

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

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.

  1. Set up RStudio and Positron for text analysis with R and Python.
  2. Organize code with GitHub and submit written coursework through shared Overleaf projects.
  3. Inspect supplied corpora and check project data feasibility: coverage, metadata, and access.
  4. 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):

Scope of these notes

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.Slides 2, 60

Concept map: from a pile of text to a matrix Slides 14–15

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).

🗺Interactive concept mapClick a box for details
Click any box to begin.

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.Slides 14–15

The two practice datasets

The four-sentence toy corpus from the slides Slide 22
  • 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: a sample of UK House of Commons speeches Slide 61
  • 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.R locally (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.Slide 62

Self-check

1. What does the 5,000 in the Lab data represent?
The Lab's reminder: the 5000 from nrow(hoc) is the number of speeches, not the number of MPs.Slide 61
2. According to the slides, W2 introduces content from which week early?
“Week 4 content introduced today: Text preprocessing and document-feature matrices (DFMs).”Slide 2
01 · Principles and selecting documents

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 Slide 3

  1. Domain knowledge defines the research problem and relevant evidence.
  2. Human judgment guides interpretation and validation.
  3. Discovery and testing require distinct stages.
  4. The task determines which methods are useful.
  5. Validation evaluates whether the measure fits the claim.

Sources: Schoonvelde (2026); Grimmer et al. (2022).Slide 3

In plain words · Supplement (not from the lecture)

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) Slide 4

Classroom example: measuring expressed preference for coffee.

Design choiceExample
Target populationThai-language public posts about coffee in a specified month
Quantity of interestShare of those posts expressing positive preference for coffee
Observed corpusPosts 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.Slide 4

Selection bias begins before preprocessing Slide 5

Source of biasExampleResearch consequence
ResourcesWell-funded groups archive more documentsAvailable texts overrepresent some actors
IncentivesPoliticians publish strategicallyPublic statements differ from private beliefs
MediumA platform limits length or visibilityThe medium shapes expression
RetrievalSearching only for “economy”Relevant texts with other words disappear

Interactive: which kind of selection bias is this?

🔎Selection-bias detectorPractice · scenarios are a supplement (not from the lecture)

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 Slide 6

DecisionExampleWhat to record
PopulationParliamentary speech contributionsChamber, actors, dates
InclusionAll contributions in selected debatesRule and exclusions
Document unitOne contribution per rowHow segments were defined
IdentifierA persistent doc_idLinks to source and metadata

Changing the unit to "speaker-day" or "party-year" changes the comparison itself.Slide 6 The Lab in Chapter 10 demonstrates this: 81 Engagements speeches become 364 "documents" once the unit is changed to sentences.

Sources and import routes Slide 7

SourceTypical route (R packages)First check
Existing corpusDownload plus codebookCoverage and sampling
TXT, CSV, TSVreadr, data.table, base REncoding and columns
JSON or APIjsonlite, httr2Pagination and identifiers
HTML or XMLrvest, xml2Boilerplate and structure
PDF or DOCXpdftools, readtextReading order and document boundaries

Scanned PDFs may need OCR before they contain usable text.Slide 7

Self-check

1. A researcher searches news only with the keyword “economy” and misses articles that discuss the economy using “jobs” or “prices”. Which kind of bias is this?
The Retrieval example on slide 5: searching only for “economy” makes relevant texts with other words disappear.Slide 5
2. What is the most direct consequence of changing the document unit from "each speech" to "party × year"?
“Changing the unit to speaker-day or party-year changes the comparison.”Slide 6
3. Which practice best matches the principle that "discovery and testing must be separated"?
Principle 3: Discovery and testing require distinct stages.Slide 3
02 · Tool landscape

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

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 articleAlternatives (excerpt)
importing textreadtextjsonlite, XML, antiword, readxl, pdftools
string operationsstringistringr
preprocessing / DTM / filtering and weightingquantedatm, tidytext, Matrix, etc.
unsupervised machine learningtopicmodelsquanteda, stm, austin, text2vec
advanced NLPspacyrcoreNLP, cleanNLP, koRpus

Beyond 2017: annotation and embeddings Slide 9

Tool / access from RModel typeOutput and use
UDPipe 1: R udpipeSupervised annotation pipeline trained on a treebankTokens, lemmas, POS, dependency labels
UDPipe 2: R + REST APINeural annotation with contextual embeddingsLinguistic annotations; current models use BERT-based representations
Flair: R reticulate + Python (flaiR; Liao et al., 2023)Contextual string embeddings or Transformer embeddingsWord/document vectors; models for NER, tagging and classification

FlairEmbeddings uses character language models; TransformerWordEmbeddings uses models such as BERT.Slide 9

quanteda, UDPipe, spaCy, and Flair Slide 10

Tool / accessMain emphasisTypical output
quanteda (R)Corpus management and feature analysisCorpus, tokens, DFM; KWIC and TF-IDF
UDPipe (R / API)Linguistic annotation using trained modelsTokens, lemmas, POS, UD dependency labels
spaCy (Python)Configurable NLP pipelinesTokens, POS, dependencies, named entities
Flair (Python; flaiR is an R wrapper)Embeddings and neural task modelsVectors; 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).Slide 10

Flip cards: what does this tool / function do?

🃏Flip cardsPractice · click a card to flip it

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 Slides 11–12

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.Slide 11

Python inside an R session Slide 12
  • R's reticulate package 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.
Separate scripts, shared data Slide 12
  • 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 Slide 13

  • 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

1. When you prepare text in R, compute vectors in Python, and then analyze them back in R, what matters most for connecting the two sides?
“A stable document ID connects inputs and outputs.” Slide 12.Slide 12
2. Which tool's typical output is "tokens, lemmas, POS, UD dependency labels"?
UDPipe: linguistic annotation using trained models.Slide 10
03 · Workflow and objects

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

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 Slide 15

ObjectContentsUse
Data frameText, identifiers, metadataImport checks and joins
corpusText with document variables (docvars)Subsets and metadata access
tokensSequences of tokens (order preserved)Phrase matching and context inspection (KWIC)
dfmDocuments × featuresCounts and weighted representations

stringr handles strings. quanteda provides the corpus → tokens → DFM workflow.Slide 15

→ → →
  • 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() and kwic().
  • dfm: only counts remain and order is gone; you can use dfm_group(), dfm_trim(), textstat_keyness().

Import checks and encoding Slide 16

R · slide 16 (sketch; the file path is the slide's example)
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.
The key warning on slide 16

Adding an encoding = "UTF-8" argument does not repair text whose source encoding was wrongly identified.Slide 16

A real example from the Lab data (local R output)

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 Slides 17–18

FieldValue in the source slide
Date1997-01-20
SpeakerWilliam Hague
PartyConservative
AgendaPublic Expenditure [Oral Answers To Questions > Wales]

Text includes [Interruption.], DRAMATICALLY, and !!!. The slide asks: which elements are metadata, meaningful language, or recording conventions?Slide 17

Interactive: metadata, language, or recording convention?

🗂Sorting exercisePractice · based on slides 17–18

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.

ElementPossible treatmentInformation at stake
Speaker and partyStore as metadataWho speaks
[Interruption.]Remove or extract into an indicatorParliamentary interaction
CapitalizationPreserve or lowercaseNames and emphasis
NumbersKeep, normalize, or removeYears, budgets, percentages
Repeated punctuationPreserve or simplifyRhetorical emphasis

Keep an untouched copy of the raw text.Slide 18

Self-check

1. Which object still keeps word order, so that it can be used for KWIC and phrase matching?
tokens: Sequences of tokens → phrase matching and context inspection.Slide 15
2. After import, garbled text such as “Féin” appears. Which statement is correct?
“A UTF-8 argument does not repair a wrongly identified source encoding.”Slide 16
3. When studying "interaction and interruptions in parliament", what is the most reasonable treatment of [Interruption.]?
Slide 18: Remove or extract into an indicator; the information at stake is Parliamentary interaction. Cleaning depends on the research question.Slide 18
04 · Cleaning and regex

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 Slide 19

FunctionPurposeExample use
str_detect()Test whether a pattern appears (TRUE / FALSE)Flag bracketed annotations
str_extract()Retrieve the first matchExtract a year
str_remove_all()Remove all matchesDelete selected annotations
str_replace_all()Replace matchesStandardize separators
str_squish()Normalize whitespaceRemove repeated spaces and leading/trailing whitespace
str_to_lower()Change caseMerge 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 Slide 20

R · S02 Bracket patterns (slide 20) (W2 slides week2.qmd, reconstructed from the slides for these notes)
s <- "Trade [Commons] and jobs [Wales]"
str_remove_all(s, "\\[.*\\]")
str_remove_all(s, "\\[[^\\[\\]]*\\]") |> str_squish()
R console output (run locally: 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)
> s <- "Trade [Commons] and jobs [Wales]"
> str_remove_all(s, "\\[.*\\]")
[1] "Trade "
> str_remove_all(s, "\\[[^\\[\\]]*\\]") |> str_squish()
[1] "Trade and jobs"
"\\[.*\\]"
.* is greedy: it consumes everything from the first [ to the last ], deleting the “and jobs” in between as well and leaving only "Trade ".
"\\[[^\\[\\]]*\\]"
[^\\[\\]]* means "any number of characters that are not brackets", so each bracket group is removed separately; then str_squish() tidies up the extra whitespace → "Trade and jobs".

The slide: the second pattern handles separate, non-nested bracket groups.Slide 20

Interactive: greedy vs. non-greedy bracket removal

🧪Bracket-removal comparatorToy intuition · Supplement (not from the lecture); default string from slide 20
RuleResult
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 Slide 21

R · S03 Cleaning with an audit trail (slide 21; week2.qmd clean-agenda) (W2 slides week2.qmd, reconstructed from the slides for these notes)
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
R console output (run locally: 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)
> 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"
str_remove_all("\\[[^\\[\\]]*\\]")
Deletes [Commons].
str_to_lower()
Lowercases everything: Export Trade → export trade.
str_replace_all("[^[:alnum:][:space:]]", " ")
Replaces characters that are "neither alphanumeric nor whitespace" (--, .) with a space.
str_squish()
Collapses runs of whitespace into one and trims leading and trailing whitespace.

This rule preserves numbers and removes punctuation; another task may need a different rule.Slide 21 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)

🔤Regex playgroundReal data · 5,000 agenda values

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.

Matching speeches
–
Distinct matching labels
–
Check
–
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

1. What is the result of str_remove_all("Trade [Commons] and jobs [Wales]", "\\[.*\\]")?
The greedy .* consumes everything from the first [ to the last ].Slide 20
2. What does the cleaning rule on slide 21 give for " Export Trade [Commons] -- vol. 407 "?
The rule keeps numbers, removes punctuation and bracketed annotations, and lowercases.Slide 21
3. Why does the Lab store the cleaned result in a new column agenda_clean instead of overwriting agenda?
“Keep an untouched copy of the raw text.” (slide 18); the Lab: “The original column is kept so that you can review the changes.”Slides 18, 21
05 · Toy corpus

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 Slides 22–23

R · S01 Slide worked example: four synthetic texts (week2.qmd setup; slides 22-23) (W2 slides week2.qmd, reconstructed from the slides for these notes)
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)
R console output (run locally: 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)
> 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.Slide 23

Compare with the Lab

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 Slide 24

Text: “Health services need health workers.”

RepresentationTokensDistinct types
Case and punctuation retained66
Lowercase, punctuation removed54

After normalization: health, services, need, health, workers. A token is an occurrence. A type is a distinct form under the chosen representation.Slide 24

R · S04 Tokens and types (slide 24) (W2 slides week2.qmd, reconstructed from the slides for these notes)
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)
R console output (run locally: 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)
> 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

🔢Token / type counterToy intuition · Supplement (not from the lecture); default sentence from slide 24
tokens
–
types
–
Type / token ratio
–

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 Slide 25

ComparisonCommon R text-analysis workflowTypical LLM workflow
Common unitsWords; optionally characters or sentencesOften subwords; can include whole words, characters or byte units
Segmentation depends onPackage, tokenizer and your settingsThe model’s tokenizer and vocabulary
Main useWord counts, DFM, TF-IDF, topic modelsToken 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.Slide 25

Tokenizing with explicit choices Slide 26

R · S05 Tokenizing with explicit choices (slide 26) (W2 slides week2.qmd, reconstructed from the slides for these notes)
toks <- tokens(corp, remove_punct = TRUE) |>
  tokens_tolower()
as.list(toks)[[1]]
R console output (run locally: 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)
> 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.Slide 26 (An example from the Lab: “right hon.”, common in parliamentary text, makes sentence splitting go wrong; see Chapter 10.)

Self-check

1. After lowercasing and removing punctuation, how many tokens and types does “Health services need health workers.” have?
health appears twice → 5 tokens, 4 types.Slide 24
2. Which statement about LLM tokens matches the slides?
Slide 25; slide 35 also warns that a BoW preprocessing recipe should not automatically become an LLM input recipe.Slides 25, 35
06 · Preprocessing choices

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 Slide 27

ChoicePossible benefitPossible loss
LowercaseMerge Health and healthProper-name distinctions
Remove stopwordsReduce frequent function wordsNegation or writing style
Stem or lemmatizeMerge some word formsDifferences in meaning
Trim rare featuresReduce vocabulary sizeRare but important concepts

Stopwords and negation Slide 28

R · S06 Stopwords and negation, document d3 (slide 28) (W2 slides week2.qmd, reconstructed from the slides for these notes)
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"))
R console output (run locally: 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)
> 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 d3Remaining tokens
Standard English stopword listworkers support policy
List that retains negationworkers not support policy

Retaining not preserves a clue; but a unigram model still needs a way to use its scope.Slide 28 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 Slide 29

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:

R · S07 Selected DFM columns (slide 29) (W2 slides week2.qmd, reconstructed from the slides for these notes)
x <- dfm(toks_content)
as.matrix(x[, c("health", "workers", "government", "policy", "not")])
R console output (run locally: 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)
> 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   0

Identical to the table on slide 29 (health = 2 for d1). Features can also represent phrases or other categories.

What word counts cannot recover Slide 30

After lowercasing, “Workers support government.” and “Government support workers.” have exactly the same unigram counts:

R · S08 Word order is lost (slide 30) (W2 slides week2.qmd, reconstructed from the slides for these notes)
wo <- tokens(c(a = "Workers support government.", b = "Government support workers."),
             remove_punct = TRUE) |> tokens_tolower() |> dfm()
as.matrix(wo)
R console output (run locally: 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)
> 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.Slide 30 (The R check that the two rows above have identical counts was run additionally for these notes.)

Multiword expressions Slide 31

R · S09 Multiword expressions (slide 31) (W2 slides week2.qmd, reconstructed from the slides for these notes)
phrase_toks <- tokens(
  "We support the armed forces.",
  remove_punct = TRUE
) |> tokens_tolower()
tokens_compound(
  phrase_toks,
  pattern = phrase("armed forces")
)
R console output (run locally: 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)
> 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.Slide 31 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 Slide 32

R · S10 Bigrams and operation order (slide 32) (W2 slides week2.qmd, reconstructed from the slides for these notes)
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)
R console output (run locally: 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)
> 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.Slide 32 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 Slide 33

Feature strategyExampleJudgment needed
Known phrasearmed_forcesWhich phrases matter?
Statistical collocationCandidates such as northern_irelandIs the association substantively useful?
Selection by part of speech (POS)Nouns, verbs, adjectivesWhich 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.Slide 33 In the Lab's real output, northern ireland occurs 338 times with λ ≈ 12.41 (Chapter 11).

Stemming and lemmatization Slide 34

MethodExampleLimitation
Stemmingstudies → studiA stem may not be a dictionary word
Lemmatizationstudies may → studyAccuracy depends on language and context
Explicit replacementMap forces to forceOnly handles the mappings you provide

Neither method guarantees correct semantic grouping. A dictionary built from full words may fail to match stemmed features.Slide 34 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)

🎛Preprocessing switches → live DFMToy intuition · Supplement (not from the lecture); corpus from slide 22

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.

dim(x)
–
topfeatures (counts)
–
Remaining tokens in d3
–

Self-check

1. What remains of d3 “Workers do not support the policy.” after removing the standard English stopword list?
not is in the standard stopword list; once it is deleted, the meaning of the sentence is reversed.Slide 28
2. Why should bigrams be created before removing stopwords?
“Deleting words first can create pairs that were never adjacent.”Slide 32
3. Your dictionary uses full words (e.g., “studies”), but the DFM has been stemmed. What can happen?
“A dictionary built from full words may fail to match stemmed features.”Slide 34
07 · Multilingual text and UDPipe

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.

Data sources for this chapter (stated plainly)

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 Slide 35

Language
  • English whitespace is not a universal word boundary.
  • Chinese segmentation needs inspection.
  • Stopwords and word-form tools are language-specific.
Model
  • 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.Slide 35

UDPipe models: Japanese, Chinese, Thai Slide 36

Input languageAccess from RModel
Japaneseudpipe: local UDPipe 1japanese-gsd (UD 2.5)
Traditional Chineseudpipe: local UDPipe 1chinese-gsd (UD 2.5)
Thaihttr2: UDPipe 2 APIthai-tud (UD 2.17)
  • All three provide segmented tokens and predicted upos (POS).
  • Dependency parsing adds heads and relation labels.
  • lemma is the predicted base form; this Thai model returns _ (not available).

Annotating UTF-8 text with UDPipe Slide 37

R · slide 37 (not run for these notes: requires downloading the chinese-gsd model first)
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_id identifies the head; dep_rel labels the relation. Head 0 marks the sentence root.
  • Chinese uses chinese-gsd; English uses english-ewt; Thai uses R + the UDPipe 2 API.Slide 37

Interactive: segmentation and dependency viewer (output from slides 38–42)

🌳Segmentation and dependency viewerInteractive summary · Supplement (not from the lecture); data = UDPipe output on 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.Slides 38–39

Model errors and negation Slides 40–42

  • Japanese “政府は医療従事者を支援する。”: 政府 (NOUN, nsubj → 6), 医療 (compound → 4), 従事者 (obj → 6), 支援 (VERB, root), する (AUX).Slide 40
  • 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.Slide 41
  • Negation “政府不支持刪減醫療預算。”: 不 (ADV) attaches to 支持 (ID 3) as advmod. Keeping only NOUN and VERB removes “不”, so the feature list loses the negation.Slide 42 (Pick this sentence in the viewer above and try unticking ADV.)

From Thai syntax to research measurement Slide 43

→ → →

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.Slide 43 This also echoes the “coffee preference” research design from Chapter 01, slide 4.

Turning UDPipe annotations into quanteda tokens and a DFM Slides 44–45

R · Slide 44 (code sketch; ann_multi is an annotation table)
# 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.Slide 44

🧮Same tokens, three kinds of DFM columnsToy intuition · Supplement (not from the lecture); content based on slide 45

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.Slide 45

Self-check

1. “政府不支持刪減醫療預算。” What happens after keeping only NOUN and VERB?
Slide 42.Slide 42
2. The Chinese output on slide 41 predicts “者” as root and tags “支持” as NOUN. What is the right attitude?
“Inspect the original sentence before interpreting these outputs.”Slide 41
3. What does head = 0 mean in a dependency annotation?
“Head 0 marks the sentence root.”Slides 37, 39
08 · DFM, trimming, TF-IDF, KWIC

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 Slide 46

R · S11 Building and inspecting the DFM (slide 46) (W2 slides week2.qmd, reconstructed from the slides for these notes)
dim(x)
topfeatures(x, 6)
featnames(x)
R console output (run locally: 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)
> 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).Slide 46

Note supports vs. support

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 Slide 47

R · S12 Term and document frequency; trimming (slide 47) (W2 slides week2.qmd, reconstructed from the slides for these notes)
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)
R console output (run locally: 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)
> 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"    
FeatureTotal occurrencesDocuments containing it
health32
workers22
not11

The threshold min_docfreq = 2 removes not. Rare features can still carry crucial meaning.Slide 47 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 Slide 48

RepresentationWhat a cell meansPossible use
CountNumber of occurrencesFrequency-based measurement
BinaryWhether the feature appearsComparison by presence/absence
TF-IDFCount adjusted by how common the feature is in the corpusDocument retrieval or comparison

The choice changes how much repeated words contribute. Model requirements may restrict which representation is appropriate.Slide 48

Writing out the TF-IDF formula Slides 49–50

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.Slide 49
R · S13 TF-IDF in the worked example (slides 49-50) (W2 slides week2.qmd, reconstructed from the slides for these notes)
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)
R console output (run locally: 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)
> 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.301

health: 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.Slide 50

Interactive: TF-IDF calculator

🧮TF-IDF calculatorToy intuition · Supplement (not from the lecture); corpus and formula from slides 22 and 49

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).

N (number of documents)
–
df(t)
–
IDF = log(N / df)
–

Checking context with KWIC Slide 51

R · S14 KWIC (slide 51) (W2 slides week2.qmd, reconstructed from the slides for these notes)
kwic(toks, pattern = "support*", window = 3)
R console output (run locally: 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)
> 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.Slide 51

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

1. In the four-sentence toy corpus, dfm_trim(x, min_docfreq = 2, docfreq_type = "count") removes not because?
df(not) = 1.Slide 47
2. Using the formula on slide 49, what is the TF-IDF of a word that appears in all 4 documents?
“A feature in every document receives IDF = 0 under this formula.”Slide 49
3. What is the TF-IDF (count, log10) of health in d1?
2 × log10(4/2) = 2 × 0.3010 = 0.6021.Slide 50
09 · Research uses and sensitivity

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 Slide 52

ToolWhat it lets you do
DFMRepresent document features for comparison and modelling
KWICRead words in context to check what feature counts mean
TF-IDFEmphasize 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”.Slide 52

Research applications of a DFM Slide 53

Research goalMethodOutput
Estimate positionsWordfish / WordscoresRelative positions of documents
Predict categoriesSupervised classifierIssue or stance labels
Study issue attentionLDA / STM / keyATMTopics and topic proportions
Measure a conceptDictionaryCategory counts or proportions
Compare documentsCosine similarity / clusteringSimilarity 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.Slide 53 These methods are covered in depth in W4 (dictionaries), W7 (scaling), W8 (topic models) and other weeks.

Interactive: method matching

🧭Research goal → method → required inputPractice · based on slides 52–53

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 Slides 54–58

CategoryStudyOne-line summary on the slides
Topic modelsSTM: Roberts et al. (2014)Compare topics in survey responses across respondent groups.Slide 54
Topic modelskeyATM: Eshima et al. (2024)Guide topics with selected keywords to study policy attention.Slide 54
Text scalingWordfish: 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).Slides 55–56
Text scalingWordscores: 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).Slides 55, 57
TF-IDFText similarity: Blumenau (2021)Track whose language later speakers use in House of Commons debates.Slide 58
TF-IDFStance classification: Bestvater & Monroe (2023)Classify political support or opposition with TF-IDF plus SVM.Slide 58

TF-IDF provides weighted features; the analysis determines what we measure.Slide 58 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 Slide 59

ComparisonCheckInterpretation
With / without stopwordsNegation and grammatical contextWhich distinctions disappear?
Unigrams / phrasesCompound conceptsWhich matches change?
Full / trimmed vocabularyDropped features and empty rowsWhich documents lose evidence?
Counts / TF-IDFRelative contribution of featuresDo results depend on weighting?

Keep the corpus and research question fixed while comparing a chosen rule.Slide 59 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

1. You want to compare the positions of party manifestos with Wordfish. The input should be?
“Input: counts, not TF-IDF weights.”Slide 52
2. What is the main difference between Wordscores and Wordfish?
Slides 52–53, 55.Slides 53, 55
3. When doing sensitivity checks, what does slide 59 ask you to keep fixed?
“Keep the corpus and research question fixed while comparing a chosen rule.”Slide 59
10 · Lab 1–2

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 Slides 60–61

  • Download and install R and Python 3, then install RStudio Desktop and Positron.
  • Try the console: type 1 + 1 in R and print(1 + 1) in Python; both return 2.
  • Open Lab_Session_W2.R in lab/ and install the packages in the R console (only once):
R · Slide 60
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.Slide 60 The Lab is not graded and nothing is submitted; no Python, language models or APIs are needed.Slide 61

R · load_packages (W2/lab/answers/Lab_Session_W2_Answers.R)
# 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)
R console output (run locally: 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)
> # 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

Comparison result (50 chunks compared one by one)

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

R · read_hoc_sample (W2/lab/answers/Lab_Session_W2_Answers.R)
# 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)
R console output (run locally: 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)
> # 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] 5000
paths[file.exists(paths)]
Tries four possible relative paths in turn; if none is found, file.choose() pops up so you can pick the file manually.
setwd(dirname(dirname(data_path)))
Sets the working directory to the parent of Data/ (i.e., lab/).
nrow(hoc)
5000 = number of speeches, not number of MPs.
R · create_year (W2/lab/answers/Lab_Session_W2_Answers.R)
hoc <- hoc |>
  mutate(year = as.integer(format(date, "%Y")))

hoc |>
  select(date, year, speaker, party, agenda, terms) |>
  head(5)
R console output (run locally: 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)
> 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)    50

terms 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

R · create_agenda_vector (W2/lab/answers/Lab_Session_W2_Answers.R)
agenda_labels <- hoc$agenda[1:8]

agenda_labels
str(agenda_labels)
R console output (run locally: 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)
> 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)" ...
R · extract_first_pattern (W2/lab/answers/Lab_Session_W2_Answers.R)
str_extract(agenda_labels, "Trade")
str_extract(agenda_labels, "WAR")
R console output (run locally: 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)
> 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   
R · case_sensitive_matching (W2/lab/answers/Lab_Session_W2_Answers.R)
str_extract(agenda_labels, "war")
str_extract(str_to_lower(agenda_labels), "war")
R console output (run locally: 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)
> 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   
How to read the output
  • NA means 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; after str_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.
R · locate_matching_strings (W2/lab/answers/Lab_Session_W2_Answers.R)
str_which(str_to_lower(agenda_labels), "war")
str_which(str_to_lower(agenda_labels), "trade")
R console output (run locally: 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)
> str_which(str_to_lower(agenda_labels), "war")
[1] 3 5 7
> str_which(str_to_lower(agenda_labels), "trade")
[1] 1
R · locate_pattern_positions (W2/lab/answers/Lab_Session_W2_Answers.R)
str_locate(str_to_lower(agenda_labels), "war")
R console output (run locally: 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)
> 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  NA

str_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

R · inspect_speech_urls (W2/lab/answers/Lab_Session_W2_Answers.R)
speech_urls <- hoc$speech_url[1:5]

speech_urls
R console output (run locally: 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)
> 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"
R · extract_digits (W2/lab/answers/Lab_Session_W2_Answers.R)
str_extract(speech_urls, "\\d")
str_extract(speech_urls, "\\d+")
str_extract_all(speech_urls, "\\d+")
R console output (run locally: 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)
> 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"      
R · extract_url_dates (W2/lab/answers/Lab_Session_W2_Answers.R)
str_extract(speech_urls, "\\d{4}/[a-z]{3}/\\d{2}")
R console output (run locally: 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)
> 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"
"\\d"
One digit → the first digit of every URL is “1”.
"\\d+"
One or more digits → the first run of digits, “1945”.
str_extract_all(…, "\\d+")
All runs of digits: year, day, plus 5, 0407, 0, 19450116, 118… from the URL anchor (these are not dates!).
"\\d{4}/[a-z]{3}/\\d{2}"
Four digits / three lowercase letters / two digits → “1945/jan/16”.
R · word_boundary_examples (W2/lab/answers/Lab_Session_W2_Answers.R)
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")
R console output (run locally: 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)
> 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)

R · replace_patterns (W2/lab/answers/Lab_Session_W2_Answers.R)
str_replace(agenda_labels, "Trade", "TRADE")
str_replace_all(agenda_labels, "[aeiou]", "-")
R console output (run locally: 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)
> 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

R · inspect_business_agendas (W2/lab/answers/Lab_Session_W2_Answers.R)
hoc |>
  filter(str_detect(str_to_lower(agenda), "business of the house")) |>
  count(agenda, sort = TRUE) |>
  head(10)
R console output (run locally: 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)
> 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  1

The same agenda, “Business of the House”, has at least three capitalizations (56 + 54 + 34 records), plus many variants with bracketed context.

R · clean_agenda_labels (W2/lab/answers/Lab_Session_W2_Answers.R)
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)
R console output (run locally: 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)
> 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   8
str_to_lower() |> str_squish()
Unify case and collapse whitespace.
str_replace_all("\\s*\\[.*\\]", "")
Delete bracketed context (note that this uses the greedy .*, the case from Chapter 04, slide 20; agenda labels usually have only one pair of brackets, so the impact is small).
case_when(…)
Gives four common agendas a unified spelling; merges all labels beginning with engagements into “Engagements”; uses str_to_title() for the rest.
The Lab's reminder: cleaning is not neutral

Merging 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)

🧽Agenda cleaning pipelineReal data · JS reproduces the R rules

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.

Distinct labels (excluding NA)
–
“Engagements” records
–
Check against R top 15
–
JS result: top 15
Most-merged labels (click a row to see the original spellings)

Build and inspect a corpus

R · create_hoc_corpus (W2/lab/answers/Lab_Session_W2_Answers.R)
hoc_corpus <- corpus(
  hoc,
  text_field = "text"
)
R · summarise_hoc_corpus (W2/lab/answers/Lab_Session_W2_Answers.R)
summary(hoc_corpus, n = 10)
R console output (run locally: 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)
> 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 Bill

The 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).

R · count_documents (W2/lab/answers/Lab_Session_W2_Answers.R)
ndoc(hoc_corpus)
R console output (run locally: 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)
> 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)

R · inspect_docvars (W2/lab/answers/Lab_Session_W2_Answers.R)
names(docvars(hoc_corpus))
head(docvars(hoc_corpus, "party"), 10)
head(docvars(hoc_corpus, "agenda_clean"), 10)
R console output (run locally: 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)
> 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"          
R · inspect_corpus_text (W2/lab/answers/Lab_Session_W2_Answers.R)
as.character(hoc_corpus)[1]
R console output (run locally: 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)
> 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 Slide 6

R · subset_labour_since_2010 (W2/lab/answers/Lab_Session_W2_Answers.R)
labour_since_2010 <- corpus_subset(
  hoc_corpus,
  party == "Labour" & year >= 2010
)

ndoc(labour_since_2010)
summary(labour_since_2010, n = 5)
R console output (run locally: 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)
> 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 Allowance

271 Labour speeches from 2010 onward; hoc_corpus is still the full 5,000 speeches.

R · subset_engagements (W2/lab/answers/Lab_Session_W2_Answers.R)
engagements_corpus <- corpus_subset(
  hoc_corpus,
  agenda_clean == "Engagements"
)

ndoc(engagements_corpus)
summary(engagements_corpus, n = 5)
R console output (run locally: 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)
> 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  Engagements
R · reshape_to_sentences (W2/lab/answers/Lab_Session_W2_Answers.R)
engagements_sentences <- corpus_reshape(
  engagements_corpus,
  to = "sentences"
)

ndoc(engagements_corpus)
ndoc(engagements_sentences)
R console output (run locally: 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)
> 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)

R · inspect_sentence_corpus (W2/lab/answers/Lab_Session_W2_Answers.R)
as.character(engagements_sentences)[1:5]
R console output (run locally: 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)
> 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." 
Reading the output: sentence boundaries split wrongly
  • 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

✅I have run this in RStudio / PositronSaved in this browser

Self-check

1. str_extract(agenda_labels, "war") returns NA everywhere, but after str_to_lower() it matches 3. Why?
Lab: Pattern matching is case-sensitive by default.
2. corpus_reshape(engagements_corpus, to = "sentences") turns 81 documents into 364. Which statement is false?
The total amount of text is unchanged, but the definition of “a document” has changed, so comparisons and statistics change with it.Slide 6
3. After cleaning, the top entry of agenda_clean is <NA> (206 records). What does this mean?
The first row of the frequency table of the original agenda is already NA 206 (output of Exercise 7).
11 · Lab 3–4

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 Slide 31

R · tokenize_hoc_corpus (W2/lab/answers/Lab_Session_W2_Answers.R)
hoc_tokens <- tokens(
  hoc_corpus,
  remove_punct = TRUE,
  remove_symbols = TRUE,
  remove_numbers = FALSE
)
R · compound_multiword_expressions (W2/lab/answers/Lab_Session_W2_Answers.R)
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 Slide 51

R · kwic_european_union (W2/lab/answers/Lab_Session_W2_Answers.R)
kwic(
  hoc_tokens,
  pattern = phrase("European_Union"),
  window = 8
) |>
  head(10)
R console output (run locally: 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)
> 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     
R · kwic_economy (W2/lab/answers/Lab_Session_W2_Answers.R)
kwic(
  hoc_tokens,
  pattern = "economy",
  window = 8,
  valuetype = "fixed",
  case_insensitive = TRUE
) |>
  head(10)
R console output (run locally: 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)
> 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)

🔍KWIC explorerReal data · sample of 700

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.

Matches
–
Speeches containing it
–
Per 1,000 words (sample)
–

A second set of tokens for the DFM

R · tokenize_for_dfm (W2/lab/answers/Lab_Session_W2_Answers.R)
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)
padding = TRUE
Removed words leave empty placeholders, so words that were not adjacent are not joined together—avoiding the “creating pairs that never existed” problem from slide 32, which matters especially for finding collocations.
remove_url = TRUE, split_hyphens = FALSE
Removes URLs; hyphenated words like post-war stay one token.
tokens_tolower() |> tokens_remove(stopwords("en"), padding = TRUE)
Lowercases and removes 175 English stopwords (including not).

Collocations Slide 33

R · find_collocations (W2/lab/answers/Lab_Session_W2_Answers.R)
hoc_collocations <- textstat_collocations(
  hoc_tokens_dfm,
  min_count = 10
) |>
  arrange(desc(lambda))

head(hoc_collocations, 20)
R console output (run locally: 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)
> 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.646568
How to read the output
  • lambda (λ) is the strength of association and z its standardized value; the list is sorted by λ. hong kong (λ ≈ 18.02), sri lanka and per cent (724 times) come first.
  • northern ireland occurs 338 times with λ ≈ 12.41—the “statistical collocation candidate” example on slide 33.
  • sinn fein (17) and sinn 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.
R · compound_collocations_for_dfm (W2/lab/answers/Lab_Session_W2_Answers.R)
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 Slide 46

R · create_party_dfm (W2/lab/answers/Lab_Session_W2_Answers.R)
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)
R console output (run locally: 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)
> 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)

R · inspect_top_features (W2/lab/answers/Lab_Session_W2_Answers.R)
topfeatures(hoc_dfm_party, 25)
R console output (run locally: 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)
> 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 Slide 47

R · trim_party_dfm (W2/lab/answers/Lab_Session_W2_Answers.R)
hoc_dfm_party_trimmed <- dfm_trim(
  hoc_dfm_party,
  min_termfreq = 10
)

dim(hoc_dfm_party)
dim(hoc_dfm_party_trimmed)
R console output (run locally: 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)
> 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)

✂️min_termfreq thresholdReal data · term-frequency distribution of hoc_dfm_party

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).

Features kept
–
Tokens kept (share of all)
–
Features occurring once (hapax)
–

Word cloud and frequency plot

R · plot_wordcloud (W2/lab/answers/Lab_Session_W2_Answers.R)
set.seed(719102)  # keep the layout reproducible
textplot_wordcloud(hoc_dfm_party_trimmed, max_words = 50)
Word cloud of the party-level DFM (generated locally in R)
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)

R · plot_feature_frequency (W2/lab/answers/Lab_Session_W2_Answers.R)
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()
Top 25 most frequent features (generated locally in R)
Top 25 most frequent features (generated locally in R). A dot plot makes sizes easier to compare than a word cloud.

Comparing parties with keyness

R · conservative_keyness (W2/lab/answers/Lab_Session_W2_Answers.R)
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)
R console output (run locally: 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)
> 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)
Conservative keyness plot (generated locally in R)
textplot_keyness(conservative_keyness, n = 20) (generated locally in R).
How to read the output
  • 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)

⚖️Keyness explorerReal data · hoc_dfm_party_trimmed

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).

Over-represented in the target (χ² > 0)
Over-represented in the reference (χ² < 0)
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.Slide 59

Tracking a feature over time

R · conservative_economy_by_year (W2/lab/answers/Lab_Session_W2_Answers.R)
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()
Yearly economy counts for Conservative (generated locally in R)
Raw yearly counts of economy in Conservative speeches (generated locally in R).

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)

📈Feature time seriesReal data · by year; the “per 1,000 tokens” conversion is a supplement (not from the lecture)

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

1. dim(hoc_dfm_party) is 23 × 30640. What is 23?
After grouping, rows are parties, columns are features, and cells are summed counts.
2. In the keyness results, cyberstalking has a very high χ² (42 vs. 0). What is the best next step?
Keyness compares word use; it is not issue salience or sentiment. Go back to the text first.Slide 51
3. Why do the tokens for the DFM use padding = TRUE?
Lab: padding helps identify collocations; this echoes the order-of-operations issue on slide 32.Slide 32
12 · Exercises 1–11

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 Slide 62

  • 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.R and 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.Slide 62

The 11 exercises

Exercise 1 · 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)
R · exercise_detect_sir (W2/lab/answers/Lab_Session_W2_Answers.R)
speaker_names <- hoc$speaker[1:20]

speaker_names
str_detect(speaker_names, "Sir")
speaker_names[str_detect(speaker_names, "Sir")]
R console output (run locally: 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)
> 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.

Exercise 2 · str_extract_all()

Use str_extract_all() to extract all four-digit years from the first 20 speech_url values.

Show reference answer
R · exercise_extract_years_from_urls (W2/lab/answers/Lab_Session_W2_Answers.R)
speech_urls_20 <- hoc$speech_url[1:20]

str_extract_all(speech_urls_20, "\\b\\d{4}\\b")
R console output (run locally: 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)
> 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.

Exercise 3 · Creating an indicator variable

Create a new variable mentions_prime_minister that detects whether the speech text contains Prime Minister. How many speeches mention it?

Show reference answer
R · exercise_prime_minister_indicator (W2/lab/answers/Lab_Session_W2_Answers.R)
hoc <- hoc |>
  mutate(
    mentions_prime_minister = str_detect(
      str_to_lower(text),
      "\\bprime minister\\b"
    )
  )

sum(hoc$mentions_prime_minister)
R console output (run locally: 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)
> 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.

Exercise 4 · corpus_subset()

Use corpus_subset() to build a corpus of Conservative speeches from 2016 onward. How many documents are there?

Show reference answer
R · exercise_subset_conservative (W2/lab/answers/Lab_Session_W2_Answers.R)
conservative_since_2016 <- corpus_subset(
  hoc_corpus,
  party == "Conservative" & year >= 2016
)

ndoc(conservative_since_2016)
summary(conservative_since_2016, n = 5)
R console output (run locally: 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)
> 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 Commission

368.

Exercise 5 · corpus_reshape() (follows Exercise 4)

Reshape the corpus from Exercise 4 into sentences. How many sentence-level documents are there?

Show reference answer
R · exercise_reshape_conservative_sentences (W2/lab/answers/Lab_Session_W2_Answers.R)
conservative_sentences <- corpus_reshape(
  conservative_since_2016,
  to = "sentences"
)

ndoc(conservative_sentences)
as.character(conservative_sentences)[1:5]
R console output (run locally: 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)
> 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.

Exercise 6 · Phrases + KWIC

Tokenize while keeping the three multiword expressions Prime Minister, European Union and House of Commons, then inspect Prime_Minister with kwic().

Show reference answer
R · exercise_kwic_prime_minister (W2/lab/answers/Lab_Session_W2_Answers.R)
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)
R console output (run locally: 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)
> 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.

Exercise 7 · Comparing before and after cleaning

Count the 10 most common values of agenda and of agenda_clean. What changed after cleaning?

Show reference answer
R · exercise_compare_agenda_cleaning (W2/lab/answers/Lab_Session_W2_Answers.R)
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.
R console output (run locally: 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)
> 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.

Exercise 8 · Three-feature collocations

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
R · exercise_three_word_collocations (W2/lab/answers/Lab_Session_W2_Answers.R)
textstat_collocations(
  hoc_tokens_dfm,
  size = 3,
  min_count = 5
) |>
  arrange(desc(lambda)) |>
  head(20)
R console output (run locally: 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)
> 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.193026

transport 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).Slide 32

Exercise 9 · Grouped DFM

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
R · exercise_create_grouped_dfm (W2/lab/answers/Lab_Session_W2_Answers.R)
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)
R console output (run locally: 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)
> 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.

Exercise 10 · Trimming (follows Exercise 9)

Trim hoc_dfm_exercise to keep only features that occur at least 20 times. Look at the new dimensions.

Show reference answer
R · exercise_trim_grouped_dfm (W2/lab/answers/Lab_Session_W2_Answers.R)
hoc_dfm_exercise_trimmed <- dfm_trim(
  hoc_dfm_exercise,
  min_termfreq = 20
)

dim(hoc_dfm_exercise)
dim(hoc_dfm_exercise_trimmed)
R console output (run locally: 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)
> 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.

Exercise 11 · Labour keyness (follows Exercise 10)

Use textstat_keyness() to show the features that most distinguish Labour from all other parties.

Show reference answer
R · exercise_labour_keyness (W2/lab/answers/Lab_Session_W2_Answers.R)
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)
R console output (run locally: 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)
> 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)
Labour keyness plot (generated locally in R)
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)

ExerciseKey numbers
15 of the first 20 speakers contain Sir
3279 speeches mention prime minister
4 / 5Conservative since 2016: 368 speeches → 2,995 sentences
7Business of the House: scattered as 56 / 54 / 34… before cleaning, 151 after
9 / 1023 × 30,640 → 23 × 3,424 (min_termfreq = 20)
11Labour top three: waste (χ² 73.18), advertising (51.96), giro (44.04)

Self-check

1. Exercise 2 extracts years with "\\b\\d{4}\\b", and URL 12 yields “1945” and “1914”. What is the correct reading?
A pattern matches a “shape”; meaning has to be judged from context.
2. Labour's keyness in Exercise 11 includes tory and conservative. What does this most likely reflect?
Lab: keyness is a comparison of word use, not a sentiment score.
13 · Readings and discussion

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. Slides 8, 14, 64

Type of articleTeacher’s corner (a teaching introduction): gives an overview of the general steps and operations of a computational text analysis project and demonstrates how to do each step in R (p. 245 abstract). It focuses mainly on bag-of-words: using only word frequencies per text and ignoring word positions (p. 246).
StructureTable 1 divides the operations into three parts—data preparation, analysis, advanced topics—and lists the packages used plus alternatives (p. 247); Figure 1 is a diagram of the order of operations (p. 247)—these are the two reproduced on slides 8 and 14.
Five data-preparation stepsimporting text, string operations, preprocessing, document-term matrix, filtering and weighting (p. 248). It stresses that the choices made in preparing text can affect accuracy, validity and findings as much as the analysis technique itself (p. 248).
EncodingRecommends making sure all text in R is UTF-8: read UTF-8 directly, or convert from a known encoding on import; when the encoding is unknown, readtext's functions can guess it (p. 249). Compare slide 16.
Preprocessingtokenization (the period in “Dr.”; Chinese and Japanese have no whitespace word boundaries, p. 250); lowercasing and stemming (SnowballC; p. 251); stopwords (p. 251); order matters: stemming before removing stopwords turns “during” into “dure”, which no longer matches the stopword list (p. 252).
DTM, trimming and weightingA DTM has documents as rows, terms as columns and counts in cells (p. 252); quanteda's dfm uses the Matrix package as a backend (p. 252); document variables can be used to group and aggregate (e.g., tweets by user or date, p. 253); filter with document-frequency thresholds, or use tf-idf to give more common terms lower weight (p. 253).
AnalysisFollowing Boumans & Trilling (2016): counting and dictionary, supervised ML, unsupervised ML, ordered from deductive to inductive, plus text statistics (pp. 254–255).
Advanced topicsadvanced NLP (lemmatization, POS, dependency parsing; spacyr and others, pp. 258–259); keeping word positions and syntax, n-grams and skipgrams—n-grams can handle negations such as “not good”, but are computationally heavier and need more data (pp. 260–261).
Link to this weekSlide 8 specifically notes that Table 1 is a historical overview from 2017: package roles and APIs have changed since (e.g., this week uses stringr, UDPipe and Flair instead).

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. Slides 10, 25, 50, 53

What it isAn R package providing a complete workflow: corpus management, tokenization, analysis and visualization; it includes dictionary analysis, KWIC, document and feature similarity, and finding multiword expressions by scoring collocations (p. 1).
Definition of a corpusA collection of texts that includes document-level variables for each text plus metadata for the documents and the whole collection; it can be segmented by words, paragraphs or sentences, and grouped or subset by document variables (p. 1). Compare slides 15 and 23 and the Lab's corpus_subset / corpus_reshape.
TechnologyUses the ICU library via stringi for Unicode regex and word boundaries; tokens are mapped to an integer hash table for speed and memory savings; DFMs are often more than 90% sparse (p. 2).
Models and statisticstextmodel_* 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).
Design principlesConsistent naming (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).
Link to this weekAlmost everything the Lab uses follows this naming scheme: 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.Slide 54
  • Slapin & Proksch (2008) Wordfish; Lowe (2008), Laver et al. (2003) Wordscores.Slides 55–57
  • Blumenau (2021); Bestvater & Monroe (2023).Slide 58
  • Grimmer, Roberts & Stewart (2022) Text as Data, Chapter 4 (book).Slides 4, 64
  • Schoonvelde (2026) Essex Summer School slides (called the “main lecture source” on slide 64; 38 pages).Slide 64

Class discussion Slide 63

Pick one of the applied papers introduced earlier, and first look at its research question and one main figure or table:

  1. What is the research question? What counts as a document?
  2. How might removing words, aggregating documents or weighting affect this measurement?
  3. 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).Slide 63

Interactive: judging claims—does this statement hold up?

⚖️Judging claimsPractice · based on the slides and Lab output

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

🗒Slide 63 discussion prep cardAutosaved · export to Markdown

    

Self-check

1. According to Welbers et al. (2017, p. 252), why remove stopwords before stemming?
The order of operations changes the result; this is the same kind of problem as the bigram order on slide 32.Slide 32
2. What naming convention for quanteda functions do Benoit et al. (2018) describe?
JOSS p. 3, Consistency.
14 · Wrap-up

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

PitfallWhy it is a problemEvidence from this week
Treating available texts as the populationResources, incentives, media and retrieval all introduce biasSlides 4–5 Slide 5
Overwriting the original textYou cannot check what cleaning changedThe Lab saves agenda_clean separately Slide 18
Greedy regex\[.*\] deletes all the way to the last ]“Trade ” Slide 20
No word boundarieswar matches warfare and towardsLab word_boundary_examples
A standard stopword list removes negationThe meaning of d3 is reversedworkers support policy Slide 28
Removing words before building bigramsCreates pairs that never existedworkers_support Slide 32
Keeping only NOUN / VERBThe negation “不” (ADV) disappearsSlide 42 Slide 42
Trimming away rare but crucial wordsmin_docfreq = 2 removes notSlide 47 Slide 47
Treating raw counts as attentionThe denominator (speeches, tokens) differs from year to yearYearly economy plot (Chapter 11)
Treating keyness as position or sentimentIt is only a comparison of word use, often dominated by parliamentary language and a few long speecheshon, friend, cyberstalking (Chapter 11)

Glossary (searchable)

📖Term lookupSearch terms and definitions

Final review Slide 62

📝16-question final reviewNot answered yet

Preprocessing decision log (for your project) Slides 2, 59

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.

🗒Preprocessing decision log formAutosaved · export to Markdown

    

My progress

📌Progress overviewStored only in this browser

Only the records for these W2 notes are cleared.

References and software Slide 64

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.
These notes are based on the NTLDEV 7191 W2 slides (Yen-Chieh Liao, 2026-09-18; 64-page PDF, last compiled 2026-09-20), W2/slide/week2.qmd, W2/lab/Lab_Session_W2.R, W2/lab/answers/Lab_Session_W2_Answers.R / .html, W2/lab/README.md and the two PDFs in W2/papers/. R output is from a local rerun (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) and matches the output in the instructor's answer HTML chunk by chunk. The UDPipe demo was not rerun (the output on the slides is used). Passages and toy demos marked “Supplement (not from the lecture)” are additional explanation. Prepared 2026-11-06.
NTLDEV 7191 Text as Data · W2 interactive self-study notes · based on the 2026-09-18 lecture slides (2026-11-06)