library(dplyr)
input_paths <- c(
"data/raw/smoke_toy.csv",
"data/raw/weather_toy.csv"
)
raw_hashes_before <- tools::md5sum(input_paths)
smoke <- read.csv(
input_paths[1],
colClasses = c(GEOID = "character", date = "character"),
na.strings = "NA"
)
weather <- read.csv(
input_paths[2],
colClasses = c(GEOID = "character", date = "character"),
na.strings = "NA"
)
key <- c("GEOID", "date")
check_path <- "output/checks/week12.txt"
dir.create("output/checks", recursive = TRUE, showWarnings = FALSE)
weather_repeated_keys <- weather |>
count(GEOID, date) |>
filter(n > 1)
report <- capture.output({
cat("SYNTHETIC TEACHING DATA\n")
cat("Smoke input rows:", nrow(smoke), "\n")
cat("Weather input rows:", nrow(weather), "\n")
cat("Repeated weather keys before cleaning\n")
print(weather_repeated_keys)
})
writeLines(report, check_path)
# Check key fields before matching.
stopifnot(
"Smoke keys must be complete." = !anyNA(smoke[key]),
"Weather keys must be complete." = !anyNA(weather[key]),
"Smoke GEOIDs must have five digits." =
all(grepl("^[0-9]{5}$", smoke$GEOID)),
"Weather GEOIDs must have five digits." =
all(grepl("^[0-9]{5}$", weather$GEOID)),
"Smoke counties must belong to the approved sample." =
all(smoke$GEOID %in% c("01001", "06037", "36061")),
"Weather counties must belong to the approved sample." =
all(weather$GEOID %in% c("01001", "06037", "36061")),
"Smoke dates must belong to the approved sample." =
all(smoke$date %in% c("2023-06-07", "2023-06-08")),
"Weather dates must belong to the approved sample." =
all(weather$date %in% c("2023-06-07", "2023-06-08")),
"Smoke county-day keys must be unique." =
anyDuplicated(smoke[key]) == 0
)
# Approved rule: compare entire rows when removing exact duplicates.
weather_clean <- distinct(weather)
weather_conflicts <- weather_clean |>
count(GEOID, date) |>
filter(n > 1)
report <- c(
report,
"Weather keys still repeated after exact deduplication",
capture.output(print(weather_conflicts))
)
writeLines(report, check_path)
if (nrow(weather_conflicts) > 0) {
stop("Conflicting weather records remain. Inspect the check log.")
}
unmatched_smoke <- anti_join(smoke, weather_clean, by = key)
unmatched_weather <- anti_join(weather_clean, smoke, by = key)
joined <- left_join(
smoke,
weather_clean,
by = key,
relationship = "one-to-one"
)
checks <- data.frame(
check = c(
"Smoke input rows",
"Weather input rows",
"Exact weather duplicates removed",
"Weather rows after cleaning",
"Unmatched smoke county-days",
"Unmatched weather county-days",
"Joined rows",
"Unique joined county-days",
"Original smoke columns unchanged",
"Missing precipitation values",
"Negative smoke estimates",
"Raw file hashes unchanged"
),
observed = c(
nrow(smoke),
nrow(weather),
nrow(weather) - nrow(weather_clean),
nrow(weather_clean),
nrow(unmatched_smoke),
nrow(unmatched_weather),
nrow(joined),
nrow(distinct(joined, GEOID, date)),
as.integer(identical(joined[names(smoke)], smoke)),
sum(is.na(joined$precipitation_mm)),
sum(joined$smoke_pm25_ug_m3 < 0, na.rm = TRUE),
as.integer(identical(
tools::md5sum(input_paths), raw_hashes_before
))
),
expected = c(6, 7, 1, 6, 0, 0, 6, 6, 1, 1, 1, 1)
)
checks$passed <- checks$observed == checks$expected
report <- c(report, capture.output(print(checks, row.names = FALSE)))
writeLines(report, check_path)
if (!all(checks$passed)) {
stop("A task-card check failed. Inspect the check log.")
}
dir.create("data/derived", recursive = TRUE, showWarnings = FALSE)
write.csv(
joined,
"data/derived/smoke_weather_toy.csv",
row.names = FALSE,
na = "NA"
)
report <- c(report, "Completed. All task-card checks passed.")
writeLines(report, check_path)
cat(paste(report, collapse = "\n"), "\n")Classwork 7 — Example Answer
A checked join of synthetic smoke and weather data
This example answers all four parts of Classwork 7. It uses the Lecture 8 starter so that the entire task can be inspected in class. The prompts and researcher decisions illustrate a possible exchange with an agent.
All numerical observations are synthetic teaching values. The county identifiers and dates provide a practice setting. The results describe the supplied files.
The R code is displayed without running when this document renders. To reproduce the example, work in a copy of the starter folder, save the script below as R/07_project_task.R, and run the stated commands from that folder. The script requires dplyr 1.1.1 or later. The example results below were checked with the supplied CSV files.
1. Choose one research task
Example task card
| Item | My answer |
|---|---|
| Research question and decision | Can I attach one weather record to each supplied smoke county-day? This will establish whether the two files can support a county-day descriptive table. |
| Inputs | data/raw/smoke_toy.csv, data/raw/weather_toy.csv, and their definitions in data/README.md. These are course-provided synthetic fixtures created November 2, 2026. |
| Observation unit | One county on one day. The intended key is GEOID and date. |
| Sample | County codes 01001, 06037, and 36061 on June 7–8, 2023. There are six intended county-days. |
| One output | data/derived/smoke_weather_toy.csv, with six rows and the smoke, temperature, and precipitation fields. |
| Check 1 | After resolving the documented duplicate, each file must have one row per county-day and every smoke key must match weather. The joined table must retain all six smoke rows. |
| Check 2 | The join must preserve the original smoke columns, the negative smoke estimate, and the missing precipitation value. I will also trace one joined row to both raw inputs. |
| Researcher decision | Whether and how to handle the repeated weather record. I will inspect the records and documentation before approving a rule. |
| Stop condition | Stop if keys are missing or malformed, repeated keys have conflicting values, either file contains an unmatched county-day, or a check differs from this task card. |
I will read GEOID as text to preserve its leading zeros. Smoke PM2.5 is in µg/m³, temperature is in degrees Celsius, and precipitation is in millimeters. The literal NA denotes a missing value.
2. Ask for a plan and review it
Example planning prompt
Read
data/README.mdand this task card. Inspectdata/raw/smoke_toy.csvanddata/raw/weather_toy.csv. Summarize the observation unit, sample, keys, and units. Report repeated keys, exact duplicate rows, and missing values. Propose one R script that createsdata/derived/smoke_weather_toy.csvand saves a check log tooutput/checks/week12.txt. Keep the raw files intact. Stop after the plan so I can decide how to handle any repeated records.
What inspection reveals
| Finding | Evidence from the supplied files |
|---|---|
| Smoke coverage | Six rows and six unique county-day keys. |
| Weather coverage | Seven rows and six unique county-day keys. |
| Repeated weather key | 06037 on 2023-06-07 occurs twice. Both rows have temperature 22 and precipitation 0. |
| Missing precipitation | 01001 on 2023-06-08 has NA precipitation. |
| Negative smoke estimate | 06037 on 2023-06-07 has smoke PM2.5 of −0.4. |
The starter data documentation identifies the exact duplicate as intentional and instructs us to preserve the negative estimate and missing precipitation.
Example reviewed plan
- Read both CSVs with
GEOIDstored as text. - Report the initial row counts and repeated weather key.
- Remove exact full-row duplicates from a derived weather table.
- Check that the derived weather key is unique. Stop if conflicting records remain.
- Check unmatched keys in both directions.
- Left join weather onto smoke, enforcing a one-to-one matching relationship.
- Check the output against the task card, save the derived CSV, and record the result.
My decision before implementation
I approve removing the one exact full-row duplicate from the derived weather table. The two records are identical, and the exercise documentation explains why the duplicate is present.
The script will use distinct(weather), which compares all columns. If two weather records share a key but contain different measurements, they will remain separate and the uniqueness check will stop the script.
I will preserve the missing precipitation value and the negative smoke estimate. I will use a left join with smoke as the starting table so that its six county-days define the output sample.
3. Implement and run the script
Example implementation prompt
Implement the reviewed plan in
R/07_project_task.R. My approved rule is to remove only exact full-row weather duplicates in a derived table. Preserve the raw inputs, missing precipitation, negative smoke estimates, and five-character county codes. Check unmatched keys in both directions and enforce a one-to-one left join. Write the output todata/derived/smoke_weather_toy.csvand the check log tooutput/checks/week12.txt. Run the script from the project root and report the command and actual check results.
Complete R script
Save this code as R/07_project_task.R in your copy of the starter folder.
The expected counts come from this six-county-day task card. For a different dataset, establish the sample and expected checks before adapting the script.
Command to run
Run this command from the root of your copy of agentic-ai-starter.
Rscript --vanilla R/07_project_task.RRecorded example results
| Check | Observed | Expected | Result |
|---|---|---|---|
| Smoke input rows | 6 | 6 | Pass |
| Weather input rows | 7 | 7 | Pass |
| Exact weather duplicates removed | 1 | 1 | Pass |
| Weather rows after cleaning | 6 | 6 | Pass |
| Unmatched smoke county-days | 0 | 0 | Pass |
| Unmatched weather county-days | 0 | 0 | Pass |
| Joined rows | 6 | 6 | Pass |
| Unique joined county-days | 6 | 6 | Pass |
| Original smoke columns unchanged | 1 | 1 | Pass |
| Missing precipitation values | 1 | 1 | Pass |
| Negative smoke estimates | 1 | 1 | Pass |
| Raw file hashes unchanged | 1 | 1 | Pass |
For the three yes/no checks, 1 means true. The log ends with Completed. All task-card checks passed.
Saved artifact
| GEOID | Date | Synthetic smoke PM2.5 (µg/m³) | Temperature (°C) | Precipitation (mm) |
|---|---|---|---|---|
| 01001 | 2023-06-07 | 1.2 | 28 | 0 |
| 01001 | 2023-06-08 | 2.1 | 27 | NA |
| 06037 | 2023-06-07 | −0.4 | 22 | 0 |
| 06037 | 2023-06-08 | 0.8 | 23 | 0 |
| 36061 | 2023-06-07 | 75.0 | 20 | 0 |
| 36061 | 2023-06-08 | 42.0 | 19 | 1.5 |
4. Check the work yourself
Explain the script
The script reads the original files, checks the keys, and removes the documented exact weather duplicate in memory. It then checks both files for unmatched keys and attaches weather using a one-to-one left join. It verifies that the smoke sample and values survived the join before saving the derived table.
Rerun and compare
After the first successful run, run these commands from an R session opened at the project root.
output_path <- "data/derived/smoke_weather_toy.csv"
first_hash <- tools::md5sum(output_path)
status <- system2(
file.path(R.home("bin"), "Rscript"),
c("--vanilla", "R/07_project_task.R")
)
stopifnot(
status == 0,
identical(first_hash, tools::md5sum(output_path))
)In the checked example, the rerun succeeded and the saved table had the same hash.
Trace one row using separate base R expressions
Read the files again and inspect county 06037 on June 7. This check uses direct row selection from the raw inputs.
smoke_raw <- read.csv(
"data/raw/smoke_toy.csv",
colClasses = c(GEOID = "character", date = "character")
)
weather_raw <- read.csv(
"data/raw/weather_toy.csv",
colClasses = c(GEOID = "character", date = "character")
)
saved <- read.csv(
"data/derived/smoke_weather_toy.csv",
colClasses = c(GEOID = "character", date = "character")
)
source_smoke <- subset(
smoke_raw, GEOID == "06037" & date == "2023-06-07"
)
source_weather <- subset(
weather_raw, GEOID == "06037" & date == "2023-06-07"
)
saved_row <- subset(
saved, GEOID == "06037" & date == "2023-06-07"
)
stopifnot(
nrow(source_smoke) == 1,
nrow(source_weather) == 2,
nrow(unique(source_weather)) == 1,
nrow(saved_row) == 1,
saved_row$smoke_pm25_ug_m3 == source_smoke$smoke_pm25_ug_m3,
all(source_weather$temperature_c == saved_row$temperature_c),
all(source_weather$precipitation_mm == saved_row$precipitation_mm)
)
saved_row
# Also check that missing precipitation and leading zeros survive.
missing_row <- subset(
saved, GEOID == "01001" & date == "2023-06-08"
)
stopifnot(
nrow(missing_row) == 1,
is.na(missing_row$precipitation_mm),
identical(missing_row$GEOID, "01001")
)The traced row has smoke PM2.5 of −0.4, temperature 22, and precipitation 0. The raw weather file contains that weather record twice. The saved table contains it once. The second check confirms that 01001 retains its leading zero and that missing precipitation remains NA.
Example notebook entry
November 11, 2026. I accepted the joined table for the synthetic practice task. I approved removing one exact full-row weather duplicate after checking the supplied documentation and both repeated records.
I used the agent to help plan and write the R workflow. My research decisions were the county-day key, the smoke-based sample, the duplicate rule, and preservation of missing precipitation and the negative smoke estimate.
I ran
Rscript --vanilla R/07_project_task.R. The join produced six rows, with zero unmatched county-days. All twelve recorded checks passed, and a rerun reproduced the same CSV. Using separate base R expressions, I traced county06037on June 7 to the original files and checked the missing precipitation for01001on June 8.The values are invented, so the exercise supports a conclusion about this data workflow. My next step for a real project is to read its source definitions and choose a small sample before applying the same checks. Repeated records in another source may require a different decision.
Bring to class discussion
- The task card and the decision approving exact duplicate removal.
R/07_project_task.Rand the command used to run it.- The six-row derived CSV and
output/checks/week12.txt. - The separate raw-row check and a notebook entry explaining what the researcher decided.