Module 05Code & Data Analysis

⏱ 3–4h 📋 technical Python notebook 📌 Module 1; Modules 4 or 7 helpful 🎯 Audited data analysis with verified statistics



§ workbook

Learning Outcomes

# Module 5: Code and Data Analysis with AI Assistants

Estimated time: ~3.5 hours

Type: Technical — Python notebook + markdown workbook

Prerequisites: Module 1 (How LLMs Work); Modules 4 (Text Annotation and Measurement) or 7 (Validation) recommended

What you'll produce: A documented data analysis with at least one independently verified statistic and interpretation, plus an AI use disclosure

1. Why AI for Code and Data?

Social scientists increasingly encounter code in their research even when they are not programmers. A collaborator shares a replication script. A journal requires data deposit. A reviewer asks about a transformation. An RA hands you a .py file and moves on.

Until recently, engaging with code required either learning to program or finding someone who could. AI assistants change the terms of engagement: they can read the code you cannot write, explain what it does, spot problems, and generate new analysis. But they also generate code that looks correct and is not — and you cannot always tell the difference by looking.

This module is not a programming course. It is a course about supervised delegation: how to ask an AI assistant to work with code and data while keeping the research decisions visible and the results verifiable.

The scaffold approach

The core principle of this module is that you never need to write code from a blank editor. Instead, you work from a scaffold — a pre-written script or notebook that provides the structure — and adapt it using AI assistance. The instructor provides the scaffold; you provide the research questions and the verification.

This is the pattern you will use:

  1. Start with a working script or notebook (provided, or one you already have)
  2. Ask the AI to explain what each part does, in plain language
  3. Ask the AI to extend or modify the analysis to answer your question
  4. Verify at least one statistic and one interpretation independently
  5. Document the AI's contribution and your checks
Key insight: The AI is your interpreter and assistant — not your supervisor. You decide what question to ask, which result to trust, and when to override. If you cannot verify a result, you treat it as provisional.

2. AI for Code: What It Can Do

AI assistants can perform several distinct tasks with code. Each has a different risk profile and requires different verification.

Explanation

What it is: You paste a script into a chat window and ask "What does this do?" The AI produces a plain-language explanation of the logic, the variables, and the output.

When to use it: Whenever you inherit code you did not write — a replication script, an RA's analysis, a methods appendix snippet. This is the lowest-risk use: the AI is describing code that already exists. The code is the ground truth; you can check the explanation against it.

What can go wrong: The AI may invent a plausible interpretation of an ambiguous variable name. It may claim the code does something it does not, or miss something it does. Always cross-check: read the explanation alongside the code and confirm at least one claim by tracing a value through the logic yourself.

Debugging

What it is: You give the AI a script that produces an error or the wrong result, describe what you expected, and ask for a fix. The AI identifies the problem and proposes a corrected version.

When to use it: When a script fails with an error message you do not understand, or when the output does not match what the codebook says it should produce.

What can go wrong: The AI may fix the surface error but introduce a new error. It may change the analysis logic in a way you do not notice. It may drop observations, change the unit of analysis, or silently reinterpret a missing-data code. Always run the fixed script and verify the output against a value you computed independently.

Documentation

What it is: You give the AI an uncommented script and ask it to add comments explaining what each section does, or to generate a docstring describing the function's purpose, inputs, and outputs.

When to use it: Before sharing code with a collaborator, depositing replication materials, or submitting to a journal.

What can go wrong: Comments may be factually wrong about what the code does. They may describe what the AI expected the code to do rather than what it actually does. Always read the comments alongside the code and verify at least one claim by tracing it.

Translation

What it is: You give the AI a script in one language (R, Stata, Python) and ask it to produce an equivalent script in another language.

When to use it: When you are more comfortable reading one language than another, or when a collaborator works in a different language.

What can go wrong: Statistical functions with the same name may behave differently across languages (e.g., default standard error calculations, missing-value handling, factor variable treatment). The translation may look correct but produce different numbers. Always run both versions on the same data and compare outputs.

Generation (with caution)

What it is: You describe an analysis you want ("load this CSV, compute means by group, make a bar chart") and the AI writes the script.

When to use it: For exploratory work on non-sensitive data, when you can verify every output. In this course, we prefer the scaffold approach — modifying existing working code — over generating from scratch. Generation is riskier because there is no baseline to compare against.

What can go wrong: Everything listed above, plus: the AI may use packages that do not exist, call functions with wrong arguments, or write code that runs without error but produces the wrong result. The fluency of the code is not a guarantee of its correctness.


3. Data Exploration with AI

The most common research use of AI-assisted coding is data exploration: loading a dataset, producing summaries, checking for problems, creating plots, and running simple models. Here is a workflow you can use, structured around verification:

Step 1: Load and inspect

Ask the AI to load your dataset and display the first few rows, the column names, the data types, and the dimensions (rows × columns). Verify one of these values yourself: count the columns by hand, or confirm that the number of rows matches what you expect from your data source.

Step 2: Summary statistics

Ask the AI to produce summary statistics: means, medians, standard deviations, minimums, maximums, and counts of missing values for each variable. Pick one statistic for one variable and compute it yourself — with a calculator, in a spreadsheet, or by counting cases — before trusting any other number the AI reports.

Step 3: Data quality checks

Ask the AI to check for:

  • Missing values (how many, in which variables)
  • Impossible values (e.g., age = 250, a Likert scale with a value of 99)
  • Duplicate rows
  • Inconsistent categories (e.g., "male", "Male", "m", "M" all appearing in the same column)

For each issue the AI flags, confirm at least one example manually: find the row it identified and check that the problem is real.

Step 4: Transformations

Ask the AI to create new variables: recode a categorical variable, compute a scale mean, create a binary indicator. Before running the transformation, predict what the result should be for one specific case. After the AI produces the transformation, check whether your prediction matches.

Step 5: Visualisation

Ask the AI to produce a plot: a histogram, a bar chart, a scatterplot. Read the plot: does the pattern make sense given what you know about the data? Are the axis labels correct? Are the units right? Pick one data point on the plot and confirm it against the raw data.

Step 6: Simple models

Ask the AI to run a regression, a t-test, or a correlation. Before looking at the result, write down what direction you expect the relationship to have and why. After seeing the result: did the AI use the right variables? The right unit of analysis? The right standard errors? Verify one coefficient by running a simpler calculation: if the model says the mean of group A is 4.3, compute that mean yourself.


4. What to Verify Independently

You cannot verify everything — that would defeat the purpose of using AI. But you must verify something, or you are accepting output on faith. The validation menu from Module 4 (modules/shared/validation_menu.md) provides seven checks you can choose from — source verification, human comparison, repeated runs, prompt variation, boundary cases, sensitivity to model or settings, and downstream consequence. For code and data analysis, checks 2 (human comparison — compute one value yourself), 5 (boundary cases — test on a known-answer case), and 7 (downstream consequence — does the error change your interpretation?) are the most directly applicable.

Here is a minimum verification checklist for any AI-assisted data analysis:

| What to verify | How |

|---|---|

| One descriptive statistic | Compute it by hand or in a spreadsheet |

| One count | Count rows, cases, or groups yourself |

| One plot point | Find the corresponding value in the raw data |

| One transformation | Predict the result for one case before running, then check |

| The unit of analysis | Confirm that each row is what you think it is (respondent? country-year? article?) |

| Missing-data handling | Check what happened to cases with missing values — were they dropped, imputed, or silently included? |

| One interpretation | Ask: "Does the number actually support this claim?" Read the output yourself |

| Edge cases | Test the code on a case you constructed with a known answer |

If you verify nothing, you know nothing. If you verify one thing, you have a toehold. If you verify three things across different aspects of the analysis (a count, a statistic, and an interpretation), you have a basis for evaluating the rest.


5. Common Failure Modes

AI-assisted data analysis fails in predictable ways. Knowing what to watch for is half the defence.

Hallucinated functions

The AI calls a function that does not exist — pandas.read_csv_smart() or ggplot.geom_smooth_robust(). This is usually easy to spot because the code produces an error. Less visible: the AI calls a real function with wrong arguments that have plausible defaults, and the code runs silently with unexpected behaviour.

Plausible wrong analyses

The AI runs the analysis you asked for, but on the wrong subset of data, with the wrong denominator, or with the wrong variable coding. The output looks correct — coefficients, p-values, R-squared — but every number is wrong. You cannot detect this by looking at the output; you must trace one value back to the raw data.

Off-by-one errors

The AI selects rows 1–10 when you wanted the first ten rows but the data has a header row, and row 1 is the header. Or it splits data at index 100 but the index is zero-based. These are classic programming errors that AI inherits from its training data.

Dropped observations

The AI silently drops rows with missing values and reports results on a smaller N than you expect. Or it fills missing values with zeros or means without telling you. Always compare the N in the model output to the N you expect from your data description.

Silent recoding

The AI treats "99" as a number rather than a missing-value code, or converts a categorical variable to numbers in a different order than you expected. The analysis runs; the results are wrong. This is why the codebook matters: the AI cannot infer data semantics from numbers alone.

The self-assessment gap

Becker et al. (2025) found that developers using AI felt more productive, but objective measures showed smaller and less consistent gains. The same gap appears in data analysis: the AI makes you feel faster and more confident, but that feeling is not evidence that the results are correct. Confidence and correctness are separate dimensions.


6. The Four Questions Applied to Code and Data Tasks

Before every AI-assisted code or data task, answer the four questions. (Full reference: modules/shared/four_questions.md — keep it open alongside this workbook.) Here they are applied to a typical scenario: asking an AI to explore a survey dataset.

1. What is being delegated?

Task: The AI loads the data, computes descriptive statistics, produces plots, and runs a regression.

Decisions being delegated: Which statistics to report (the AI selects from available variables). How to handle missing values (the AI chooses a default strategy). Which regression specification to run (the AI infers from the prompt). How to interpret the coefficient (the AI produces a narrative interpretation).

Notice that "task" and "decision" blur together in data analysis. Every computational step embeds a methodological choice. Separating them is the first step toward deciding what you need to verify.

2. What would make the result believable?

  • I compute one mean by hand and match it to the AI's output.
  • I trace one case through a transformation and confirm the result.
  • I read the regression output myself and confirm the coefficient sign matches my expectation.
  • I check that the N in the model matches the N of complete cases I counted.
  • I run the same analysis on a different AI system (or the same system twice) and compare.

3. What could be lost or flattened?

  • Cases with missing values might be silently dropped, changing my effective sample.
  • Outliers might be included in means without my knowledge, skewing the results.
  • The AI might choose a default reference category for a categorical variable that obscures the comparison I care about.
  • My own judgment about which variables are substantively important is replaced by the AI's statistically-driven selection.
  • The data provenance — where it came from, how it was collected, what the codes mean — is invisible to the AI.

4. What must remain visible or human?

  • The codebook must be written by me, not the AI, because the AI cannot know what the data mean.
  • The decision about which cases to include or exclude must be documented and justified by me.
  • The interpretation of what a coefficient means for my research question is mine.
  • The disclosure must record what the AI did, what I checked, and what I decided.
  • I must be able to say: "Here is the exact code the AI ran, here is the output, here is what I verified, and here is what I would need to see to change my interpretation."

7. Demonstration: Debug a Broken Analysis

Let's walk through a concrete example. Below is a short Python script that computes the mean of a survey variable by region. The script runs without error — but it contains at least two problems.

```python

SURVEY_ROWS = [

{"respondent_id": 1, "region": "urban", "trust_eu": 6},

{"respondent_id": 2, "region": "urban", "trust_eu": 7},

{"respondent_id": 3, "region": "urban", "trust_eu": 99},

{"respondent_id": 4, "region": "rural", "trust_eu": 4},

{"respondent_id": 5, "region": "rural", "trust_eu": 5},

{"respondent_id": 6, "region": "rural", "trust_eu": 3},

{"respondent_id": 7, "region": "rural", "trust_eu": None},

{"respondent_id": 8, "region": "urban", "trust_eu": 5},

]

def mean_trust_by_region(rows):

totals = {}

counts = {}

for row in rows:

if row["trust_eu"] is None:

continue

region = row["region"]

totals[region] = totals.get(region, 0) + row["trust_eu"]

counts[region] = counts.get(region, 0) + 1

return {region: totals[region] / counts[region] for region in totals}

# What does this actually compute?

```

Without reading the codebook, can you identify what is wrong? The script runs. It produces numbers. But:

  1. Problem 1: Respondent 3 has trust_eu = 99. In many survey datasets, 99 is a missing-value code, not a genuine trust score. Including it in the mean inflates the urban average. The AI cannot know this from the code alone — it needs the codebook.
  1. Problem 2: Respondent 7 has trust_eu = None and is excluded. But the script does not report how many cases were excluded, so the user does not know the denominator changed.
  1. Problem 3 (less visible): The output reports only the mean, not the count. A mean of 5.0 from 100 cases means something different from a mean of 5.0 from 3 cases. Without the N, the statistic is uninterpretable.

Now, with the codebook in hand (see materials/day1_codebooks.md), we learn:

  • trust_eu: 0 = no trust, 10 = complete trust
  • 99 = "no answer" (missing)
  • None = system missing

The fix is to exclude 99 as well as None, and to report the count alongside the mean. An AI can suggest these changes — but it can only do so after you provide the codebook. The AI cannot infer data semantics from numbers.

Verify one statistic

Urban respondents (excluding 99 and None): 6, 7, 5 → mean = (6 + 7 + 5) / 3 = 6.0. Compute this yourself. Do not trust the printed output until you have confirmed one value independently.

Document the finding

The AI was given a script that computed mean trust scores by region. It identified that the value 99 should be treated as missing (per the codebook), proposed excluding it, and recommended reporting the count alongside each mean. The researcher independently computed the urban mean as 6.0 and confirmed the AI's output matched. The AI did not identify the missing-count issue without prompting; the researcher added the requirement to report dropped cases.

8. Exercise Instructions

The exercises for this module are in exercises.md. Work through them in order:

  • Exercise 5.1: Ask AI to explain a short script; verify the explanation
  • Exercise 5.2: Ask AI to add comments; check for errors in the comments
  • Exercise 5.3: Give AI a dataset and ask for summary statistics; independently verify three
  • Exercise 5.4: Ask AI to debug a script with an intentional error; identify what was fixed and what was missed
  • Exercise 5.5: Apply the four questions to a code/data workflow

Each exercise includes a collapsible answer key. Work through the exercise before reading the key. The point is to form a judgment before seeing a prepared answer.

The demo notebook

The notebooks/ directory contains analysis_demo.ipynb, a Python notebook you can open in Google Colab (free, no installation). It demonstrates the full scaffold workflow: load a small CSV, request summary statistics, create a plot, run a regression, and verify each step. Open it, run the cells, and use it as a template for your own data.


9. Summary

  • AI can explain, debug, document, translate, and generate code — but every use requires independent verification.
  • The scaffold approach lets you work with code without writing from scratch: start with working code, ask the AI to modify it, and verify the output.
  • For data exploration, verify one statistic, one count, one plot point, and one transformation before trusting the rest.
  • Common failure modes — hallucinated functions, plausible wrong analyses, off-by-one errors, dropped observations, silent recoding — are predictable. Check for them explicitly.
  • The AI cannot infer what your data mean. The codebook, the research question, and the interpretive judgments are yours.
  • Apply the four questions before and after every AI-assisted code or data task.
  • Every output you use in your research must carry a disclosure naming the tool, the task, the verification performed, and the decisions the researcher retained.

10. Connection to Module 6

Module 6 (Agents) extends the code-and-data workflow in one direction: automation. Where Module 5 uses AI as an assistant — you ask, AI responds, you verify — Module 6 introduces the agent loop: the AI decides what to do next, executes it, and reports back, potentially without asking at every step. The verification discipline you build in this module is the foundation for that delegation. An agent running unattended is only as trustworthy as the checks you built into its workflow. If you have not learned to verify a single statistic independently, you cannot supervise an agent that produces a hundred.

Module 7 (Validation, Reproducibility, and Research Integrity) extends the workflow in the other direction: evidence standards. It asks how much verification is enough for a publication claim, what a reviewer can inspect, and what happens to your results when the model is updated or deprecated.


Module 5 of 8 · AI as a Research Tool: Workflow Design for the Social Sciences · University of Zurich


§ exercises

# Module 5: Exercises

Each exercise includes an answer key. Work through the exercise before reading the key. The point is to form a judgment before seeing a prepared answer — this is the "human first" principle from Module 1, applied to code and data.

You will need access to any AI chat interface (ChatGPT, Claude, Gemini, or equivalent — a free account is sufficient). No programming experience, API keys, or installed software is required. Exercises 5.3–5.4 use the supplied scripts and data, which can be pasted directly into a chat window. Exercise 5.5 can be done with the demo notebook or with your own data.


Exercise 5.1: Ask AI to Explain a Script

Goal: Practice asking an AI to explain code, and verify the explanation against the code.

Below is a short Python script. Paste it into an AI chat window with the instruction: "Please explain what this script does, line by line, in plain language. Identify the unit of analysis, what is being computed, and any assumptions the code makes that are not explicit in the code itself."

```python

SURVEY_ROWS = [

{"id": 1, "region": "north", "turnout": 1},

{"id": 2, "region": "north", "turnout": 0},

{"id": 3, "region": "north", "turnout": 2},

{"id": 4, "region": "north", "turnout": 1},

{"id": 5, "region": "south", "turnout": 1},

{"id": 6, "region": "south", "turnout": 0},

{"id": 7, "region": "south", "turnout": 0},

{"id": 8, "region": "south", "turnout": 2},

]

def turnout_rate_by_region(rows):

totals = {}

counts = {}

for row in rows:

region = row["region"]

totals[region] = totals.get(region, 0) + row["turnout"]

counts[region] = counts.get(region, 0) + 1

return {region: totals[region] / counts[region] for region in totals}

```

Write the AI's explanation here (or paste the key parts):

```

```

Now, answer these questions yourself, using the code, not the AI's explanation:

  1. What is each row? _________________________________
  2. What does the function compute? _________________________________
  3. What happens to respondent 3 (turnout = 2)? _________________________________
  4. Does the AI's explanation mention this? _________________________________
  5. What assumption is the code making about the turnout values? _________________________________

Answer Key (click to expand)

What the AI should identify:

The script groups rows by region and computes the mean of turnout for each region. It does this by accumulating a totals dictionary (sum of turnout values per region) and a counts dictionary (number of rows per region), then dividing.

What the AI cannot know from the code alone:

  1. What the turnout values mean. The code treats 0, 1, and 2 as numbers on a continuous scale. But turnout is typically coded as 0 = did not vote, 1 = voted, and 2 = not eligible. Computing a mean of these values is nonsensical — what is a "mean turnout" of 0.75 when the values are categorical? The AI cannot detect this from the code. You need the codebook.
  1. That respondent 3 (turnout = 2) should be excluded. The code includes all rows. If 2 means "not eligible," including it produces the wrong result because the denominator includes ineligible people. The code should compute the proportion of eligible respondents who voted, excluding those coded 2. The AI may or may not flag the value 2 as suspicious — but without the codebook, it cannot know.
  1. The unit of analysis. The code assumes one row = one respondent, but a script cannot tell you whether this is a person-level or aggregate dataset from the variable names alone.

Good AI responses will:

  • Distinguish what the code does (computes means) from what the variables mean (unknown without a codebook)
  • Note that the function does not report the count alongside the mean
  • Flag that value 2 in a variable called "turnout" is unusual and ask for a codebook

Weaker AI responses will:

  • Confidently state that the code computes "turnout rates" without noting the coding issue
  • Treat turnout as continuous without questioning it
  • Not mention that the denominator includes all rows regardless of eligibility

Your verification:

You should check at least one claim from the AI's explanation against the code. For example: "The AI says the code computes the mean — let me compute the north mean by hand: (1+0+2+1)/4 = 1.0. Yes, that is a mean."


Exercise 5.2: Ask AI to Add Comments — Then Check for Errors

Goal: Experience the gap between what the AI thinks the code does and what it actually does.

Below is an uncommented script. Paste it into an AI chat window with the instruction: "Add a comment to every line of this script explaining what it does. Use plain language. Do not change the code — only add comments."

```python

SURVEY_ROWS = [

{"respondent_id": 1, "region": "urban", "trust_eu": 6},

{"respondent_id": 2, "region": "urban", "trust_eu": 7},

{"respondent_id": 3, "region": "urban", "trust_eu": 99},

{"respondent_id": 4, "region": "rural", "trust_eu": 4},

{"respondent_id": 5, "region": "rural", "trust_eu": 5},

{"respondent_id": 6, "region": "rural", "trust_eu": 3},

{"respondent_id": 7, "region": "rural", "trust_eu": None},

{"respondent_id": 8, "region": "urban", "trust_eu": 5},

]

def mean_trust_by_region(rows):

totals = {}

counts = {}

for row in rows:

if row["trust_eu"] is None:

continue

region = row["region"]

totals[region] = totals.get(region, 0) + row["trust_eu"]

counts[region] = counts.get(region, 0) + 1

return {region: totals[region] / counts[region] for region in totals}

```

Paste the AI's commented version here (or write the key comments it added):

```

```

Now answer these questions:

  1. Did the AI identify that 99 is included in the mean? _________________________________
  2. Did the AI note that the function only skips None, not other missing-value codes? _________________________________
  3. Did the AI comment on what "trust_eu" means, or did it only describe the operation? _________________________________
  4. Pick one comment from the AI's output. Trace the corresponding code. Does the comment accurately describe what the code does? _________________________________
  5. Did the AI add any comment that is wrong or misleading? If so, which one? _________________________________

Answer Key (click to expand)

What a good AI response looks like:

The AI should add comments like:

  • # Loop through each survey respondent row (correct — states the unit of analysis explicitly)
  • # Skip rows where trust_eu is missing (None) (correct — but incomplete)
  • # Add the trust_eu value to the region's running total (correct)
  • # Increment the count of valid responses for this region (correct)
  • # Calculate the mean trust score for each region (correct)

What a weak AI response looks like:

The AI might add comments like:

  • # Calculate the average trust in the EU by region (makes a substantive claim about what "trust_eu" means — the code cannot tell you it is "trust in the EU" versus "trust in national government")
  • # The value 99 is an outlier and will skew the mean (the AI guesses 99 is an outlier; with the codebook we know it is a missing-value code — a different problem)

Common errors in AI-generated comments:

  1. Silent assumption about variable meaning: The AI may write "trust in the EU" based on the variable name. But trust_eu could mean "trust in European Union institutions," "trust that the EU will act," or "trust measured on a scale from the EU Social Survey." The variable name is suggestive, not definitive. The codebook is the authority.
  1. Incomplete missing-data handling: The AI will correctly note that None is skipped, but most AIs will not flag that 99 is included. A good AI response will add a comment like # NOTE: value 99 is included in the mean — check whether this is a missing-value code.
  1. Wrong interpretation of the denominator: The AI may say the function computes "mean trust among all respondents" when it actually computes "mean trust among respondents with non-None trust_eu." The denominator changed, and the AI's comment may not reflect this.
  1. No mention of what is NOT reported: The function does not report the count of valid responses or the number excluded. Most AIs will not flag this as a problem unless prompted.

Your verification check:

Pick one comment and trace it. Example: "The AI's comment says 'Skip rows where trust_eu is missing (None).' I see the if row["trust_eu"] is None: continue line. That is correct — it skips None. But it does not skip 99. The comment is accurate about what the code does, but incomplete about what it should do."


Exercise 5.3: Ask AI for Summary Statistics — Then Verify Three

Goal: Practice the core verification workflow: ask, compute, compare.

Below is a small dataset. Paste it into an AI chat window with the instruction: "This is survey data. Load it and produce summary statistics for all numeric variables: mean, median, minimum, maximum, standard deviation, and count of missing values. Use Python (or R, if you prefer). Then create one histogram and one bar chart of your choice. Report the output."

```

id,age,income,education,trust_gov

1,34,45000,3,5

2,28,32000,2,7

3,45,67000,5,4

4,99,41000,4,3

5,31,,2,6

6,42,52000,3,99

7,29,38000,1,5

8,37,61000,4,4

9,44,49000,5,2

10,33,44000,3,5

```

Paste the AI's summary statistics here:

```

```

Now, independently verify three of the AI's statistics:

Verification 1: A mean

  • Variable: _______________
  • Your calculation (show your work): _______________
  • AI's value: _______________
  • Match? _______________

Verification 2: A count

  • Variable: _______________
  • Your count (how many valid cases?): _______________
  • AI's count: _______________
  • Match? _______________

Verification 3: A data quality issue

  • Did the AI flag age = 99 as suspicious? _______________
  • Did the AI flag trust_gov = 99 as suspicious? _______________
  • Did the AI handle the missing income value (row 5)? _______________
  • What did the AI do that you would change? _______________

Answer Key (click to expand)

Expected summary statistics (correct values):

age (10 values, all present):

  • Mean: (34+28+45+99+31+42+29+37+44+33) / 10 = 422/10 = 42.2
  • Median: sort → 28, 29, 31, 33, 34, 37, 42, 44, 45, 99 → median of even set = (34+37)/2 = 35.5
  • Min: 28 · Max: 99 · SD: depends on whether 99 is treated as valid

income (9 values, 1 missing — row 5):

  • Mean of valid: (45000+32000+67000+41000+52000+38000+61000+49000+44000) / 9 = 429000/9 = 47666.67
  • Missing: 1 (row 5, id=5)

education (10 values, all present):

  • Mean: (3+2+5+4+2+3+1+4+5+3) / 10 = 32/10 = 3.2
  • Missing: 0

trust_gov (10 values, all present):

  • Mean: (5+7+4+3+6+99+5+4+2+5) / 10 = 140/10 = 14.0 ← THIS IS WRONG. 99 is a missing-value code.
  • Correct mean (excluding 99): (5+7+4+3+6+5+4+2+5) / 9 = 41/9 = 4.56

What a good AI response does:

  1. Flags age = 99 as a likely data entry error or missing-value code
  2. Flags trust_gov = 99 as a likely missing-value code (a 0–10 trust scale cannot have 99)
  3. Reports missing income count
  4. Reports statistics both with and without the suspected-missing 99 values, and lets the user decide

What a weak AI response does:

  1. Reports means including 99 as valid values without comment
  2. Does not notice that trust_gov = 99 is impossible on a 0–10 scale
  3. Computes all statistics without noting any data quality concerns

Common AI failure patterns in this exercise:

  • The AI reports summary statistics without inspecting the data for impossible values
  • The AI excludes the missing income row but does not report how many cases were dropped
  • The AI treats age = 99 as a genuine age without questioning it (a 99-year-old respondent is possible but uncommon; the AI should flag it)
  • The AI's histogram may include the 99 values, distorting the visual scale

Your verification:

  • If you computed the age mean as 42.2 and the AI reported something different, the AI may have excluded 99 (treating it as missing) or made an arithmetic error. Either way, you have detected the discrepancy.
  • If you counted 9 valid income values and the AI reported 9, that matches. If it reported 10, it may have filled the missing value with 0 without telling you.
  • The trust_gov mean including 99 is 14.0 — clearly wrong for a 0–10 scale. A competent AI should flag this, but some will not.


Exercise 5.4: Ask AI to Debug a Script — What Did It Miss?

Goal: Experience AI debugging and learn to evaluate what the AI fixed versus what it overlooked.

Below is a script with an intentional error. Paste it into an AI chat window with the instruction: "This script is supposed to compute the proportion of eligible respondents who voted, separately by region, using the codebook below. It contains at least one error. Find and fix the error(s). Show the corrected script."

The script:

```python

SURVEY_ROWS = [

{"id": 1, "region": "north", "turnout": 1},

{"id": 2, "region": "north", "turnout": 0},

{"id": 3, "region": "north", "turnout": 2},

{"id": 4, "region": "north", "turnout": 1},

{"id": 5, "region": "south", "turnout": 1},

{"id": 6, "region": "south", "turnout": 0},

{"id": 7, "region": "south", "turnout": 0},

{"id": 8, "region": "south", "turnout": 2},

]

def turnout_rate_by_region(rows):

totals = {}

counts = {}

for row in rows:

region = row["region"]

totals[region] = totals.get(region, 0) + row["turnout"]

counts[region] = counts.get(region, 0) + 1

return {region: totals[region] / counts[region] for region in totals}

def main():

results = turnout_rate_by_region(SURVEY_ROWS)

for region, rate in sorted(results.items()):

print(f"{region}: turnout rate = {rate:.3f}")

```

The codebook:

  • turnout: 0 = eligible, did not vote; 1 = eligible, voted; 2 = not eligible
  • Analysis population: eligible respondents only (turnout = 0 or 1)
  • Target quantity: proportion of eligible respondents who voted, by region

Paste the AI's corrected script here:

```

```

Now answer:

  1. What error(s) did the AI find and fix? _________________________________
  2. What did the AI miss? (Hint: does the corrected script report what a reviewer would need to know?) _________________________________
  3. Compute the north turnout rate by hand using the codebook. Your calculation: _________________________________ · AI's output: _________________________________ · Match? _________________________________
  4. If you ran the AI's corrected script, would the denominator be correct? Verify by checking which rows are included. _________________________________
  5. Did the AI change anything it should not have changed? (e.g., variable names, output format, logic unrelated to the fix) _________________________________

Answer Key (click to expand)

The error:

The script includes all eight rows in the calculation, but the codebook specifies that the analysis population is eligible respondents only (turnout = 0 or 1). Respondents coded 2 (not eligible) should be excluded from the analysis entirely.

Without the fix:

  • North: (1+0+2+1)/4 = 1.0 → "turnout rate of 100%" — wrong because respondent 3 (not eligible) is in the denominator
  • South: (1+0+0+2)/4 = 0.75 → wrong for the same reason

With the fix (excluding turnout = 2):

  • North: (1+0+1)/3 = 0.667 → 66.7% of eligible respondents voted
  • South: (1+0+0)/3 = 0.333 → 33.3% of eligible respondents voted

What the AI should fix:

The AI should add a filter: if row["turnout"] == 2: continue (or equivalent) before the accumulation. The corrected script should exclude ineligible respondents from both the numerator (totals) and denominator (counts).

What many AIs miss:

  1. Reporting the excluded count. The script should report how many respondents were excluded as ineligible. A reviewer needs to know: "North: 3 eligible (1 excluded), South: 3 eligible (1 excluded)." Without this, the denominator is invisible.
  1. Documenting the analysis population in the function. The docstring or comments should state: "Computes turnout among eligible respondents. Excludes turnout = 2 (not eligible)."
  1. Reporting anything beyond the proportion. The function returns only the ratio. A responsible analysis also reports the N (number of eligible respondents) and the number excluded.
  1. Handling the edge case of zero eligible respondents. What happens if a region has only ineligible respondents? The script would divide by zero. A good fix includes a check for this.

Hand verification — North:

Eligible respondents (turnout = 0 or 1):

  • id=1: turnout=1 (voted)
  • id=2: turnout=0 (did not vote)
  • id=4: turnout=1 (voted)

Voted = 2, Eligible = 3 → 2/3 = 0.667

Compare to the AI's output. If the AI reports 1.0, it did not fix the error. If it reports 0.667, the fix is correct.

What the AI might change unnecessarily:

Some AIs will rewrite the entire script — adding imports, error handling, type hints, or changing the data structure. A good fix is minimal: add the filter line and maybe improve the output message. If the AI rewrote the script from scratch, compare the new logic to the old logic carefully — the AI may have introduced new errors in the rewrite.

This exercise is drawn from the Day 1 code evaluation materials (day1_code_team.py and day1_codebooks.md). The original exercise asks students to evaluate the script before seeing the codebook, then again after. If you want additional practice, repeat Exercise 5.4 without the codebook and compare the AI's answers.


Exercise 5.5: Apply the Four Questions to a Code/Data Workflow

Goal: Complete the four-question framework on a real or realistic code-and-data task.

Choose one of the following, or use your own:

  • Option A: The demo notebook (notebooks/analysis_demo.ipynb) — load a CSV, compute summaries, create a plot, run a regression
  • Option B: The script from Exercise 5.3 — load survey data, produce summary statistics and plots
  • Option C: A short script or dataset you have from your own research (do not upload sensitive data to an external AI service)

Before running anything, answer the four questions:

1. What is being delegated?

Task (what specific action is the AI performing?):

_________________________________

Decision (what methodological judgment is being handed over?):

_________________________________

2. What would make the result believable?

Name at least three pieces of evidence outside the model output:

  1. _________________________________
  2. _________________________________
  3. _________________________________

3. What could be lost or flattened?

Identify at least two risks:

  1. _________________________________
  2. _________________________________

4. What must remain visible or human?

Name at least two things that cannot disappear into the interface:

  1. _________________________________
  2. _________________________________

Now run the task (or trace through the notebook). After running, answer the four questions again:

After running — What was different?

  1. What did the AI do that you did not expect? _________________________________
  2. What did you need to verify that you had not planned to? _________________________________
  3. What, if anything, would you change about your prompt or instructions if you ran it again? _________________________________

Disclosure

Write a disclosure statement for this task using the course template (modules/shared/disclosure_template.md):

```

AI Use Disclosure

Tool(s): _________________________________

Purpose: _________________________________

Location: _________________________________

Verification: _________________________________

Human decisions: _________________________________

The author takes full responsibility for all content in this document.

No AI tool was used as a source of fact, and no AI-generated reference

was included without personal verification.

```


Answer Key (click to expand)

There is no single correct answer — the four questions are a lens, not a checklist with right answers. This answer key provides an example for Option A (the demo notebook: load CSV, summaries, plot, regression) and flags what a strong response contains.

Before running — example answers

1. What is being delegated?

  • Task: Loading the CSV, computing descriptive statistics (means, SDs, correlations), generating a scatterplot, and running an OLS regression.
  • Decision: How to handle missing values (the AI chooses silently). Which variables to include in the regression (the AI selects from the prompt). Whether to use robust standard errors (the AI chooses OLS defaults). The interpretation of the coefficient direction and magnitude.

2. What would make the result believable?

  1. I compute one mean by hand from the raw data and confirm it matches the AI's output.
  2. I check that the N in the regression matches the number of complete cases I count in the dataset.
  3. I verify one data point on the scatterplot against the raw CSV data.
  4. I run the same instructions on a different AI system (or same system, second time) and compare the regression coefficients.

3. What could be lost or flattened?

  1. Cases with missing values could be silently dropped, changing which respondents are represented.
  2. Outliers could drive the regression results without being flagged — the AI might not check for influential observations.

4. What must remain visible or human?

  1. The interpretation of whether the coefficient is substantively meaningful (not just statistically significant) is my judgment.
  2. The disclosure must record what the AI did, what I verified, and what I decided.

After running — signs of a thorough response

  • A specific discrepancy found: "The AI's histogram included a value of 99 in age without flagging it. I had to ask explicitly for a check of impossible values."
  • A verification performed: "I computed the mean age by hand: 36.9. The AI reported 36.9. Match confirmed."
  • A prompt improvement identified: "I should have specified 'use robust standard errors' in the prompt, because the AI used OLS defaults and I don't know whether the assumptions hold."
  • A judgment retained: "The AI said the relationship was 'significant and positive.' I read the coefficient and p-value myself and concluded the effect size is small (0.12) even though the p-value is < 0.05."

Disclosure example

```

AI Use Disclosure

Tool(s): Claude 4 (Anthropic), via claude.ai, [date]

Purpose: To load a CSV of survey data, compute descriptive statistics,

generate a scatterplot of age vs. trust, and run an OLS regression

Location: The analysis in this exercise document; the plot and

regression output in the accompanying notebook

Verification: The mean age was computed by hand and matched the AI's

output (36.9). The regression N (200) was confirmed against the

row count of complete cases. One data point on the scatterplot

was traced to its source row and confirmed.

Human decisions: The choice of variables to analyse, the

interpretation of the regression coefficient direction and

magnitude, and the decision to flag age=99 as a likely error

are the author's. The AI was not asked to select variables or

interpret the substantive meaning of the results.

```

What a weak response looks like:

  • "The AI did a good job, the results look fine" (no verification performed)
  • "I trust the AI" (the point of the exercise is to not trust without checking)
  • "The AI's output was correct" (how do you know?)
  • Disclosure: "Used ChatGPT for analysis" (too vague — what model? what task? what verification?)


Module 5 Exercises · AI as a Research Tool


§ readings

Nothing on this list is required before starting the module. Read in any order — before, during, or after. Each entry explains why it is useful and what to take from it.

---

Core Readings

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. Chapters 1–4, 6, and 18.

Why read it: This is the standard social-science reference for computational text analysis, and Chapters 3–4 and 6 are directly relevant to data analysis with AI. Chapter 3 covers the discovery–measurement–inference framework that structures any empirical project. Chapter 4 treats selection, representation, and the decisions that shape a dataset before analysis begins. Chapter 6 covers validation: how do you know your measurement is working? Chapter 18 (conclusion) returns to the core argument: computational methods are social-science methods, and the same standards of validity, reliability, and transparency apply. What to take: The book's framework predates LLMs but applies directly to them. The questions Grimmer, Roberts, and Stewart ask about any computational method — what is being measured? how is it validated? what are the consequential errors? — are the same questions this module asks about AI-assisted code and data analysis. The technology changed; the methodological demands did not. ---

Wickham, H., & Grolemund, G. (2023). R for Data Science, 2nd ed. O'Reilly Media. Chapters 1–5 and 9–10. Freely available at https://r4ds.hadley.nz.

Why read it: The standard introduction to data science with R. This module uses Python examples, but the conceptual workflow — import, tidy, transform, visualise, model, communicate — is language-agnostic. Chapters 1–5 cover data import, transformation, and exploratory analysis. Chapters 9–10 cover visualisation with ggplot2. If you want to understand what the AI is doing when it generates ggplot code or pandas transformations, these chapters give you the mental model. What to take: The workflow, not the syntax. You do not need to learn R. Read for the concepts: what is a "tidy" dataset? why does every row need to be an observation? what does a good exploratory plot reveal that a summary statistic hides? These are the questions you should be asking the AI to answer, regardless of which language it writes in. Note: This is listed as optional in the syllabus. You do not need to read it to complete the module. It is here for students who want to understand the programming concepts behind the AI's output. ---

Becker, J., Rush, N., Barnes, E., & Rein, D. (2025). "Measuring the Impact of Early-2025 AI on Experienced Open-Source Developer Productivity." arXiv:2507.09089.

Why read it: This paper is about programmers, not social scientists. Read it for the self-assessment gap: developers who used AI reported feeling more productive, but objective measures showed smaller and less consistent gains. The gap between perceived and actual improvement is a pattern that appears across AI application domains — and it is the reason this module requires independent verification of AI-generated statistics and interpretations. What to take: The abstract and the discussion of the self-assessment gap (Sections 1 and 5–6, not the full methods). The key finding: your feeling that the AI saved you time or produced correct results is not evidence that it did. Confidence and correctness are separate dimensions. You need an external check. ---

Kapoor, S., & Narayanan, A. (2023). "Leakage and the Reproducibility Crisis in Machine-Learning-Based Science." Patterns, 4(9).

Why read it: A clear explanation of how data leakage — when information from the test set bleeds into training — can inflate performance claims. The relevance to AI-assisted data analysis: if an AI was trained on code and data similar to what you are asking it to analyse (which it almost certainly was), its performance may look better than it would on genuinely novel analytical tasks. The model may "know" the structure of your data without understanding it. What to take: The concept of leakage, not the technical details. For this module, the practical implication is: do not assume the AI's plausible-looking output is correct because it looks right. It may be reproducing patterns from its training data rather than engaging with your specific dataset. Verification — computing one statistic yourself — is the only way to detect this. ---

Spirling, A., Smith, N. A., & Palmer, A. (2023). "Using proprietary language models in academic research requires explicit justification." Nature Computational Science.

Why read it: A short argument that using commercial, proprietary AI models in research carries obligations that free and open-source models do not: the model may change or become unavailable, the training data is undocumented, and reproducibility is compromised. The argument applies to AI-assisted data analysis the same way it applies to AI-assisted writing or annotation. What to take: The justification framework. If you use a commercial AI (ChatGPT, Claude, Gemini) for data analysis in your portfolio or publication, you need to say why that model rather than an open alternative, and what happens to your results if the model is updated or deprecated. This connects to Module 7 (Validation, Reproducibility, and Research Integrity). ---

AI + Code: Methods and Cautionary Papers

Barke, S., James, M. B., & Polikarpova, N. (2023). "Grounded Copilot: How Programmers Interact with Code-Generating Models." Proceedings of the ACM on Programming Languages, 7(OOPSLA1).

Why read it: An empirical study of how programmers actually use AI code generation in practice. The key finding: programmers who accept AI-generated code without reading it carefully introduce more bugs; programmers who treat the AI as a suggestion engine and verify the output produce better code. The finding generalises beyond programming to any AI-assisted analytical work. What to take: The distinction between "acceleration" (AI writes, you accept) and "exploration" (AI suggests, you verify). This module teaches the exploration mode. Section 4 on interaction patterns is the most relevant. ---

Ziegler, A., Kalliamvakou, E., Li, X. A., et al. (2024). "Measuring GitHub Copilot's Impact on Productivity." Communications of the ACM, 67(3).

Why read it: A large-scale study of AI-assisted programming productivity. Like Becker et al. (2025), it finds that perceived productivity gains exceed measured ones, but it also documents where AI helps most: boilerplate code, repetitive transformations, and standard analyses. These are exactly the tasks this module delegates to AI — and exactly the tasks where verification is most important, because the AI's fluency masks potential errors. What to take: The findings on task types. AI is strongest on routine, well-documented tasks and weakest on novel or domain-specific analysis. If you are doing something standard (compute means by group, run a t-test), the AI will probably produce correct code — but you still need to verify the output against your data, because the AI does not know your data's semantics. ---

Perry, N., Srivastava, M., Kumar, D., & Boneh, D. (2023). "Do Users Write More Insecure Code with AI Assistants?" Proceedings of the 2023 ACM SIGSAC Conference on Computer and Communications Security.

Why read it: A controlled experiment showing that participants who used an AI assistant wrote code with more security vulnerabilities than those who did not — and were more confident in the security of their code. This is the same self-assessment gap documented in other domains, applied specifically to code quality. What to take: The finding that AI increases confidence more than it increases correctness. This is the core rationale for the "verify one thing independently" rule in this module. You do not need to read the full methods; Sections 1 (introduction) and 6–7 (discussion and implications) are sufficient. ---

Read Across Modules (Previously Listed)

These readings were introduced in earlier modules and remain relevant to code and data analysis:

- *Shanahan, M. (2024). "Talking About Large Language Models." Communications of the ACM, 67(2). — The vocabulary of "knowing" and "thinking" misleads. The model predicts tokens; it does not understand your data. (Module 1) - Bender, E. M., Gebru, T., McMillan-Major, A., & Shmitchell, S. (2021). "On the Dangers of Stochastic Parrots." FAccT 2021. — The model reassembles patterns from training data. When it writes data analysis code, it is not reasoning about your dataset; it is reproducing statistical patterns it has seen. (Module 1) - Egami, N., Hinck, M., Stewart, B. M., & Wei, H. (forthcoming). "Using Large Language Model Annotations for the Social Sciences." American Journal of Political Science. — What happens when machine-generated values enter your analysis as if they were observations. Read Section 3 on measurement error and downstream bias. (Module 4) - Barrie, C., Palmer, A., & Spirling, A. (forthcoming). "Replication for Language Models." American Journal of Political Science.* — What happens when you run the same analysis twice and get different results, and what happens when the model is deprecated. Relevant to the reproducibility dimension of AI-assisted data analysis. (Module 7) ---

Optional Reference

Wickham, H., Çetinkaya-Rundel, M., & Grolemund, G. (2023). R for Data Science, 2nd ed. Full text at https://r4ds.hadley.nz.

The complete book. Chapters 22–25 cover communication (R Markdown, graphics for publication) and are useful if you want to produce publication-ready output from AI-assisted analysis. Chapters 26–30 cover the programming fundamentals underlying data analysis in any language.

McKinney, W. (2022). Python for Data Analysis, 3rd ed. O'Reilly Media.

The Python equivalent of R for Data Science. If you want to understand what pandas and matplotlib are doing when the AI writes code for you, Chapters 1–6 provide the foundation. Not required reading — the AI handles the syntax — but useful for the verification step, when you need to trace a value through the code.

University of Zurich. (2023). "Recommendations on the Use of Generative Artificial Intelligence."

The institutional policy framework that governs AI use in research at UZH. Read the sections on data handling, disclosure, and researcher responsibility. Relevant whenever AI-assisted analysis touches university data or produces output for a graded submission. --- Module 5 Reading List · AI as a Research Tool