🗓️ Week 09
Reproducible Workflow & Responsible Use of AI

STAT 204 – Introduction to Statistical Data Analysis

24 Nov 2026

📜 Learning Pledge (reminder)

Programming is a systematic way to think about a problem — turning a fuzzy question into precise definitions and a chain of answers. Learning R is how we build that mental model.

There’s no point using AI if you’re trying to build that mental model yourself.

Today’s plan

Time What
0:00 Part 1: A workflow for reproducible analysis 20 min
↳ Your turn: write your project’s file structure, post on Ed 8 min
0:20 Part 2: Responsible use of AI 40 min
↳ Where AI fails, checks vs. rewrites 10 min
↳ Writing checks with Claude Code 12 min
↳ Bias, privacy, environmental cost → discussion 18 min
1:00 Before Week 10

Why today: all statistical topics are done. From today on, the AI Policy allows genAI on your project for reproducibility checks and code testing — so we practice doing that well.

Part 1: A Workflow for Reproducible Analysis

What “reproducible” means in this class

Someone else — your peer code reviewer, me, or you in six months — can:

  1. Clone your repository into a new folder
  2. Open it in Positron
  3. Render one file
  4. Get the same numbers, tables, and figures you reported

This is what should happen in the peer code review

Peer code review is due Fri Dec 4. Your reviewer will clone your repo and try to render it. Every error they find should be submitted as an “issue” on Github.

The reproducibility checklist

Row Ask How to check
Runs Does it render from a fresh clone, with no edits? Clone into a new folder → quarto render report.qmd
Paths Relative paths only? No hidden state? Search for /Users/, C:\, setwd(, rm(list
Data Is raw data untouched and documented? data/raw/ is read-only; data/README.md lists source, license, date
Environment Are package versions recorded? renv.lock, or sessionInfo() at the end of the report
Randomness Are seeds set? set.seed() before every split, cv.glmnet(), kmeans()
Correct Row counts at every join and filter? NAs decided? stopifnot() checks; report how many rows were dropped
Honest Limitations stated? AI use disclosed? “AI use” section at the end of the report

Keep this table — it is also the rubric you will use to review your classmates’ code.

Habits behind the checklist

Habit One-line test
One folder, one job. Raw data is read-only. Could you delete output/ and get it back by rendering?
Names say what a thing is. Would a stranger know what df2 holds?
No magic numbers. Does 0.7 (your train fraction) appear in more than one place?
Fail loudly. Does a broken assumption stop the render?
Missing values are a decision. Do you know how many rows each step dropped?
Relative paths, fresh session. Does it render after Restart R?
Small commits that say what changed. Could you find the commit that broke it?

A scaffold for your project

stat204-project/
├── README.md            # what this is + ONE line: how to run it
├── report.qmd           # the runbook: rendering it rebuilds everything
├── data/
│   ├── README.md        # source, license, date downloaded, variable notes
│   ├── raw/             # never edited — by hand or by code
│   └── processed/       # created by code; safe to delete
├── R/
│   ├── 01-clean.R       # numbered = run order
│   ├── 02-explore.R
│   ├── 03-model.R
│   └── functions.R      # helpers you call more than once
├── tests/
│   └── check-clean.R    # checks that stop if something is wrong (Part 2)
├── output/              # figures and tables; safe to delete
├── renv.lock            # package versions (optional but recommended)
└── AGENTS.md            # rules for any AI assistant (Part 2)

Test: delete output/ and data/processed/, render report.qmd — does everything come back?

What that looks like in code

library(here)            # paths relative to the project root

# Constants live in one place
train_frac <- 0.7
seed       <- 204

raw <- read.csv(here("data", "raw", "survey.csv"))   # not "/Users/me/Desktop/..."

clean <- subset(raw, !is.na(income))
message(nrow(raw) - nrow(clean), " rows dropped: missing income")  # a decision, reported

set.seed(seed)
train_id <- sample(nrow(clean), size = floor(train_frac * nrow(clean)))

# Fail loudly: stop the render if an assumption breaks
stopifnot(
  "Duplicated IDs after cleaning" = !anyDuplicated(clean$id),
  "Train set is empty"            = length(train_id) > 0
)

Your turn: your project’s file structure (8 min) ⏱️

With your project partner:

  1. Write the tree your project has now (or will have by Week 10). In the R console:

    fs::dir_tree(recurse = 2)
  2. Annotate each folder and key file with a one-line comment (# what lives here).

  3. Mark which checklist rows you currently fail: ✅ / ⚠️ / ❌.

  4. Post it on Ed Discussion, thread “Week 9: Project file structure” — one post per group, as a code block.

  5. Reply to one other group’s post with one question or suggestion.

Tip

Your structure doesn’t have to match the scaffold exactly. It has to pass the test: fresh clone → render → same results.

Part 2: Responsible Use of AI

The AI Policy, for your project

Work Status
Reproducibility checks and code testing ✅ Allowed from today on
Formatting of report / slides ✅ Allowed
Writing or rewriting your analysis code ❌ Not allowed — the analysis choices are yours
Prose, interpretation, analysis text ❌ Not allowed (grammar software is fine)
AI-use statement in the report 📝 Required — even if it says “no AI used”
  • No one has to use AI, and no one is advantaged by paying for it. Everything today can be done by hand.
  • In Week 10 you defend your analysis orally. Any line of code you can’t explain is a liability.

Where AI fails in data analysis

  • Runs, but answers the wrong question — e.g., predicts on the training set, or reports the CV error at the wrong \(\lambda\)
  • Invented functions and arguments — plausible-looking glmnet() or ggplot2 arguments that don’t exist
  • Silent “fixes” — makes an error go away by wrapping everything in na.omit() or dropping a variable
  • Confident, wrong statistics — causal language for regression coefficients, p-values after lasso selection, “clusters” treated as true groups

How to verify: read the documentation (?cv.glmnet), compare against your own diagnostics, and recompute one number by hand on a small subset.

Checks vs. rewrites

✅ A check

  • Tests your code; stops if something is wrong
  • Doesn’t change any result
  • Lives in tests/ or a check chunk
  • You can explain every line
stopifnot(
  nrow(train) + nrow(test) == nrow(clean)
)

❌ A rewrite

  • Changes how the analysis is done
  • Changes a number, a model, or a figure
  • Replaces your reasoning with the tool’s
# "I cleaned up your model code" ->
# new predictors, new lambda, new plot

The policy allows the left column. Today you learn to make an AI tool stay there.

Writing checks with Claude Code

Claude Code is a coding agent that runs in your terminal (or inside Positron/VS Code). It can:

  • read the files in your project folder
  • run commands (render, run scripts) — after asking permission
  • edit and create files

That is exactly why it needs rules. An agent that can edit files can also “helpfully” rewrite your analysis.

At the start of every session it reads a file called CLAUDE.md from your project folder. That’s where the rules go.

Step 1: Write the rules (AGENTS.md)

# AGENTS.md

## What this project is
STAT 204 final project. Pipeline: R/01-clean.R -> R/02-explore.R -> R/03-model.R -> report.qmd

## Boundaries: you must NEVER
- modify anything in data/raw/, or print its rows (column names only)
- change analysis code, models, tuning choices, or results in R/ or report.qmd
- write or edit prose, interpretation, or the "AI use" section
- add a package without asking
- use absolute paths, setwd(), or rm(list = ls())

## What you MAY do
- write checks in tests/ that stop with a clear message when an assumption fails
- render report.qmd and report the first error and its chunk label, without fixing it
- explain, line by line, what a check does

CLAUDE.md contains one line: @AGENTS.md (other tools read AGENTS.md directly).

Step 2: Ask for one check at a time

❌ Vague

Make my project reproducible and fix any bugs.

The agent decides what “fix” means — and touches everything.

✅ Specific

Read R/01-clean.R. In a new file tests/check-clean.R, write stopifnot() checks that (1) id is unique after the join on line 40, and (2) no more than 5% of rows are dropped. Do not edit R/01-clean.R. Show me the diff before writing.

One task · one file · the check you want · ask for a diff.

Tip: press Shift+Tab to switch to plan mode — Claude Code describes what it will do before touching any file.

Other useful check prompts

  • Fresh-clone test: > Clone this repo into a temporary folder and run quarto render report.qmd. Report the first error and the chunk label. Do not fix anything.

  • Path audit: > List every line in R/ and report.qmd with an absolute path, setwd(), or rm(list = ls()). Don’t edit.

  • Seed audit: > List every call that uses randomness (sample, kmeans, cv.glmnet, …) and whether a set.seed() comes before it.

  • Consistency check: > Every number in the text of report.qmd — is it computed inline with `r ` or typed by hand? List the hand-typed ones.

Notice: none of these change your results. They report; you decide.

Example: the check it might write

# tests/check-clean.R
source(here::here("R", "01-clean.R"))   # creates `raw` and `clean`

stopifnot(
  "Duplicated id after join"         = !anyDuplicated(clean$id),
  "Response has missing values"      = !anyNA(clean$income),
  "More than 5% of rows were dropped" = nrow(clean) >= 0.95 * nrow(raw)
)
message("check-clean: all checks passed (", nrow(clean), " rows)")

Is this good? Who chose 5%? (You did — it’s your decision, not the agent’s.) Does 01-clean.R actually create raw? (Verify!)

Step 3: Verify the check — it’s your check now

  1. Read every line. If you can’t explain it, delete it.
  2. Break it on purpose. Duplicate a row, insert an NA → does the check fail? A check that never fails is not a check.
  3. Own the thresholds. Every number in a check is an analysis decision.
  4. Run it from a fresh session — the check has to be reproducible too.
  5. Commit separately, with an honest message: git commit -m "Add checks for cleaning step (drafted with Claude Code)"

Your commit history is your process evidence — it shows what you wrote and what a tool drafted.

Your AI-use statement

Required in the report: which tool, what for, how you verified it.

AI use. We used Claude Code to draft the checks in tests/check-clean.R and to run a fresh-clone render test. We read each check, confirmed each one fails when we insert a duplicate row or a missing value, and changed the row-loss threshold from 10% to 5%. No AI was used for analysis code, interpretation, or writing. Grammarly was used for spelling.

Or: “We did not use any AI tools.” — that’s a complete statement too.

Beyond “does it work?”

  • Privacy: an agent can open any file in your folder, and what it reads is sent to a company’s servers. Never point it at restricted data (health, student records, IRB-protected, data whose license forbids sharing). Put that in AGENTS.md — or don’t use the tool on that project.
  • Bias: models reflect their training data. They’re most fluent in the most common code and the most common framing of a question — which is not always right for your data.
  • Environmental cost: one agent session can make many model calls. Writing stopifnot(!anyDuplicated(df$id)) yourself takes 30 seconds. Is the tool worth it for this task?
  • Authorship & learning: the code you can’t explain is code you can’t defend in Week 10.

Discussion (15 min) 💬

In groups of 3–4, pick one question. Post one answer per group on Ed, thread “Week 9: Responsible AI”.

  1. Responsibility. Your peer reviewer finds that a check Claude Code wrote never actually runs. Whose bug is it? What should your AI-use statement say?
  2. Privacy. Your dataset has free-text survey answers. Is it OK to let an agent read the folder? What would you put in AGENTS.md?
  3. Where’s the line? Give one example of “testing my code” and one of “the AI did my analysis” that look almost the same. What separates them?
  4. Cost. When is running an agent worth its energy and money, and when is it faster and better to write the check yourself?
  5. Bias. If the AI’s “default” way of handling missing values or outliers is the most common one online, how could that bias your results?

Last 3 minutes: one group per question shares out.

Key points

  • Reproducible = fresh clone → render one file → same results. Test it, don’t assume it.
  • The checklist is also your peer-review rubric.
  • On your project, AI may check and test your code — never write your analysis or your words.
  • Rules first (AGENTS.md), one small request at a time, ask for a diff.
  • Break every check on purpose before you trust it.
  • Disclose what you used, what for, and how you verified it.

Before Week 10

Week 10: presentations Dec 1 & 3 (oral exam — be ready to defend every choice) · peer code review due Fri Dec 4 · report due Tue Dec 8, 5 pm.

No class Thursday — Happy Thanksgiving! 🦃

Questions?

Bring questions about the project’s AI policy to office hours or the Wednesday session.