# ============================================================================
# THIS CHUNK DOES NOT BELONG IN YOUR PROJECT. It fabricates the survey file.
# ============================================================================
if (!file.exists("student_survey_demo.csv")) {
set.seed(540); N <- 260
ct <- sample(c("Lark","Neither","Owl"), N, TRUE, prob = c(.25,.50,.25))
base <- ifelse(ct == "Lark", 60, ifelse(ct == "Neither", 110, 170))
bw <- round(pmax(rnorm(N, base, 28), 0))
bk <- bw + round(pmax(rnorm(N, 45 + 25*(ct == "Owl"), 25), -20))
jet <- bk - bw
d <- data.frame(
id = 1:N, year = NA, chronotype = ct, bed_week = bw, bed_wknd = bk,
sleep_hrs = NA, gpa = NA, stress = NA, alcohol = NA,
stringsAsFactors = FALSE)
d$stress <- round(pmin(pmax(12 + .055*jet + 2.5*(ct=="Owl") + rnorm(N,0,5), 0), 40))
d$sleep_hrs <- round(pmin(pmax(rnorm(N, 7.1 - .004*jet, .9), 3), 11), 1)
d$gpa <- round(pmin(pmax(rnorm(N, 3.25 - .0018*jet, .42), 0), 4), 2)
d$alcohol <- rpois(N, 3.2)
d$year <- sample(c("First","Soph","Junior","Senior"), N, TRUE)
s <- sample(N, 11); d$stress[s] <- -9
c6 <- sample(setdiff(1:N, s), 6); d$chronotype[c6] <- ""
d$gpa[c(18, 89, 202)] <- round(d$gpa[c(18, 89, 202)] * 10, 1)
d$alcohol[c(6, 43, 131, 200)] <- 99
d <- rbind(d, d[c(34, 151), ]); d <- d[order(d$id), ]
write.csv(d, "student_survey_demo.csv", row.names = FALSE)
}Social jet lag and stress — and whether I can trust the translation
Model answer · STAT 540 · Computing in Statistics · Fall 2026
A worked example at roughly full marks, including the bonus. The grey “Why this scores well” boxes are notes from me to you; a real submission would not have them.
Language pair: R → Python. My analysis is in R; the assistant translated it to Python. This document therefore uses the knitr engine — no Jupyter needed. If your pair runs the other way, start from project_report_template.qmd instead.
About the data. A real submission loads an Appendix A dataset. So that this file renders anywhere with no packages, it uses a synthetic stand-in of the same shape with realistic defects built in. The numbers are not any real dataset’s numbers — the structure is what you are copying.
About the transcript. The Python in section 4 is a realistic reconstruction of what an assistant produces for this task, including its two characteristic mistakes. Yours will be the real thing, pasted verbatim.
Do not copy the question. Note what this example does to escape the obvious: a derived variable, and a question about whether a relationship differs by subgroup — which section 6 then shows it does not, once the numbers are asked the right question.
1 The question
Among these students, does the weekend-to-weekday shift in bedtime — social jet lag — track reported stress, and does it do so equally for larks and owls?
I expected a positive association, stronger among owls, on the theory that an owl forced into an early weekday start is doing the most violence to their own schedule.
Risky elements I built in (Part 1 of the handout): missing values with documented codes, a derived variable, a grouped summary with counts, a three-level categorical, a statistic with a divisor convention, and a filter that changes the row count. Six of the eight — which is why there was plenty to find.
2 The data
| Dataset | Student sleep-and-wellbeing survey (stand-in) |
| Collected by, from whom | One instructor, from students in their introductory statistics sections |
| Why | As a teaching dataset, not to study sleep |
| One row is | one student’s self-report |
| Size as downloaded | 262 rows × 9 columns |
| Variable | Units / levels | Missing code | What it measures |
|---|---|---|---|
bed_week, bed_wknd |
minutes after 22:00 | none | typical bedtimes |
chronotype |
Lark / Neither / Owl | blank | self-classified |
stress |
0–40 | -9 |
self-reported |
alcohol |
drinks/week | 99 |
self-reported |
gpa |
0.00–4.00 | none | self-reported |
What this dataset cannot tell me. It is cross-sectional, so I cannot say which way the arrow points. Chronotype is self-classified. Everything is self-reported to an instructor.
Students in one instructor’s introductory statistics sections. Not “college students.” Every conclusion below stays inside that sentence.
2.1 Import and cleaning
raw <- read.csv("student_survey_demo.csv", na.strings = c("", "NA"))
dim(raw)[1] 262 9
The na.strings argument is not decoration — see section 11 for how I learned to put it there.
summary(raw[, c("bed_week", "bed_wknd", "stress", "gpa", "alcohol")]) bed_week bed_wknd stress gpa alcohol
Min. : 17.00 Min. : 9.0 Min. :-9.00 Min. : 2.220 Min. : 0.000
1st Qu.: 73.25 1st Qu.:117.2 1st Qu.:11.00 1st Qu.: 2.910 1st Qu.: 2.000
Median :105.50 Median :156.0 Median :15.50 Median : 3.215 Median : 3.000
Mean :111.29 Mean :161.1 Mean :14.77 Mean : 3.513 Mean : 4.775
3rd Qu.:143.00 3rd Qu.:204.8 3rd Qu.:20.00 3rd Qu.: 3.420 3rd Qu.: 4.000
Max. :232.00 Max. :326.0 Max. :30.00 Max. :33.600 Max. :99.000
That summary finds three of the five defects on its own: stress has a minimum of −9 on a 0–40 scale, alcohol a maximum of 99, and gpa a maximum above 4.00.
clean <- raw
n_dupes <- sum(duplicated(clean)); clean <- clean[!duplicated(clean), ]
n_stress <- sum(clean$stress == -9, na.rm = TRUE); clean$stress[clean$stress == -9] <- NA
n_alc <- sum(clean$alcohol == 99, na.rm = TRUE); clean$alcohol[clean$alcohol == 99] <- NA
n_gpa <- sum(clean$gpa > 4, na.rm = TRUE)
clean$gpa[clean$gpa > 4] <- clean$gpa[clean$gpa > 4] / 10
n_ct <- sum(is.na(clean$chronotype))
clean$jetlag <- clean$bed_wknd - clean$bed_week
write.csv(clean, "student_survey_clean.csv", row.names = FALSE)
c(dupes = n_dupes, stress_minus9 = n_stress, alcohol_99 = n_alc,
gpa_times10 = n_gpa, chronotype_blank = n_ct, rows_after = nrow(clean)) dupes stress_minus9 alcohol_99 gpa_times10 chronotype_blank
2 11 4 3 6
rows_after
260
| Defect | Rows | What I did |
|---|---|---|
| Identical duplicated rows (ids 34, 151) | 2 | dropped |
stress coded -9 |
11 | recoded to NA; kept the rows, their bedtimes are real |
alcohol coded 99 |
4 | recoded to NA |
gpa ten times too large (31.2, 31.9, 33.6) |
3 | divided by 10 — all landed in plausible range |
chronotype left blank |
6 | treated as missing; not given a category of its own |
260 distinct students; 243 have all three of the variables my question needs.
ok <- clean[!is.na(clean$jetlag) & !is.na(clean$stress) &
!is.na(clean$chronotype), ]
nrow(ok)[1] 243
2.2 Summary
round(do.call(rbind, lapply(split(ok, ok$chronotype), function(s)
c(n = nrow(s), mean_jetlag = mean(s$jetlag),
mean_stress = mean(s$stress), sd_jetlag = sd(s$jetlag)))), 2) n mean_jetlag mean_stress sd_jetlag
Lark 61 43.23 13.52 25.62
Neither 120 44.11 15.82 25.14
Owl 62 67.84 18.66 27.02
Owls shift their bedtime about 25 minutes more between weekdays and weekends than larks do, and report about 5 points more stress.
2.3 A function of my own
I need the same slope four times — once overall and once within each chronotype — and writing the lm call out four times is four chances to fit the wrong column.
#' Slope of stress on social jet lag, scaled to a chosen interval.
#'
#' @param df Rows with non-missing jetlag and stress.
#' @param per Minutes of social jet lag the slope is reported per.
#' @return Change in stress score per `per` minutes of extra jet lag.
stress_slope <- function(df, per = 30) {
round(unname(coef(lm(stress ~ jetlag, data = df))[2]) * per, 2)
}
c(all = stress_slope(ok),
sapply(split(ok, ok$chronotype), stress_slope)) all Lark Neither Owl
2.07 0.71 1.64 2.49
2.4 Figures
cols <- c(Lark = "#4C72B0", Neither = "#999999", Owl = "#C44E52")
plot(ok$jetlag, ok$stress, col = cols[ok$chronotype], pch = 19, cex = .7,
xlab = "Social jet lag (minutes later to bed at the weekend)",
ylab = "Reported stress (0-40)",
main = "A clear gradient by eye - section 6.2 asks whether it is real")
for (g in names(cols)) {
s <- ok[ok$chronotype == g, ]
xs <- seq(min(s$jetlag), max(s$jetlag), length.out = 50)
lines(xs, predict(lm(stress ~ jetlag, data = s),
newdata = data.frame(jetlag = xs)), col = cols[g], lwd = 2)
}
legend("topleft", legend = paste0(names(cols), " (n=",
as.integer(table(ok$chronotype)[names(cols)]), ")"),
col = cols, pch = 19, bty = "n")What this figure shows: pooled across all 243 students, each extra 30 minutes of social jet lag goes with about 2.07 more stress points. The three fitted lines fan out — 0.71 for larks, 1.64 for the middle group, 2.49 for owls — which looks like a clean gradient. Section 6 asks whether that gradient survives being tested, and whether the pooled 2.07 means what it appears to.
boxplot(jetlag ~ chronotype, data = ok, col = "white", border = "grey30",
xlab = "", ylab = "Social jet lag (minutes)",
main = "Owls swing their bedtime about 25 minutes more than larks")
set.seed(1)
points(jitter(as.numeric(factor(ok$chronotype)), amount = .12), ok$jetlag,
col = "#4C72B080", pch = 19, cex = .6)What this figure shows: owls carry the most social jet lag (67.8 minutes against 43.2 for larks), with enough overlap that plenty of individual larks shift more than plenty of individual owls.
2.5 The high-stress subgroup
stressed <- clean[clean$stress > 20, ]
c(n = nrow(stressed), mean_jetlag = round(mean(stressed$jetlag, na.rm = TRUE), 2)) n mean_jetlag
67.00 64.89
67 students reporting stress above 20, with a mean social jet lag of 64.89 minutes. Hold on to that 67 — section 5 has something to say about it.
3 The translation
| Assistant | [name], [version] |
| Date | 2026-10-10 |
| Attempts | one |
My prompt, verbatim:
Here is my R analysis of a student survey. Please translate it into Python with
pandas, keeping the same logic. It should read student_survey_clean.csv, keep
only the rows with non-missing jetlag, stress and chronotype, and write a
results CSV with: rows in the clean file, rows used, number of chronotype
groups, mean stress, the standard deviation of jetlag, mean jetlag for owls,
and the size and mean jetlag of the subgroup with stress above 20.
[my R code pasted here]
What it returned, verbatim and unedited:
# translate_analysis.py
import numpy as np, pandas as pd
clean = pd.read_csv("student_survey_clean.csv")
ok = clean.dropna()
stressed = clean[clean["stress"] > 20]
out = pd.DataFrame({
"quantity": ["n_rows_clean", "n_used", "n_chronotype_groups",
"mean_stress_used", "sd_jetlag_used", "mean_jetlag_owl",
"n_high_stress", "mean_jetlag_high_stress"],
"value": [len(clean),
len(ok),
ok["chronotype"].nunique(),
ok["stress"].mean(),
np.std(ok["jetlag"]),
ok.loc[ok["chronotype"] == "Owl", "jetlag"].mean(),
len(stressed),
stressed["jetlag"].mean()],
})
out.to_csv("results_theirs.csv", index=False)Its prose alongside the code: “This is a faithful pandas translation of your R script. Note that pandas handles missing values automatically, so the explicit is.na() filtering is not needed.” — flagged for check 7 in section 6. That second sentence is doing a great deal of work and is the reason for its first mistake.
4 Verification, Tier 1 — does the translation compute the same thing?
My tolerance is 1e-8 on absolute difference. Every quantity here is a count or a mean of integers, so there is no reason for genuine floating-point drift beyond machine epsilon; anything larger is a real difference, not noise.
mine <- data.frame(
quantity = c("n_rows_clean","n_used","n_chronotype_groups","mean_stress_used",
"sd_jetlag_used","mean_jetlag_owl","n_high_stress",
"mean_jetlag_high_stress"),
value = c(nrow(clean), nrow(ok), length(unique(ok$chronotype)),
mean(ok$stress), sd(ok$jetlag),
mean(ok$jetlag[ok$chronotype == "Owl"]),
nrow(stressed), mean(stressed$jetlag, na.rm = TRUE)))
write.csv(mine, "results_mine.csv", row.names = FALSE)
print(mine, digits = 10) quantity value
1 n_rows_clean 260.00000000
2 n_used 243.00000000
3 n_chronotype_groups 3.00000000
4 mean_stress_used 15.97119342
5 sd_jetlag_used 27.70962131
6 mean_jetlag_owl 67.83870968
7 n_high_stress 67.00000000
8 mean_jetlag_high_stress 64.89285714
| Quantity | Mine (R) | Translation (Python) | Difference | Verdict | Mechanism |
|---|---|---|---|---|---|
n_rows_clean |
260 | 260 | 0 | ✓ | — |
n_used |
243 | 239 | −4 | ✗ | A |
n_chronotype_groups |
3 | 3 | 0 | ✓ | — |
mean_stress_used |
15.971193 | 15.979079 | +0.0079 | ✗ | A |
sd_jetlag_used |
27.709621 | 27.827025 | +0.1174 | ✗ | A + B |
mean_jetlag_owl |
67.838710 | 68.262295 | +0.4236 | ✗ | A |
n_high_stress |
67 | 56 | −11 | ✗ | C |
mean_jetlag_high_stress |
64.892857 | 64.892857 | 0 | ✓ | see below |
4.1 Row counts at every stage
| Stage | Mine (R) | Translated (Python) | Agree? |
|---|---|---|---|
| As read | 260 | 260 | ✓ |
Non-missing jetlag, stress, chronotype |
243 | 239 | ✗ |
Subgroup with stress > 20 |
67 | 56 | ✗ |
Two separate faults, in opposite directions, and the row-count table found both before I looked at a single statistic.
4.2 Mechanism A — dropna() with no subset
My R filter named three columns. The translation wrote clean.dropna(), which drops any row with a missing value in any column — including alcohol, which my analysis never touches. Four students were discarded purely for declining to report their drinking.
That is why four of the six quantities disagree: the two versions are averaging over different people. The fix is one argument:
ok = clean.dropna(subset=["jetlag", "stress", "chronotype"])The assistant’s own prose predicted this mistake — “pandas handles missing values automatically” — which is true in the narrow sense that .mean() skips NaN, and badly wrong as a reason to discard an explicit, deliberate filter.
4.3 Mechanism B — np.std() where I wrote sd()
Hidden inside the sd_jetlag_used difference are two faults pulling in opposite directions, which is why the net looked small enough to ignore:
| Step | Value | Change |
|---|---|---|
Mine: sd() over 243 rows (divides by \(n-1\)) |
27.709621 | — |
Same 243 rows, np.std() (divides by \(n\)) |
27.652547 | −0.057 |
np.std(), but on the translation’s 239 rows |
27.827025 | +0.174 |
numpy.std defaults to ddof=0; R’s sd() and pandas.Series.std() both use \(n-1\). The assistant reached for numpy rather than for the pandas method that would have matched. On its own this is a 0.2% error — and 0.2% errors are exactly the ones that get written off as rounding.
4.4 Mechanism C — the fault was mine, and it is an R one
n_high_stress is where the translation was right and I was wrong.
sum(is.na(stressed$id)) # rows in my subgroup that are entirely NA[1] 11
clean$stress > 20 returns NA, not FALSE, for the eleven students whose stress is missing. Subsetting a data frame with a logical vector containing NA gives you a row of all NAs for each one. My 67 was 56 real students plus eleven phantoms. Python’s boolean indexing treats NaN as False and returned the correct 56.
The fix in R is which(), which drops NA indices:
nrow(clean[which(clean$stress > 20), ])[1] 56
mean_jetlag_high_stress matched to fifteen decimal places — 64.892857 in both — because my mean(..., na.rm = TRUE) skipped the eleven phantom rows that the nrow() had just counted.
So the statistic was right while the sample size behind it was wrong by 20%. If I had compared only the means, as I originally planned to, this error would have been completely invisible. It was the row count that caught it, and nothing else would have.
The row-count table localised both faults in a minute, before any theorising. Each mechanism is named at the level of a function argument — subset=, ddof, which() — rather than as a category of blame. Two defects inside the one standard-deviation figure are separated rather than netted.
And the most interesting finding is the student’s own bug, caught because the machine disagreed. Saying so is worth more than catching the assistant out.
Note the asymmetry this direction produced: the assistant’s errors were permissive — pandas quietly did something reasonable — while mine was an R trap that produced visible NA rows nobody looked at. R → Python tends to turn loud problems into plausible numbers, so this direction needs the row counts more, not less.
5 Verification, Tier 2 — is the analysis right at all?
Now assume the translation is perfect. Nothing below would show up in any comparison.
5.1 1. Denominators
The only rate I report is “percent missing on stress”: 11 students out of the 260 in the clean file, so 4.2%. Not out of the 243 in the analysis set — that denominator already excludes the six blank chronotypes, who have nothing to do with who declined the stress question.
5.2 2. Weighting — and the finding that changed my headline
My pooled slope of 2.07 is fitted to all 243 students at once, across three groups with very different means: owls are higher on jet lag and higher on stress. Part of that slope is therefore not “more jet lag goes with more stress within a person’s group” — it is “owls are higher on both.”
w <- ok
w$j_c <- w$jetlag - ave(w$jetlag, w$chronotype)
w$s_c <- w$stress - ave(w$stress, w$chronotype)
c(pooled = round(coef(lm(stress ~ jetlag, data = ok))[[2]] * 30, 2),
within = round(coef(lm(s_c ~ j_c, data = w))[[2]] * 30, 2))pooled within
2.07 1.64
The within-group slope is 1.64, not 2.07. The pooled figure is 26% too large, and the excess is a between-group difference in level, not an association.
Both programs compute 2.07 identically and correctly. No comparison in section 5 could ever have found this.
5.3 3. Filters — who got dropped
dropped <- clean[is.na(clean$stress) | is.na(clean$chronotype), ]
rbind(dropped = c(n = nrow(dropped), mean_gpa = round(mean(dropped$gpa), 2)),
kept = c(n = nrow(ok), mean_gpa = round(mean(ok$gpa), 2))) n mean_gpa
dropped 17 3.05
kept 243 3.19
The 17 dropped students have a mean GPA of 3.05 against 3.19 for those kept. GPA is not in my model, but this says the dropped students are not a random seventeen — which matters for the next check.
5.4 4. Missingness
refused <- raw$id[!is.na(raw$stress) & raw$stress == -9]
c(refused_n = length(unique(refused)),
refused_jetlag = round(mean(clean$jetlag[clean$id %in% refused]), 1),
answered_jetlag = round(mean(clean$jetlag[!(clean$id %in% refused)]), 1)) refused_n refused_jetlag answered_jetlag
11.0 53.0 49.7
Students who declined the stress question average 53.0 minutes of social jet lag against 49.7 for those who answered — about three minutes higher. That is small, and with eleven students I would not want to lean on it, but it points the same way as check 3: the people I dropped are not quite like the people I kept.
Direction of the bias: I have removed students who were slightly higher on my explanatory variable and whose stress is unknown. If their stress was also high, my slope is attenuated. I cannot rule it out, and no amount of correct code would help.
5.5 5. Assumptions — is the gradient real?
My figure shows three slopes fanning out, 0.71 → 1.64 → 2.49, and my prediction was that owls would be steepest. They are. But “steepest in the sample” and “steeper in these students” are different claims, so I tested it rather than reading it off the plot.
for (g in c("Lark", "Neither", "Owl")) {
s <- ok[ok$chronotype == g, ]
ci <- confint(lm(stress ~ jetlag, data = s))[2, ] * 30
cat(sprintf("%-8s n=%3d slope/30 = %5.2f 95%% CI [%5.2f, %5.2f]\n",
g, nrow(s), stress_slope(s), ci[1], ci[2]))
}Lark n= 61 slope/30 = 0.71 95% CI [-0.75, 2.17]
Neither n=120 slope/30 = 1.64 95% CI [ 0.50, 2.77]
Owl n= 62 slope/30 = 2.49 95% CI [ 0.95, 4.02]
anova(lm(stress ~ jetlag * chronotype, data = ok))["jetlag:chronotype", ]Analysis of Variance Table
Response: stress
Df Sum Sq Mean Sq F value Pr(>F)
jetlag:chronotype 2 73.416 36.708 1.363 0.2579
The three confidence intervals overlap almost entirely, and the interaction term gives F = 1.36, p = 0.26. There is no evidence here that the slopes differ by chronotype at all. The gradient I was pleased with is consistent with three samples of a single common slope of about 1.64.
The lark slope is especially fragile:
lark <- ok[ok$chronotype == "Lark", ]
js <- sapply(seq_len(nrow(lark)),
function(i) coef(lm(stress ~ jetlag, data = lark[-i, ]))[[2]] * 30)
c(slope_all_61 = stress_slope(lark),
jackknife_min = round(min(js), 2), jackknife_max = round(max(js), 2)) slope_all_61 jackknife_min jackknife_max
0.71 0.44 1.08
Leaving out any single one of the 61 larks moves their slope anywhere between 0.44 and 1.08. A number that moves by half its own size when one student leaves is not evidence of anything.
I have rewritten section 8 accordingly. This is the check that cost me my headline finding, and no comparison between languages could have raised it.
5.6 6. Magnitudes
Jet lag runs from −16 to 125 minutes; up to about two hours later at the weekend is believable, and so is a handful of students going to bed slightly earlier. Stress is bounded 0–40 by the instrument, and the observed range sits inside it.
Had both bedtime columns been read in hours rather than minutes, the owl mean would have been 1.13 instead of 67.8 — but the error would have been internally consistent, both programs would have agreed perfectly, and only this check would have caught it.
5.7 7. Claims
| Claim | Who made it | Code that earns it | Kept? |
|---|---|---|---|
| “a faithful pandas translation” | the assistant | contradicted by section 5 | ✗ removed |
| “pandas handles missing values automatically, so the explicit filtering is not needed” | the assistant | false — it is what caused mechanism A | ✗ removed |
| Owls shift ~25 min more than larks | me | summary chunk |
✓ |
| Slope 2.07 per 30 min | me | my-function chunk |
✓ restated as 1.64 within groups per 6.2 |
| “the association is stronger for owls” | me | my-function chunk |
✗ withdrawn per 6.5 |
| 67 students above stress 20 | me | high-stress chunk |
✗ corrected to 56 per 5.4 |
Two of the six claims I had to remove were my own.
Three of these seven changed something: the weighting check cut the headline by 26%, the assumption check withdrew the subgroup finding entirely, and the claims audit corrected a count. Every answer names this dataset’s columns and these dropped students.
The strongest move in the whole report is in 6.5. The student had a result they liked, tested it rather than reporting it, and lost it. That is the behaviour the Tier 2 marks exist to buy.
6 The adversarial test
The phantom-row mechanism, isolated to four rows.
probe <- data.frame(id = 1:4, group = c("A","A","B","B"),
value = c(10, NA, 30, 40))
probe[probe$value > 20, ] id group value
NA NA <NA> NA
3 3 B 30
4 4 B 40
R returns three rows — two real and one entirely NA. The same filter in the translation:
probe[probe["value"] > 20] # 2 rows, as it should beAnd the sting:
c(R_nrow = nrow(probe[probe$value > 20, ]),
R_mean = mean(probe$value[probe$value > 20], na.rm = TRUE),
R_with_which = nrow(probe[which(probe$value > 20), ])) R_nrow R_mean R_with_which
3 35 2
The property that triggers it: any NA in the column being compared, in a data-frame row subset written with [. Nothing else is needed — not a particular size, not missing values anywhere else.
And note the mean is 35 in both languages. The statistic agrees while the sample size does not, which is precisely why this error survives every check except a row count.
7 Findings
Among these 243 students, social jet lag and reported stress move together. The honest figure is the within-group one: each extra 30 minutes of weekend bedtime shift goes with about 1.6 more stress points, not the 2.07 the pooled fit suggested. The difference is owls sitting higher on both variables rather than a steeper relationship.
Owls carry about 25 minutes more shift and 5 points more stress than larks. My prediction that the association would be steepest among owls is not supported: the fitted slopes do rise from 0.71 to 2.49 across the groups, but the confidence intervals overlap almost entirely and the interaction test gives p = 0.26. With 61, 120 and 62 students, these data cannot distinguish three different slopes from one common slope of about 1.6.
Of the 56 students reporting stress above 20 — not the 67 I first wrote — mean social jet lag is 64.9 minutes.
Three numbers in this section changed during verification: the headline slope (2.07 → 1.64), the subgroup count (67 → 56), and the subgroup claim itself, which I withdrew.
8 The reckoning
The assistant did the mechanical work well. Structure, grouping, the output file, the arithmetic — all correct, written in ten seconds. Both of its defects were defaults: dropna() without a subset, and numpy.std’s ddof=0. Neither was a misunderstanding of my analysis.
Its prose was worse than its code. “A faithful pandas translation” was false, and “pandas handles missing values automatically, so the explicit filtering is not needed” was the actual cause of its worst error, stated as a reassurance. The dangerous pattern is not wrong code — wrong code often announces itself. It is nearly-right code with a confident sentence attached.
And the single most useful thing the exercise did was catch a bug of my own that I would never have found alone, because the statistic it corrupted looked perfectly fine.
What I will check by reflex: row counts at every stage, in both versions, before looking at any statistic. That one table found all three defects in this project, including the one where the mean agreed to fifteen decimal places. And in R specifically, which() rather than a bare logical whenever the column being compared can be missing.
9 Limitations
I did not choose the sample — one instructor’s introductory sections — and nothing here extends past them. I did not choose the variables: course load and exam timing would plausibly drive both weekend recovery sleep and stress, and nobody recorded them.
The design is cross-sectional, so the arrow could point either way. Chronotype is self-classified. Per 6.3 and 6.4 the students I dropped are slightly unlike those I kept. And per 6.5, the subgroup analysis is underpowered — three groups of roughly 60, 120 and 60 cannot resolve the slope differences I went looking for.
10 What broke
My first summary table had four chronotype groups. Lark, Neither, Owl, and one with no name at all, containing six students.
I assumed I had a typo in my recoding and spent twenty minutes reading a chunk that was fine. The actual cause was my read.csv call: R reads an empty field in a character column as the string "", which is a perfectly good factor level and not missing at all. The six students who left chronotype blank became a category.
What found it: printing table(raw$chronotype) and seeing a count sitting beside an empty label. What fixed it: na.strings = c("", "NA") in the read.csv call, which is why that argument is in section 3 and why I flagged it there.
What I changed more generally: I now print table() on every categorical column before using it, and I never assume a blank is missing until I have checked which language is doing the reading. Pandas would have given me NaN here without being asked — which is a reminder that “it worked in the other language” is not the same as “I understood it.”
11 References
- Codebook for the dataset — in a real submission,
?SleepStudyor the DASL or Census documentation, with URL and date accessed. - R
?read.table— confirmed thatna.stringsdoes not include""by default for character columns. Accessed 2026-10-10. - R
?"["and R Language Definition §3.4.1 — confirmed that logical subsetting withNAyieldsNArows, and thatwhich()drops them. Accessed 2026-10-10. numpy.stdandpandas.DataFrame.stddocumentation — confirmed theddofdefaults of 0 and 1 respectively. Accessed 2026-10-10.pandas.DataFrame.dropnadocumentation — confirmed thatsubsetdefaults to all columns. Accessed 2026-10-10.- [Assistant name], 2026-10-10 — produced the Python translation in section 4. Transcript reproduced there in full.
Appendix: what this example would score
| Component | Points | Why |
|---|---|---|
| Question, data, and analysis | 20 / 20 | six risky elements; provenance, sample reach and codebook stated; five defects documented |
| The transcript | 5 / 5 | prompt and output verbatim, assistant and date recorded, prose preserved for check 7 |
| Tier 1 | 15 / 15 | eight quantities, stated tolerance, row counts by stage, three mechanisms named — one of them the student’s own |
| Tier 2 | 18 / 18 | all seven answered about this analysis; three changed something, one withdrew the headline subgroup claim |
| Adversarial test | 7 / 7 | four rows, both languages, triggering property named, and the mean-agrees sting |
| The reckoning | 5 / 5 | separates the assistant’s code from its prose; ends in two concrete reflexes |
| Reproducibility | 5 / 5 | renders clean from a restarted session; both programs and the probe submitted |
| Report subtotal | 75 / 75 | |
| Subtle-error bonus | +10 | mechanism C — a 20% error in sample size that left the reported mean bit-for-bit identical |
The proposal (10) and the presentation (15) are graded separately.