W1: Introduction to Text as Data (How We Can Use Text as Data for Social Science Research)
Week 1 covers two things: Part 1 explains what text as data is, how the field developed and what it is used for; Part 2 explains how this course works: schedule, tools, grading, extra credit, AI use and academic integrity.
What you should be able to explain this week
The slides do not list "learning goals"; the four points below are organized from the structure of slides 2–34 (the organization is a supplement; every item has a slide source):
- Explain in one sentence what text as data means, and name each step of the pipeline corpus → representation → model → validation → inference.
- Tell whether a study is Measurement (contribution in measurement / method) or Application (contribution in substantive findings), and explain why validation has always been a core requirement.
- State the course's grading structure, the three key deadlines (10/23, 12/4, 12/18) and the conditions of the extra-credit rules.
- Know how you must disclose generative AI use in assignments, and the consequences of not disclosing.
After reading a chapter, come back and tick the goals you think you can now meet (stored only in this browser):
Concept map: from text to inference
Slide 4 writes text-as-data research as a chain: corpus → representation → model → validation → inference. Click each step for an explanation (the explanations are organized from slide 4; the examples are supplementary):
- Corpus: e.g., parliamentary speeches, party manifestos, court rulings, news, tweets, open-ended survey responses.
- Representation: bag of words, word embeddings, language models.
- Model: dictionaries, classifiers, topic models, scaling.
- Validation: comparison with human coding, expert judgment, external benchmarks.
- Inference: use what you measured to answer a social science question; "the social science question is the job."
Materials used in these notes
| Material | How these notes use it |
|---|---|
Slides W1/slide/week1.pdf (38 pages, compiled 2026-09-20) | Chapter structure, all course rules and numbers; the slide panel on the right shows page images of this PDF. |
Syllabus NTLDEV_7191_1151.pdf | The grading table on slide 25 is an image, so weights and deadlines were checked against the text table in syllabus §8.1 (page 40 of the syllabus PDF); the workload differs, see chapter 06. |
W1/papers/: Grimmer & Stewart (2013), Benoit (2020), Baden et al. (2022) | Chapter 12 reading guide, with page numbers. |
| R scripts | W1 has no classroom or lab R script. Chapter 11 is a small Supplement (not from the lecture) written by the TA: it uses quanteda to treat this week's slides as a 38-document corpus, and all output comes from actually running it locally. |
How to use these notes
- Reading the chapters on the left in order works best. Chapters 00–04 are Part 1 (research content), chapters 05–10 are Part 2 (course rules), and chapter 11 is a supplementary lab.
- Badges marked are clickable: the slide opens on the right (or via the button at bottom right), and the panel also follows as you scroll.
- The blue "interactive lab" boxes can be used directly and come in three kinds: real data (the schedule, grading weights, extra-credit rules, Baden et al.'s language statistics, the slide corpus exported from R in chapter 11), toy intuition (marked "Supplement"; the numbers are not course results) and practice (sorting questions, scenario judgments, flashcards, an AI disclosure statement generator, a research-idea builder).
- Each chapter ends with a "Self-check"; chapter 14 has a final review (you can redo only the questions you got wrong).
- Progress and your entries are stored only in this browser's localStorage; chapter 14 can clear them with one click.
Dates to write down
- W7 · 10/23: individual research abstract due
- W13 · 12/4: midterm research design report due
- W14 · 12/11: poster workshop
- W15 · 12/18: final poster presentations
- Deadline for the full paper (manuscript) and extra credit: TBA
- No class: W3 (9/25), W5 (10/9), W11 (11/20), W16 (12/25)
Self-check
Why text? What is text as data
Why text?
The starting point of slide 3: most political activity leaves a textual or digital trace.
- Parliamentary speeches, hearing transcripts, party manifestos
- Court rulings, bills, administrative records, diplomatic cables
- News reports, social media posts, politicians' tweets
- Open-ended survey responses, interview transcripts
Then: human reading and hand coding (e.g., the Manifesto Project).
Now: scale: millions of documents can be analyzed systematically.
Benoit (2020) opens in a similar way: legislative debates, manifestos, committee transcripts, speeches, lobbying documents, court opinions and laws are not only recorded today, but many are in forms that are easy to turn into structured data (Benoit 2020, repo PDF p. 2).
What is "Text as Data"?
Slide 4 also lists common options at three stages of the pipeline:
| Stage | Options listed on slide 4 | Roughly which weeks of this course (from syllabus schedule titles; supplement) |
|---|---|---|
| Representation | bag of words, word embeddings, language models | W4 (tokenisation, DFM), W9 (embeddings), W10, W12 (transformers, LLMs) |
| Model | dictionaries, classifiers, topic models, scaling | W4 (dictionaries), W6 (classification), W7 (scaling), W8 (topic models) |
| Validation | comparison with human coding, expert judgment, external benchmarks | Appears every week |
The first step of representation: bag of words
This week's slides only name "bag of words"; the details come in W4. Here we borrow Grimmer & Stewart (2013) to build intuition: when turning text into numbers, the most consequential and most surprising step is discarding word order, assuming documents are a "bag of words". The authors argue that examples where word order changes the meaning of a sentence are rare in practice, and unigrams alone usually suffice to convey the gist of a text; if that is unacceptable, bigrams and trigrams can be added to retain some word order (Grimmer & Stewart 2013, p. 272).
They also warn that all quantitative models of language are wrong. Their example is the classic joke "Time flies like an arrow. Fruit flies like a banana.": the same "flies like" is a metaphor in the first half and literal in the second (p. 270). A bag of words cannot see this difference at all.
Interactive: bag-of-words builder
Type a document (in English) in each box; the document-feature matrix below updates instantly. The tokenization rule is a simplified version written for these notes (splitting on spaces and punctuation), not quanteda's rule; quanteda's real results are in chapter 11.
Try "Example: swapped word order": the two sentences mean opposite things but are identical in a unigram bag of words; only after ticking bigrams can they be told apart. This is the trade-off Grimmer & Stewart describe.
Self-check
How the field got here
Three phases, seven studies
| Phase | Study | Slide 5's one-liner |
|---|---|---|
| 2003–2010 · Bag of words | Wordscores (2003), Laver, Benoit & Garry · APSR | — |
| Wordfish (2008), Slapin & Proksch · AJPS | — | |
| Expressed agenda (2010), Grimmer · Political Analysis | — | |
| 2013–2014 · Validation | Promise and Pitfalls (2013), Grimmer & Stewart · Political Analysis | the four principles — and “validate” |
| Structural topic model (2014), Roberts et al. · AJPS | topics as a function of covariates | |
| 2023– · Meaning in context | Embedding regression (2023), Rodríguez, Spirling & Stewart · APSR | what a word means, by party and era |
| LLMs as annotators (2024), Heseltine & Clemm von Hohenberg · Research & Politics | — |
Slide 5's summary: what did each phase add? bag of words → validation & covariates → meaning in context → models that label for you.
Interactive: click a phase
Sources of the descriptions: sentences in quotation marks come from slide 5; descriptions of the other three are based on the paper titles listed on slides 35–38 (for Wordscores and Wordfish, see also Grimmer & Stewart 2013, p. 269); "which week of this course" is matched from the syllabus schedule titles and is supplementary.
Practice: put them in chronological order
Click the studies below from earliest to latest. A wrong click gives a hint, and you can start over.
“Validation is the one demand that never went away.”
This sentence is one of the most important messages of the week. Grimmer & Stewart's (2013) fourth principle is "Validate, Validate, Validate" (Table 1, p. 269); Baden et al. (2022) surveyed authors of text-analysis studies and found that 40% saw validity as a major concern and another 35% as a minor concern (p. 6). In the era of LLMs as annotators, the question is still: does what the model labels match the concept you want to measure?
The tools keep changing: word counts, topics, vectors, LLMs. But every generation of researchers has to answer the same question: "How do you know you measured the thing you say you measured?"
Self-check
Two kinds of work: Measurement and Application
Text-as-data research does two different things
| Measurement | Application | |
|---|---|---|
| Core question | How do you turn a concept into a credible, text-based measure? | What substantive question does this measure answer? |
| Contribution | New methods, new measures, new datasets | New empirical findings, theory testing |
| Star of the show | The method itself | Research design and identification |
Mapping to the textbook
The textbook Grimmer, Roberts & Stewart (2022) divides the work into three tasks: discovery, measurement, inference. This course merges them into two: measurement ≈ discovery + measurement; application ≈ inference. The book is the framework for the lectures, but you do not need to buy it; the course is paper-based, with 3–4 core readings per week, and excerpts of required book chapters will be provided.
Practice: which kind of work is this?
Each item describes the "main contribution" of a study. Pick one according to slide 6's definitions. The scenarios were written for these notes (supplement); the basis for judging is slide 6.
Not answered yet.
Self-check
Two research cases: From Pork to Policy, and turning open-ended answers into causal maps
Case 1: From Pork to Policy
Catalinac (2016), The Journal of Politics 78(1): 1–18. Slide 7 focuses on the role of the method:
- Method: an off-the-shelf tool, not a new one: LDA (2003), with every topic validated by reading.
- The contribution is political science, not a new algorithm.
- Building new NLP models is the job of computer science; our job is to use them well to answer a question.
Slide 7 shows a screenshot of the paper's abstract; W1's papers/ folder does not contain the full text, so these notes do not summarize the paper's content or numbers. This paper reappears in W8 (topic models).
Case 2: coding open-ended answers as causal maps
- Jankin, Liao & Tang (2026), Folk Theories of Partisan Conflict (working paper)
- Question: does what a partisan believes about "why the country is divided" matter beyond how much they dislike the other side?
- Data: 1,200 US adults (quota-matched); several open-ended questions (the figure on the slide codes Q7).
“Which factors, events, groups, or institutions do you think caused Democrats and Republicans to view each other more negatively than they did 50 years ago? Please explain what caused what, who or what you think was responsible, and what effects followed.”
- Same factors, opposite arrows: only the direction separates the two theories; the graph gives each person's root cause.
- Validation: coder agreement on "which factors each answer mentions" κ = 0.84; an LLM using the same codebook compared with human coding F1 = 0.92.
- What the text does: the theory you hold predicts your tolerance of anti-democratic actions, even after controlling for affective polarization (affect) and ideology.
The figure on slide 9 (Fig. 4) shows common folk theories grouped by root cause (% = share within party); these notes do not transcribe the figure's numbers, so see the slide on the right. This is a working paper; the repo has no full text.
Interactive: same factors, opposite arrows
The three factors below are a toy example made up for these notes, not the paper's 15 factors. Click the button next to each edge to flip the arrow (or delete it), and see how the "root cause" (a factor that no arrow points to) changes.
Interactive: what do κ and F1 compute?
Suppose two coders (or "human vs. LLM") each judge whether N answers "mention a given factor". Enter the four cells of the 2×2 table. These are toy numbers, not the paper's data; the slide's κ = 0.84 and F1 = 0.92 cannot be reproduced from the data in the repo.
| Coder 2: yes | Coder 2: no | |
|---|---|---|
| Coder 1: yes | ||
| Coder 1: no |
Self-check
Course positioning, materials and the 16-week schedule
Who is this course for?
This is an introductory course designed for students of the Graduate Institute of National Development and related social science fields, and it requires no advanced technical training; the focus is on using text-as-data and NLP techniques to answer substantive research questions in political science, political communication, legal studies, sociology and similar fields.
- Want to learn model internals, architectures, optimization? This is not that course.
- Goal: use these methods to write your own political science / social science paper.
Where the materials come from
- Lecture framework: Grimmer, Roberts & Stewart (2022), Text as Data: A New Framework for Machine Learning and the Social Sciences (Princeton University Press). This course's two kinds of work simplify the book's discovery → measurement → inference.
- No need to buy the book: the course is paper-first, with 3–4 core materials per week, mostly journal articles and open tutorials; excerpts of required book chapters are provided.
- Also useful: Benoit (2020), Nielbo et al. (2024), Watanabe & Müller's quanteda tutorials, Jurafsky & Martin's SLP (free online).
The semester in three blocks
Introduction to quantitative text analysis; text preparation and a collaborative R/Python workflow.
Tokenisation and DFMs; dictionaries and sentiment analysis; human coding and classification; scaling; topic models.
Readability, similarity and embeddings; NLP and transformers; LLMs; multilingual and multimodal data.
No class: W3 (9/25), W5 (10/9), W11 (11/20), W16 (12/25).
Interactive: the 16-week schedule
The schedule on slide 13 is an image; the weeks, dates, topics and notes here are taken from the schedule in the syllabus (page 10 of the syllabus PDF) and cross-checked against the deadlines on slide 14. Pick a date to see how many days remain until the next deadline.
| Week | Date | Topic | Notes |
|---|---|---|---|
| W1 | 9/11 | Introduction to Quantitative Text Analysis | |
| W2 | 9/18 | Text Preparation in R and Python: Collaborative Workflow | |
| W3 | 9/25 | Mid-Autumn Festival (No Class) | No class |
| W4 | 10/2 | Tokenisation, Document-Feature Matrices, Dictionaries, and Sentiment Analysis | |
| W5 | 10/9 | National Day Observed (No Class) | No class |
| W6 | 10/16 | Human Coding and Document Classification | |
| W7 | 10/23 | Supervised, Unsupervised, and Semi-Supervised Scaling | Individual research abstract due |
| W8 | 10/30 | Topic Models and Their Variants | |
| W9 | 11/6 | Describing and Comparing Texts: Readability, Similarity, and Word Embeddings | |
| W10 | 11/13 | NLP Pipelines and Transformers: Annotation, Classification, and Interpretability | |
| W11 | 11/20 | NTU Sports Day (No Class) | No class |
| W12 | 11/27 | Large Language Models and Multi-Agent Systems | |
| W13 | 12/4 | New Forms of Textual Data: Multilingual and Multimodal Sources | Midterm research design report due |
| W14 | 12/11 | Poster Workshop: Format, Visual Presentation, and 5-Minute Talk | Poster revision clinic |
| W15 | 12/18 | Final Poster Presentations | 5-minute talk; peer feedback |
| W16 | 12/25 | Constitution Day Holiday (No Class) | No class; full paper and extra-credit deadline TBA |
Self-check
Before the course: R, Python, IDE, GitHub, Overleaf
Languages and packages
This course requires prior experience with R and the ability to run some code in a Python environment; beyond that, no advanced technical training is needed.
quanteda, tidytext, text2vec, udpipe, keyATM, spacyr
transformers, flair (transformer models); gensim, spacy (NLP tools); BERTopic (topic models)
Please bring a laptop with a working development environment already installed: most sessions are a short lecture plus coding exercises you run yourself. A detailed setup guide will be sent before the first class.
IDE and writing tools
- IDE: RStudio for R; Positron for Python and cross-language work. You should be able to edit and run code, debug, manage packages and use the built-in terminal.
- R Markdown / Quarto (RStudio) and Jupyter / Quarto notebooks (Positron) help but are not required; W2 covers the actual setup and workflow.
- Never used these IDEs? Complete a basic tutorial before W2, so the semester is spent on methods, not fighting tools.
- Written assignments and posters use LaTeX, done in shared Overleaf projects; Quarto can be used for analysis notebooks. Optional: possibly LM Studio to run LLaMA or Mistral locally, with no API costs.
GitHub for code, Overleaf for written work
- Course materials (slides, code, data, exercises) are all on GitHub. Keep research code in a private repository.
- Written assignments are submitted through shared Overleaf projects, with edit access for the instructor.
- Create a free GitHub account and install GitHub Desktop (point-and-click, no command line needed); RStudio and Positron also have built-in Git tools.
- Apply for the free GitHub Student Developer Pack (GitHub Pro, Copilot, etc.) with your university email.
- W1: how course rules and materials, assignments and communication are organized; W2: GitHub Desktop and IDE setup (clone, commit, sharing code).
Use a separate Overleaf project for each graded assignment, named with your name and the assignment; before the deadline invite the instructor as Editor (can edit); view-only access does not count as a submission. The project must contain the complete, up-to-date source files and compile successfully to PDF. A free account allows one collaborator per project, which is enough.
How much time per week?
This is a 2-credit course. Slide 18's estimate:
| Activity | Hours per week (Slide 18) |
|---|---|
| Before class: read the assigned text-as-data papers, look over this week's slides | 1–2 |
| After class: self-paced coding exercises and research project development | 1–2 |
| Total outside class (typical) | about 3 |
Syllabus §4 (syllabus PDF pp. 4–5) splits out-of-class time into three rows: pre-class reading 1–2, post-class lab 0.5–1, research project 1.5–2, 3–4 hours in total, and notes that more time may be needed near deadlines. Slide 18 has two rows totaling "about 3". Both come from the instructor; these notes do not decide which is authoritative; go by what the instructor says in class.
About the readings: the assigned papers come from political science and the social sciences and use text-as-data methods on real research questions. We read them for the methods and how they are applied, not for their substantive findings.
Interactive: checklist before W2
Every item comes from slides 15–17 and 34. Progress is shown as you tick them.
Self-check
Grading: participation, poster, two papers
Self-paced coding exercises and class participation
- Lab files provide examples and exercises. These exercises are not graded and do not need to be submitted.
- Class Participation — 20%: taking part in discussions of readings, methods and applications; peer feedback; questions and answers on NTU COOL or the course GitHub Issues.
- Written assignments and posters are made in LaTeX and submitted through shared Overleaf projects.
Final poster presentation — 25%
- W15 poster session: first a 5-minute introduction of your poster, then discussion and peer feedback; stay by your poster for the whole session to answer questions; other faculty may be invited.
- Posters follow the PolMeth poster guidelines: clear visual design, emphasizing the research question, data and methods, main findings and implications.
- W14 is a poster preparation workshop (format, visual presentation, 5-minute talk), counted toward class participation.
- Slide 21 shows four PolMeth 2025 posters as examples (Atsusaka, Lee & Lee; Jeon; Xia, Zeng, Liao & Jankin; Li); compare their research questions, evidence and visual organization.
Two papers
Your own research or thesis topic, done individually. The research set up in the midterm report is completed by the final paper.
- Abstract
- Introduction: question and motivation
- Literature review: positioning the research
- Research design: data, methods, strategy
- Preliminary results, or the planned analysis strategy
- Feasibility, expected findings, contribution
At most 10 pages and no more than 2,500 words. Due: December 4 (W13).
Also done individually. It continues the midterm report and adds the full empirical analysis: a stronger design, robust inference, appropriate validation and sensitivity checks, followed by findings, limitations and contribution.
- Main text: at most 4,000 words (excluding references), written as a PSRM Research Note
- Appendix: no word or page limit (robustness, alternative specifications, validation, annotation procedures, prompts, model details, code documentation)
- A reproducible code repository (GitHub or CodeOcean)
- Due: TBA
Where to start?
If you do not have a corpus in mind yet, the syllabus lists these suggested topics:
- Legislative behavior in Taiwan: roll-call votes, speeches, interpellations
- Analysis of legislative speech
- Party manifestos (cross-national or over time)
- Political discourse on social media
- News framing of political issues
- Comparative political rhetoric
- CCP wolf-warrior diplomacy and propaganda
Pick a topic you will still be working on by the W15 poster session.
Interactive: grading weights
The grading table on slide 25 is an image; weights and deadlines are taken from the table in syllabus §8.1 (syllabus PDF p. 40) and match the percentages written on slides 19, 20, 22 and 23. The abstract's 10% appears only in the syllabus text (the text part of slide 25 gives no percentage).
Try the weighting (supplement)
Enter hypothetical scores (0–100) for each component and see how the weighted average is computed. This only demonstrates the weighting; the slides do not say how extra credit enters the final grade, and actual grades follow the instructor's announcements.
| Component | Weight | Deadline | Source |
|---|---|---|---|
| Research Paper Abstract (title + at most 1,000 words) | 10% | 10/23 (W7) | Syllabus §8.1; slide 25 text |
| Midterm Research Design Report | 20% | 12/4 (W13) | Slide 22 |
| Class Participation | 20% | Whole semester | Slide 19 |
| Final Poster Presentation | 25% | 12/18 (W15) in class | Slide 20 |
| Final Research Paper | 25% | TBA | Slide 23 |
| Total | 100% | Syllabus PDF p. 40 |
Key points in the text of slide 25: research abstract (10/23); midterm report → final paper is one and the same original study; poster (W14 workshop, W15 presentation); coding exercises are not graded; graded assignments are submitted via Overleaf; up to 15% extra credit (chapter 08).
Self-check
Bonus: up to 15% extra credit
Two kinds of extra credit
APSA (early January), MPSA (November), EPSS (late December), COMPTEXT (early January), TPSA (summer), JSQPS (winter meeting late October; summer meeting July–August); PolMeth — Annual Meeting (March), Europe PolMeth (mid-to-late November), Asian PolMeth (mid-to-late October).
The slide notes that these months are typical submission deadlines, not conference dates.
Revise & Resubmit or major/minor revision: +10%. Reject or desk reject: +5%.
Eligible journals: SSCI-indexed political science or social science journals.
If you earn both you can claim both, capped at 15%.
- The syllabus words the +10% journal category as “Acceptance, Revise & Resubmit, or Major/Minor Revision”.
- The extra-credit claim deadline is TBA (announced on NTU COOL); submissions still awaiting a decision at the deadline get no provisional credit, and decisions received after the deadline do not count for this semester.
- A conference submission that is not accepted does not qualify for conference credit.
What proof is needed? What makes a submission ineligible?
- Proof: the confirmation email showing the submission, and the decision letter.
- Ineligible: submissions that violate NTU rules on academic integrity, research ethics, student conduct, authorship, copyright, data protection or generative AI use, or that violate the conference's / journal's rules; these may also be handled under NTU's relevant procedures.
- Writing a master's thesis? You are encouraged to develop thesis-related submissions with your advisor. GIND students (Graduate Institute of National Development): co-authored thesis-related submissions must be co-written with full-time GIND faculty. For any co-authored thesis-related submission, you must be both first author and corresponding author to claim extra credit.
Institutional and geographic names: required for every extra-credit submission
- Use the official name National Taiwan University in the manuscript, submission-system data, cover letter, acknowledgments, slides, posters and any public materials.
- Do not alter, omit or downgrade the university's name, and do not use wording that disparages or misrepresents Taiwan's status; when a location is needed, use “Taipei, Taiwan” or “Taipei, Taiwan (R.O.C.)”.
- This does not prohibit evidence-based criticism of Taiwan's politics, institutions or public policy; it governs accurate institutional and geographic description, professional conduct and non-misleading presentation.
- If a conference, journal, submission system or editor asks you to change the wording of NTU or Taiwan, you must consult the instructor first before proceeding; discussing submission plans with the instructor in advance is also strongly recommended.
Interactive: how much extra credit can my submission earn?
This is a tool for organizing the rules, not an official review; the instructor makes the final decision.
Self-check
Generative AI, academic integrity and deadlines
Using generative AI
This course follows NTU's guidelines on generative AI use and research integrity. AI is an assistive tool: it does not replace your judgment, nor your responsibility for what you submit.
- Permitted uses in assignments: conceptualisation; initial literature screening (must be verified by a human); writing and editing assistance; audiovisual and interactive components. The arguments and analysis must be your own.
- Disclose AI use in every submission: research abstract, midterm report, poster, final paper, extra-credit submissions. State which tool and version, what you asked it to do, how you used its output, and how you checked it. No AI used? Write: “No generative AI tools were used in the preparation of this assignment.”
- No statement, no acceptance: an assignment without a statement will not be accepted until a complete statement is added. Misrepresenting AI use, failing to verify AI output, fabricating sources or data through AI, or using AI to bypass learning objectives may be treated as academic misconduct.
Interactive: AI-use disclosure statement generator
The fields correspond to the four items slide 29 requires. The English sentences generated are wording suggested by these notes (supplement), not an official template; check that the content is accurate before submitting.
Academic integrity
- Credit the source of any ideas, words, code, data, figures, tables and research materials that are not your own.
- Plagiarism includes: uncited copying or close paraphrasing, unacknowledged reuse of your own earlier work, unauthorized collaboration, fabricated data or references, and AI-generated content not disclosed as required.
- This course follows NTU policy: suspected misconduct may receive a zero for that component; serious or repeated cases may be referred to the department, college or university.
Deadlines
- Deadlines are deadlines. If you cannot meet one, notify the instructor as early as possible and follow NTU's student leave procedure; in an emergency, email the instructor first.
- Approved leave or extensions do not automatically waive the work; the instructor will arrange reasonable make-up work as appropriate.
- Without approved leave or prior agreement: missed class activities count as absences; late work may receive no credit.
- From the syllabus: written assignments and extra-credit claims are due at 23:59 on the due date (Taiwan time, UTC+8) (syllabus §8.1).
Practice: is this OK?
The scenarios were written for these notes (supplement); the basis for judging is the rules on slides 29–30.
Not answered yet.
Self-check
Respect and support, background survey, before next week
Respect and support
- NTU is committed to a respectful, inclusive and safe learning environment. You have the right to learn free from bullying, harassment, discrimination, sexual harassment, sexual assault, sexual bullying, stalking and other conduct that harms dignity or safety.
- This course reads politically sensitive material. Disagreement is expected, but it must be evidence-based, professional and mutually respectful: argue with the evidence, not with the person.
- If you experience or witness harassment, gender-related misconduct, discrimination, bullying or safety threats, you are encouraged to seek support; reports are handled under NTU's relevant procedures. You are also welcome to contact the instructor directly, who will help you find the right channel.
Where to get help
- Gender Equity Education Committee complaint lines: (02) 3366-9607 / (02) 3366-9608, gender@ntu.edu.tw
- NTU sexual harassment prevention hotline: (02) 3366-5903, leader@ntu.edu.tw
- Or talk to the instructor first.
- Student Counseling Center: (02) 3366-2181, my.ntu.edu.tw/counsel (an intake appointment is needed first; in an emergency you can walk in)
- College-based counseling psychologists (walk-in): csw.ntu.edu.tw
- Campus Security Center (24 hours): (02) 3366-9119
- Danger to life or physical safety: 119 (medical) or 110 (police)
- Free national 24-hour lines: mental health support line 1925; Lifeline 1995
Save the 24-hour numbers in your phone now, before you need them.
Before you leave: background survey
Take five minutes to fill in "Student Background and Course Expectations": your level in R, Python and text analysis; what you want from this course and what research you are working on. The instructor uses the answers to set the pace of the labs and choose examples close to your projects. (The survey QR code is on slide 33.)
Before next week
- Bring a laptop with a working development environment installed; you will use it every week from now on.
- Install RStudio (R) or Positron (Python and cross-language); the setup guide will be sent before class.
- Create a free GitHub account and install GitHub Desktop (no command-line Git needed).
- Recommended: apply for the free GitHub Student Developer Pack with your NTU email.
W2 readings: quanteda tutorials Ch. 1 · Grimmer, Roberts & Stewart (2022) Ch. 4 (excerpt provided) · Quarto “Get Started” documentation · Privacy and AI Assistants on the Posit blog (skim).
Catching up on W1? Benoit (2020) · Grimmer & Stewart (2013) · Nielbo et al. (2024) · Egami et al. (2022).
Note: the syllabus's W1 core readings are Benoit (2020), Grimmer & Stewart (2013) and Baden et al. (2022); Nielbo et al. (2024) and Egami et al. (2022) are listed as supplementary readings. W1/papers/ contains the first three, which chapter 12 introduces.
Self-check
Supplementary lab: turning this week's slides into data (R)
W1 has no classroom or lab R script (the first take-home lab starts in W2). This chapter is a small demo written by the TA: extract the text of week1.pdf with pdftotext -layout, treat one slide page = one document, and use quanteda to walk through the first two steps of slide 4 (corpus → representation). All output comes from actually running the code locally (R 4.5.3 (aarch64-conda-linux-gnu), quanteda 4.5.1, quanteda.textstats 0.97.2, stopwords 2.3, jsonlite 2.0.0); the full log is in tad/labs/W1/run_output.txt. These functions are formally taught in W2 and W4, so it is fine if you do not follow everything yet.
S00–S01: loading packages, reading files
# S00 載入套件
library(quanteda)
library(quanteda.textstats)
library(jsonlite)
cat("quanteda", as.character(packageVersion("quanteda")),
"| quanteda.textstats", as.character(packageVersion("quanteda.textstats")), "\n")> library(quanteda)
> library(quanteda.textstats)
> library(jsonlite)
> cat("quanteda", as.character(packageVersion("quanteda")),
+ "| quanteda.textstats", as.character(packageVersion("quanteda.textstats")), "\n")
quanteda 4.5.1 | quanteda.textstats 0.97.2 # S01 讀檔:一頁投影片=一份文件
raw <- paste(readLines("tad/work/W1/week1.txt", encoding = "UTF-8", warn = FALSE), collapse = "\n")
pages <- strsplit(raw, "\f", fixed = TRUE)[[1]]
pages <- pages[nchar(trimws(pages)) > 0]
pages <- gsub("\\s*\\d+/38\\s*$", "", pages) # 去掉頁尾的「N/38」頁碼
length(pages)
part <- ifelse(seq_along(pages) <= 9, "Part 1: Text as Data",
ifelse(seq_along(pages) <= 34, "Part 2: How This Course Works", "References"))
corp <- corpus(pages, docvars = data.frame(page = seq_along(pages), part = part))
docnames(corp) <- paste0("p", seq_along(pages))
table(docvars(corp, "part"))> raw <- paste(readLines("tad/work/W1/week1.txt", encoding = "UTF-8", warn = FALSE), collapse = "\n")
> pages <- strsplit(raw, "\f", fixed = TRUE)[[1]]
> pages <- pages[nchar(trimws(pages)) > 0]
> pages <- gsub("\\s*\\d+/38\\s*$", "", pages) # 去掉頁尾的「N/38」頁碼
> length(pages)
[1] 38
> part <- ifelse(seq_along(pages) <= 9, "Part 1: Text as Data",
+ ifelse(seq_along(pages) <= 34, "Part 2: How This Course Works", "References"))
> corp <- corpus(pages, docvars = data.frame(page = seq_along(pages), part = part))
> docnames(corp) <- paste0("p", seq_along(pages))
> table(docvars(corp, "part"))
Part 1: Text as Data Part 2: How This Course Works References
9 25 4 38 pages → 38 documents. Following the structure of the slides, they fall into three groups: pages 1–9 Part 1 (page 1 is the cover, page 2 the Part 1 title page), pages 10–34 Part 2, pages 35–38 references. This decision about "what counts as a document" is exactly the researcher's choice at the corpus step of slide 4's pipeline.
S02: four preprocessing settings
# S02 切字:四種前處理設定
toks_A <- tokens(corp) # A 只切字
toks_B <- tokens(corp, remove_punct = TRUE, remove_numbers = TRUE,
remove_symbols = TRUE, remove_url = TRUE) # B 去標點/數字/符號/網址
toks_C <- tokens_remove(tokens_tolower(toks_B), stopwords("en")) # C 再轉小寫、去停用詞
toks_D <- tokens_wordstem(toks_C, language = "en") # D 再取詞幹
cfg <- list(A = toks_A, B = toks_B, C = toks_C, D = toks_D)
data.frame(setting = names(cfg),
tokens = sapply(cfg, function(x) sum(ntoken(x))),
types = sapply(cfg, function(x) nfeat(dfm(x, tolower = FALSE))))> toks_A <- tokens(corp) # A 只切字
> toks_B <- tokens(corp, remove_punct = TRUE, remove_numbers = TRUE,
+ remove_symbols = TRUE, remove_url = TRUE) # B 去標點/數字/符號/網址
> toks_C <- tokens_remove(tokens_tolower(toks_B), stopwords("en")) # C 再轉小寫、去停用詞
> toks_D <- tokens_wordstem(toks_C, language = "en") # D 再取詞幹
> cfg <- list(A = toks_A, B = toks_B, C = toks_C, D = toks_D)
> data.frame(setting = names(cfg),
+ tokens = sapply(cfg, function(x) sum(ntoken(x))),
+ types = sapply(cfg, function(x) nfeat(dfm(x, tolower = FALSE))))
setting tokens types
A A 4499 1422
B B 3123 1328
C C 2215 1061
D D 2215 896S03: document-feature matrix (DFM)
# S03 文件-特徵矩陣(DFM) dfmat <- dfm(toks_C) dfmat topfeatures(dfmat, 20)
> dfmat <- dfm(toks_C)
> dfmat
dfm of 38 documents x 1,061 features (2,215 occurrences, 95.50% sparsity) and 2 docvars.
features
docs text data computational methods social science research can use yen-chieh
p1 2 2 1 1 2 2 2 1 1 1
p2 1 1 0 0 0 1 0 0 0 0
p3 1 0 0 0 1 0 0 1 0 0
p4 3 3 0 0 0 0 0 0 0 0
p5 0 0 0 0 0 0 1 0 0 0
p6 0 0 0 0 0 0 2 0 0 0
[ reached max_ndoc ... 32 more documents, reached max_nfeat ... 1,051 more features ]
> topfeatures(dfmat, 20)
research political course text data science use submission grimmer
24 24 21 19 19 19 16 16 15
stewart poster methods week github social analysis et al
15 15 14 13 13 12 12 12 12
code ai
12 11 38 documents × 1,061 features, with 95.50% of cells equal to 0 (sparsity). Among the most frequent words, research, political, text, data come from Part 1; course, submission, poster, github come from Part 2; grimmer, stewart, et, al come mainly from citations and the reference pages. This is a reminder: whatever "noise" is in your documents (citation formats, footers, URLs) goes straight into your data.
Interactive: slide corpus browser
The tokens of each page under the four settings were actually produced by quanteda and exported from R; the totals below match R's S02 output (4,499 / 3,123 / 2,215 / 2,215 tokens).
Show this page's raw text (extracted with pdftotext)
S04: trimming: on how many pages must a word appear?
# S04 修剪:至少出現在幾頁? sapply(1:5, function(k) nfeat(dfm_trim(dfmat, min_docfreq = k)))
> sapply(1:5, function(k) nfeat(dfm_trim(dfmat, min_docfreq = k))) [1] 1061 332 155 91 60
1,061 → 332 → 155 → 91 → 60: merely requiring "appears on at least 2 pages" removes about 69% of the features. Most words appear on only one page, which is normal for text data (W4 formally covers dfm_trim).
S05: how do Part 1 and Part 2 differ in their words? (keyness)
# S05 兩個 Part 用字的差別(keyness) dfm_part <- dfm_group(dfm_subset(dfmat, part != "References"), groups = part) dfm_part <- dfm_trim(dfm_part, min_termfreq = 1) # 去掉只出現在 References 的字 nfeat(dfm_part) key <- textstat_keyness(dfm_part, target = "Part 1: Text as Data") head(key, 12) tail(key, 12)
> dfm_part <- dfm_group(dfm_subset(dfmat, part != "References"), groups = part)
> dfm_part <- dfm_trim(dfm_part, min_termfreq = 1) # 去掉只出現在 References 的字
> nfeat(dfm_part)
[1] 992
> key <- textstat_keyness(dfm_part, target = "Part 1: Text as Data")
> head(key, 12)
feature chi2 p n_target n_reference
1 factors 12.705822 0.0003645190 5 0
2 new 12.369396 0.0004364289 7 2
3 open-ended 9.415340 0.0021517762 4 0
4 measurement 9.188896 0.0024348771 5 1
5 text 7.441596 0.0063733351 8 6
6 answer 6.761216 0.0093160269 5 2
7 validation 6.761216 0.0093160269 5 2
8 bag 6.175408 0.0129538060 3 0
9 causal 6.175408 0.0129538060 3 0
10 example 6.175408 0.0129538060 3 0
11 graphs 6.175408 0.0129538060 3 0
12 measure 6.175408 0.0129538060 3 0
> tail(key, 12)
feature chi2 p n_target n_reference
981 r -1.272767 0.25924828 0 8
982 student -1.272767 0.25924828 0 8
983 work -1.272767 0.25924828 0 8
984 class -1.839177 0.17504741 0 10
985 ntu -1.839177 0.17504741 0 10
986 required -1.839177 0.17504741 0 10
987 ai -2.127666 0.14466088 0 11
988 github -2.711511 0.09962656 0 13
989 week -2.711511 0.09962656 0 13
990 poster -3.301885 0.06920044 0 15
991 submission -3.598904 0.05781768 0 16
992 course -5.097171 0.02396489 0 21Right (green) = relatively more frequent in Part 1 (research content); left (red) = relatively more frequent in Part 2 (course rules). With only 9 pages against 25 and very small counts, χ² merely describes differences in word use; do not treat it as a serious statistical test.
What this small experiment shows
- Defining a document is the researcher's decision: one page is one document, so the cover, the title page and the reference pages are all "documents" too, and they affect the most frequent words.
- Preprocessing changes the data: for the same slides, the number of features can be 1,422, 1,328, 1,061 or 896, depending on how you process them. Baden et al. (2022, p. 6) criticize precisely that such preprocessing and modeling choices are rarely discussed or justified.
- Crude but useful: from word counts alone, keyness separates "research content" (factors, measurement, validation, causal…) from "course rules" (course, submission, poster, github…). This is a small example of Grimmer & Stewart's first principle, "all models are wrong — but some are useful".
Self-check
Reading guide: Grimmer & Stewart (2013), Benoit (2020), Baden et al. (2022)
How page numbers are cited
- All three are in
W1/papers/and are the syllabus's three core readings for W1. - Grimmer & Stewart (2013): typeset journal PDF; page numbers are journal pages (267–297).
- Benoit (2020): the version in Singapore Management University's institutional repository (marked pp. 1–55 by the repository), not the SAGE print pagination (461–497); these notes write "repo PDF p. N" (including the repository cover page).
- Baden et al. (2022): Open Access journal version (CC BY-NC-ND); page numbers are journal pages (1–18).
Grimmer & Stewart (2013). Text as Data: The Promise and Pitfalls of Automatic Content Analysis Methods for Political Texts. Political Analysis 21(3): 267–297.
Source: W1/papers/Grimmer2013.pdf (Cambridge Core download); doi:10.1093/pan/mps028.
Benoit (2020). Text as Data: An Overview. In Curini & Franzese (eds.), The SAGE Handbook of Research Methods in Political Science and International Relations: 461–497.
Source: W1/papers/Benoit2020.pdf (Singapore Management University, Institutional Knowledge repository version); doi:10.4135/9781526486387.n29.
Baden, Pipal, Schoonvelde & van der Velden (2022). Three Gaps in Computational Text Analysis Methods for Social Sciences: A Research Agenda. Communication Methods and Measures 16(1): 1–18.
Source: W1/papers/Baden2022.pdf (Taylor & Francis, Open Access); doi:10.1080/19312458.2021.2015574. This paper is not on the slides' reference pages but is listed as a W1 core reading in the syllabus.
Interactive: how big is the English advantage?
The numbers are taken verbatim from the main text of Baden et al. (2022), p. 11, describing text-based studies in top journals. "Under 16%" is drawn as 16 and labeled.
Flashcards: four principles and seven stages
Self-check
Common misconceptions and glossary
Common misconceptions (click to see the explanation)
"This course will teach me transformer architectures and optimization."
No. Slide 11: this is a social science course, not a technical one; the goal is to use these methods to write your own paper.
"The newer the method, the bigger the contribution."
Catalinac (2016) used LDA from 2003; the contribution was to political science. In application-type research, the protagonists are research design and identification.
"Whatever the model outputs is the result; no need to validate."
Validation is the one requirement that has never gone away; Grimmer & Stewart's fourth principle is Validate, Validate, Validate.
"I lose points if I don't hand in the lab exercises."
Lab exercises are not graded and do not need to be submitted. But they are your practice ground for the project.
"If I didn't use AI, I don't need to write a declaration."
Every submission needs a declaration; if you used none, you still write “No generative AI tools were used in the preparation of this assignment.” Submissions without a declaration are not accepted.
"Submitting to a conference earns the bonus."
The conference bonus requires acceptance; only journals have the rule that a rejected submission also earns +5%, and it must be an SSCI journal, with a confirmation letter and a decision letter.
"Giving the instructor view access on Overleaf counts as submission."
Syllabus §8.1: the instructor must be invited as Editor (can edit); view-only does not count as a submission.
"An approved absence means I don't have to do the assignment."
An approved absence or extension does not automatically waive the assignment; the instructor will arrange a reasonable make-up.
Glossary (searchable)
Final review, research-idea worksheet, references
Final review quiz
Research-idea worksheet: warming up for the 10/23 research abstract
The research abstract (10%, due 10/23) consists of a title and at most 1,000 words introducing the research you plan to develop in your midterm and final papers (syllabus §8.1). The fields below follow the workflow on slide 4, the two kinds of tasks on slide 6, and the required elements of the midterm presentation on slide 22 (the field layout is a supplement); once filled in, you can export them as Markdown for a draft.
Reminder: attach an AI-use declaration when you submit (Chapter 09).
My progress
Only records starting with w1: are cleared; other weeks' notes are not affected.
References
Works listed on slides 35–38
- Benoit, K. (2020). Text as Data: An Overview. In L. Curini & R. Franzese (eds.), The SAGE Handbook of Research Methods in Political Science and International Relations: 461–497. Sage. doi:10.4135/9781526486387.n29
- Egami, N., Fong, C. J., Grimmer, J., Roberts, M. E. & Stewart, B. M. (2022). How to Make Causal Inferences Using Texts. Science Advances 8(42): eabg2652. doi:10.1126/sciadv.abg2652
- Grimmer, J. (2010). A Bayesian Hierarchical Topic Model for Political Texts: Measuring Expressed Agendas in Senate Press Releases. Political Analysis 18(1): 1–35. doi:10.1093/pan/mpp034
- Grimmer, J. & Stewart, B. M. (2013). Text as Data: The Promise and Pitfalls of Automatic Content Analysis Methods for Political Texts. Political Analysis 21(3): 267–297.
- 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.
- Heseltine, M. & Clemm von Hohenberg, B. (2024). Large Language Models as a Substitute for Human Experts in Annotating Political Text. Research & Politics 11(1). doi:10.1177/20531680241236239
- Jankin, S., Liao, Y.-C. & Tang, L. (2026). Folk Theories of Partisan Conflict. Working paper.
- Jurafsky, D. & Martin, J. H. (2026). Speech and Language Processing (3rd ed., online draft). https://web.stanford.edu/~jurafsky/slp3/
- Laver, M., Benoit, K. & Garry, J. (2003). Extracting Policy Positions from Political Texts Using Words as Data. American Political Science Review 97(2): 311–331. doi:10.1017/s0003055403000698
- Nielbo, K. L. et al. (2024). Quantitative Text Analysis. Nature Reviews Methods Primers 4(1): 25. doi:10.1038/s43586-024-00302-w
- Roberts, M. E., Stewart, B. M., Tingley, D. et al. (2014). Structural Topic Models for Open-Ended Survey Responses. American Journal of Political Science 58(4): 1064–1082. doi:10.1111/ajps.12103
- Rodríguez, P. L., Spirling, A. & Stewart, B. M. (2023). Embedding Regression: Models for Context-Specific Description and Inference. American Political Science Review. doi:10.1017/s0003055422001228
- Slapin, J. B. & Proksch, S.-O. (2008). A Scaling Model for Estimating Time-Series Party Positions from Texts. American Journal of Political Science 52(3): 705–722. doi:10.1111/j.1540-5907.2008.00338.x
- Watanabe, K. & Müller, S. (2023). Quanteda Tutorials. https://tutorials.quanteda.io
Cited on the slides but not on the reference pages
- Catalinac, A. (2016). From Pork to Policy. The Journal of Politics 78(1): 1–18. (slide 7)
Additionally used in these notes
- Baden, C., Pipal, C., Schoonvelde, M. & van der Velden, M. A. C. G. (2022). Three Gaps in Computational Text Analysis Methods for Social Sciences: A Research Agenda. Communication Methods and Measures 16(1): 1–18. doi:10.1080/19312458.2021.2015574 (syllabus W1 core reading)
- NTLDEV 7191 course syllabus (
NTLDEV_7191_1151.pdf): §4, §7.1 schedule, §8.1–8.2. - Software: quanteda, quanteda.textstats, stopwords, jsonlite (Chapter 11 supplementary lab).