A saved accuracy value does not identify the trials that contributed to it, and an unchanged total can conceal records assigned to the wrong participant. Reproducing the result requires both its source records and the decisions that connect those records to the calculation. This chapter establishes that connection first for a survey score and then for participant accuracy. We save tables and read them back, checking whether identifiers, types, and measurements survive the round trip. We also construct checks that express the analysis rules and finish by recalculating the saved participant results in a fresh session.
19.1 Recorded values, working values, and derived results
Before tracing a participant’s accuracy to many trials, consider how a single answer becomes a score. The survey file records Agree for one response to SAT_3, yet its adjusted score is 2. To explain that result, we need the recorded answer and the scoring rule, not just the final number.
The agreement scale runs from 1 for Strongly disagree to 5 for Strongly agree. The statement is “These days I am dissatisfied with my life.” Stronger agreement means lower life satisfaction, so we reverse the scale by subtracting the agreement score from 6. Blank answers and the refusal code -99 receive no score, and reason records why. Together, ResponseId and item identify the answer whose values we compare.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| library(tidyverse)
survey <- read_csv(
"data/practice/survey.csv",
col_types = cols(`Duration (in seconds)` = col_double(), .default = col_character()),
na = "",
trim_ws = FALSE,
locale = locale(encoding = "UTF-8")
)
agreement_levels <- c(
"Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"
)
sat_3 <- survey |>
select(ResponseId, recorded = SAT_3) |>
mutate(
item = "SAT_3",
score = recode_values(recorded, from = agreement_levels, to = 1:5),
reason = case_when(
is.na(recorded) ~ "skipped",
recorded == "-99" ~ "refused",
is.na(score) ~ "invalid",
.default = "observed"
),
adjusted = 6L - score
)
sat_3 |>
filter(ResponseId %in% c("R_hopQ1ccnJqGj", "R_7k2Xvb2KojVD")) |>
select(ResponseId, item, recorded, score, reason, adjusted)
count(sat_3, reason)
|
1
2
3
4
5
6
7
8
9
10
11
| # A tibble: 2 × 6
ResponseId item recorded score reason adjusted
<chr> <chr> <chr> <int> <chr> <int>
1 R_hopQ1ccnJqGj SAT_3 Agree 4 observed 2
2 R_7k2Xvb2KojVD SAT_3 -99 NA refused NA
# A tibble: 3 × 2
reason n
<chr> <int>
1 observed 491
2 refused 3
3 skipped 9
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
| import polars as pl
survey = pl.read_csv(
"data/practice/survey.csv",
infer_schema=False,
schema_overrides={"Duration (in seconds)": pl.Int64},
empty_string_is_null=True,
encoding="utf8",
)
agreement_scores = {
"Strongly disagree": 1,
"Disagree": 2,
"Neutral": 3,
"Agree": 4,
"Strongly agree": 5,
}
sat_3 = (
survey.select("ResponseId", item=pl.lit("SAT_3"), recorded=pl.col("SAT_3"))
.with_columns(
score=pl.col("recorded").replace_strict(agreement_scores, default=None)
)
.with_columns(
reason=pl.when(pl.col("recorded").is_null())
.then(pl.lit("skipped"))
.when(pl.col("recorded") == "-99")
.then(pl.lit("refused"))
.when(pl.col("score").is_null())
.then(pl.lit("invalid"))
.otherwise(pl.lit("observed")),
adjusted=6 - pl.col("score"),
)
)
sat_3.filter(pl.col("ResponseId").is_in(["R_hopQ1ccnJqGj", "R_7k2Xvb2KojVD"]))
sat_3.group_by("reason").agg(n=pl.len()).sort("reason")
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| shape: (2, 6)
┌────────────────┬───────┬──────────┬───────┬──────────┬──────────┐
│ ResponseId ┆ item ┆ recorded ┆ score ┆ reason ┆ adjusted │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ i64 ┆ str ┆ i64 │
╞════════════════╪═══════╪══════════╪═══════╪══════════╪══════════╡
│ R_hopQ1ccnJqGj ┆ SAT_3 ┆ Agree ┆ 4 ┆ observed ┆ 2 │
│ R_7k2Xvb2KojVD ┆ SAT_3 ┆ -99 ┆ null ┆ refused ┆ null │
└────────────────┴───────┴──────────┴───────┴──────────┴──────────┘
shape: (3, 2)
┌──────────┬─────┐
│ reason ┆ n │
│ --- ┆ --- │
│ str ┆ u32 │
╞══════════╪═════╡
│ observed ┆ 491 │
│ refused ┆ 3 │
│ skipped ┆ 9 │
└──────────┴─────┘
|
For response R_hopQ1ccnJqGj, the two working values for Agree are the agreement score of 4 and the adjusted score of 2. Comparing recorded with score checks the label conversion; comparing score with adjusted checks the reversal.
Response R_7k2Xvb2KojVD instead records -99. Its score and adjusted value are both missing, just as they are for a blank answer. The recorded and reason columns distinguish the three refusals from the nine skipped answers. The missing score alone cannot explain why an answer was not scored.
Trials and participant accuracy
Participant sub-001 pressed the correct key on the first practice trial and again on the first test trial. Which response counts toward test accuracy? For each participant, we count the keyboard trials in test blocks 1 through 4 and find the fraction answered correctly. That fraction is a derived result calculated from many trial records.
Trial numbers repeat across blocks and participants. In this file, participant, block, and trial together identify each keyboard trial. The first display uses that key to compare the first practice and test trials for sub-001. row_type distinguishes practice in block 0 from the test in block 1, and selected records inclusion in test accuracy.
In dplyr, case_when() labels the rows, including questionnaires. After filter(selected), summarise(.by = participant) counts the test trials and correct answers for each person.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| trials <- read_csv(
"data/practice/trials.csv",
col_types = cols_only(
participant = col_character(),
block = col_integer(),
trial = col_integer(),
trial_type = col_character(),
correct = col_integer()
),
na = "",
trim_ws = FALSE
)
trial_audit <- trials |>
mutate(
row_type = case_when(
trial_type == "survey" ~ "questionnaire",
block == 0 ~ "practice",
block %in% 1:4 ~ "test",
.default = "other"
),
selected = trial_type == "keyboard" & block %in% 1:4
)
filter(trial_audit, participant == "sub-001" & block %in% 0:1 & trial == 1)
count(trial_audit, row_type, selected)
participant_accuracy <- trial_audit |>
filter(selected) |>
summarise(n_test = n(), n_correct = sum(correct), .by = participant) |>
mutate(accuracy = n_correct / n_test)
filter(participant_accuracy, participant == "sub-001")
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| # A tibble: 2 × 7
participant block trial trial_type correct row_type selected
<chr> <int> <int> <chr> <int> <chr> <lgl>
1 sub-001 0 1 keyboard 1 practice FALSE
2 sub-001 1 1 keyboard 1 test TRUE
# A tibble: 3 × 3
row_type selected n
<chr> <lgl> <int>
1 practice FALSE 320
2 questionnaire FALSE 40
3 test TRUE 7680
# A tibble: 1 × 4
participant n_test n_correct accuracy
<chr> <int> <int> <dbl>
1 sub-001 192 180 0.938
|
In Polars, a pl.when() chain assigns row_type. filter() selects the keyboard trials in blocks 1 to 4 before group_by() and agg() count the trials and correct answers for each participant.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
| trials = pl.read_csv(
"data/practice/trials.csv",
columns=["participant", "block", "trial", "trial_type", "correct"],
infer_schema=False,
schema_overrides={"block": pl.Int64, "trial": pl.Int64, "correct": pl.Int64},
)
test_blocks = pl.col("block").is_in([1, 2, 3, 4])
trial_audit = trials.with_columns(
row_type=pl.when(pl.col("trial_type") == "survey")
.then(pl.lit("questionnaire"))
.when(pl.col("block") == 0)
.then(pl.lit("practice"))
.when(test_blocks)
.then(pl.lit("test"))
.otherwise(pl.lit("other")),
selected=(pl.col("trial_type") == "keyboard") & test_blocks,
)
trial_audit.filter(
(pl.col("participant") == "sub-001")
& pl.col("block").is_in([0, 1])
& (pl.col("trial") == 1)
)
trial_audit.group_by("row_type", "selected").agg(n=pl.len()).sort("row_type")
participant_accuracy = (
trial_audit.filter(pl.col("selected"))
.group_by("participant")
.agg(n_test=pl.len(), n_correct=pl.col("correct").sum())
.with_columns(accuracy=pl.col("n_correct") / pl.col("n_test"))
)
participant_accuracy.filter(pl.col("participant") == "sub-001")
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
| shape: (2, 7)
┌─────────────┬───────┬───────┬────────────┬─────────┬──────────┬──────────┐
│ participant ┆ block ┆ trial ┆ trial_type ┆ correct ┆ row_type ┆ selected │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 ┆ str ┆ i64 ┆ str ┆ bool │
╞═════════════╪═══════╪═══════╪════════════╪═════════╪══════════╪══════════╡
│ sub-001 ┆ 0 ┆ 1 ┆ keyboard ┆ 1 ┆ practice ┆ false │
│ sub-001 ┆ 1 ┆ 1 ┆ keyboard ┆ 1 ┆ test ┆ true │
└─────────────┴───────┴───────┴────────────┴─────────┴──────────┴──────────┘
shape: (3, 3)
┌───────────────┬──────────┬──────┐
│ row_type ┆ selected ┆ n │
│ --- ┆ --- ┆ --- │
│ str ┆ bool ┆ u32 │
╞═══════════════╪══════════╪══════╡
│ practice ┆ false ┆ 320 │
│ questionnaire ┆ false ┆ 40 │
│ test ┆ true ┆ 7680 │
└───────────────┴──────────┴──────┘
shape: (1, 4)
┌─────────────┬────────┬───────────┬──────────┐
│ participant ┆ n_test ┆ n_correct ┆ accuracy │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ i64 ┆ f64 │
╞═════════════╪════════╪═══════════╪══════════╡
│ sub-001 ┆ 192 ┆ 180 ┆ 0.9375 │
└─────────────┴────────┴───────────┴──────────┘
|
Both displayed trials of sub-001 were correct, but only the block 1 trial has selected set to true. It contributes one trial to n_test and one correct answer to n_correct. The practice trial contributes to neither count. For this participant, the selected rows give 180 correct answers out of 192 test trials, or 0.9375.
That single summary row no longer shows which trials contributed. The trial_audit table lists them, together with the practice rows excluded by the selection rule. It supplies the record-level evidence needed to check the denominator.
Keys and decision fields
For a survey score, ResponseId and item identify a single recorded answer. For participant accuracy, participant identifies the person’s rows in the trial file, and selected shows which ones counted. Table 19.1 shows which fields explain a missing score or a trial’s inclusion in the denominator.
Table 19.1. Keys and decision fields from recorded values to derived results.
| Step | Input | Output | Key | Decision field or rule |
|---|
| Label to score | recorded | score | ResponseId, item | reason |
| Score to adjusted value | score | adjusted | ResponseId, item | For SAT_3, adjusted = 6 - score |
| Select test trials | row in the trial file | selected | participant, block, trial for keyboard trials | Keyboard trial in blocks 1 to 4 |
| Test trials to accuracy | selected rows | n_test, n_correct, accuracy | participant | selected, correct |
A second calculation reports 0.94 for sub-001. That could be 0.9375 rounded to two decimal places. Did the two calculations count the same trials? Grouping this participant’s keyboard rows by row_type and selected separates the practice and test counts.
1
2
3
| sub_001 <- filter(trial_audit, participant == "sub-001" & trial_type == "keyboard")
summarise(sub_001, n = n(), n_correct = sum(correct), .by = c(row_type, selected))
sum(sub_001$correct) / nrow(sub_001)
|
1
2
3
4
5
6
| # A tibble: 2 × 4
row_type selected n n_correct
<chr> <lgl> <int> <int>
1 practice FALSE 8 8
2 test TRUE 192 180
[1] 0.94
|
1
2
3
4
5
6
7
| sub_001 = trial_audit.filter(
(pl.col("participant") == "sub-001") & (pl.col("trial_type") == "keyboard")
)
sub_001.group_by("row_type", "selected").agg(
n=pl.len(), n_correct=pl.col("correct").sum()
).sort("row_type")
sub_001["correct"].sum() / sub_001.height
|
1
2
3
4
5
6
7
8
9
10
| shape: (2, 4)
┌──────────┬──────────┬─────┬───────────┐
│ row_type ┆ selected ┆ n ┆ n_correct │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ bool ┆ u32 ┆ i64 │
╞══════════╪══════════╪═════╪═══════════╡
│ practice ┆ false ┆ 8 ┆ 8 │
│ test ┆ true ┆ 192 ┆ 180 │
└──────────┴──────────┴─────┴───────────┘
0.94
|
The eight practice trials were all correct. Including them gives 188 correct answers out of 200 keyboard trials, exactly 0.94. The test trials alone give 180 out of 192, or 0.9375.
19.2 Saving tables and reading them back
A CSV file can contain 0007 even when the table you read from it shows 7. Writing a table and reading it back is a round trip. Table 19.2 shows what should match the original row after that trip, from the four characters of its identifier to the half second in its timestamp.
Table 19.2. Expected values and column types after reading the constructed row back from a file.
| Column | Constructed value | Required result after rereading |
|---|
id | 0007 | the four characters 0007 as text |
score | a missing number | a missing value in a numeric column |
level | Agree | Agree in a column with five explicitly ordered levels |
onset | 12:24:21.500 in Asia/Seoul | the same instant to the millisecond, displayed in Asia/Seoul |
The R example starts with level as an ordered factor and onset parsed in Asia/Seoul. The first call to readr::write_csv() uses its default timestamp format. For the second file, format() converts onset to text before writing. %OS3 requests three decimal places, and %z writes the UTC offset. readLines() shows what reached each file, even when the tibble display hides part of the timestamp.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| original <- tibble(
id = "0007",
score = NA_real_,
level = factor("Agree", levels = agreement_levels, ordered = TRUE),
onset = ymd_hms("2024-03-15 12:24:21.500", tz = "Asia/Seoul")
)
original
dir.create("data/derived/ch19", recursive = TRUE, showWarnings = FALSE)
default_path <- "data/derived/ch19/row_0007_r_default.csv"
write_csv(original, default_path)
readLines(default_path)
onset_format <- "%Y-%m-%dT%H:%M:%OS3%z"
csv_path <- "data/derived/ch19/row_0007_r.csv"
original |>
mutate(onset = format(onset, onset_format)) |>
write_csv(csv_path)
readLines(csv_path)
|
1
2
3
4
5
6
7
| # A tibble: 1 × 4
id score level onset
<chr> <dbl> <ord> <dttm>
1 0007 NA Agree 2024-03-15 12:24:21
[1] "id,score,level,onset" "0007,NA,Agree,2024-03-15T03:24:21Z"
[1] "id,score,level,onset"
[2] "0007,NA,Agree,2024-03-15T12:24:21.500+0900"
|
The default file ends the timestamp at 21Z, losing the half second. The final Z marks UTC. The timestamp in the explicitly formatted file ends in .500+0900. What types will read_csv() assign to the columns in that second file if it has only the CSV text to go on?
1
2
3
4
5
6
7
8
9
10
11
12
13
| Rows: 1 Columns: 4
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (2): id, level
lgl (1): score
dttm (1): onset
ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# A tibble: 1 × 4
id score level onset
<chr> <lgl> <chr> <dttm>
1 0007 NA Agree 2024-03-15 03:24:21
|
readr::read_csv() reads 0007 as text, guesses that score is logical, and reads Agree as plain text. The file’s text is therefore insufficient to recover all the intended column types. For both CSV files, row_types specifies a numeric score and an ordered factor with the five agreement levels. In read_csv(), na = "NA" marks a missing value and %OS in col_datetime() accepts fractional seconds. with_tz() displays the parsed instant in Seoul time.
In the comparison below, default and csv name the two ways the files were written. Reading both with the same schema separates the effect of writing the timestamp from the effect of inferring column types. describe_round_trip() shows the instant in UTC to the millisecond and lists the display zone separately.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| row_types <- cols(
id = col_character(),
score = col_double(),
level = col_factor(levels = agreement_levels, ordered = TRUE),
onset = col_datetime(format = "%Y-%m-%dT%H:%M:%OS%z")
)
onset_zone <- "Asia/Seoul"
default_back <- read_csv(default_path, col_types = row_types, na = "NA") |>
mutate(onset = with_tz(onset, onset_zone))
csv_back <- read_csv(csv_path, col_types = row_types, na = "NA") |>
mutate(onset = with_tz(onset, onset_zone))
describe_round_trip <- function(table, version) {
tibble(
version = version,
id = table$id,
score = typeof(table$score),
missing = is.na(table$score),
order = is.ordered(table$level) &&
identical(levels(table$level), agreement_levels),
onset_utc = format(with_tz(table$onset, "UTC"), "%Y-%m-%d %H:%M:%OS3"),
zone = tz(table$onset)
)
}
round_trips <- bind_rows(
describe_round_trip(original, "original"),
describe_round_trip(default_back, "default"),
describe_round_trip(csv_back, "csv")
)
round_trips
|
1
2
3
4
5
6
| # A tibble: 3 × 7
version id score missing order onset_utc zone
<chr> <chr> <chr> <lgl> <lgl> <chr> <chr>
1 original 0007 double TRUE TRUE 2024-03-15 03:24:21.500 Asia/Seoul
2 default 0007 double TRUE TRUE 2024-03-15 03:24:21.000 Asia/Seoul
3 csv 0007 double TRUE TRUE 2024-03-15 03:24:21.500 Asia/Seoul
|
With those column types, both files read back with 0007 as text, a missing numeric score, and the declared category order. The default file gives 03:24:21.000 in UTC because the writer omitted the half second. In the other file, .500+0900 identifies the original instant. Seoul and Tokyo both use that offset, so the reading code specifies Asia/Seoul for display. It also gives the five levels in agreement_levels their order.
Parquet is a binary file format that stores each column’s type with its values. For the same constructed row, we can test which features the reader recovers without an explicit schema and which still require restoration.
If you need the nanoparquet package, install it with install.packages("nanoparquet") in the R Console. Its write_parquet() and read_parquet() functions write and reread the row, and read_parquet_schema() shows the types in the file. The parquet row shows what the reader returns directly; restored shows the effect of reapplying the factor order and display zone.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| library(nanoparquet)
parquet_path <- "data/derived/ch19/row_0007_r.parquet"
write_parquet(original, parquet_path)
parquet_back <- read_parquet(parquet_path)
parquet_back
levels(parquet_back$level)
read_parquet_schema(parquet_path) |>
select(name, type, repetition_type, converted_type)
restored <- parquet_back |>
mutate(
level = factor(level, levels = agreement_levels, ordered = TRUE),
onset = with_tz(onset, onset_zone)
)
round_trips <- bind_rows(
round_trips,
describe_round_trip(parquet_back, "parquet"),
describe_round_trip(restored, "restored")
)
round_trips
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| # A data frame: 1 × 4
id score level onset
<chr> <dbl> <fct> <dttm>
1 0007 NA Agree 2024-03-15 03:24:21
[1] "Strongly disagree" "Disagree" "Neutral"
[4] "Agree" "Strongly agree"
# A data frame: 5 × 4
name type repetition_type converted_type
<chr> <chr> <chr> <chr>
1 schema <NA> <NA> <NA>
2 id BYTE_ARRAY REQUIRED UTF8
3 score DOUBLE OPTIONAL <NA>
4 level BYTE_ARRAY REQUIRED UTF8
5 onset INT64 REQUIRED TIMESTAMP_MICROS
# A tibble: 5 × 7
version id score missing order onset_utc zone
<chr> <chr> <chr> <lgl> <lgl> <chr> <chr>
1 original 0007 double TRUE TRUE 2024-03-15 03:24:21.500 Asia/Seoul
2 default 0007 double TRUE TRUE 2024-03-15 03:24:21.000 Asia/Seoul
3 csv 0007 double TRUE TRUE 2024-03-15 03:24:21.500 Asia/Seoul
4 parquet 0007 double TRUE FALSE 2024-03-15 03:24:21.500 UTC
5 restored 0007 double TRUE TRUE 2024-03-15 03:24:21.500 Asia/Seoul
|
Here TIMESTAMP_MICROS records the instant, including the half second, without the Seoul zone name. The parquet row displays that instant in UTC. levels() lists all five labels in their declared sequence, but <fct> shows that level is an unordered factor. In the restored row, factor(..., ordered = TRUE) marks those levels as ordered, and with_tz() displays the same instant in Seoul time. The package topic help("nanoparquet-types", package = "nanoparquet") describes its factor metadata.
In the Polars table, id is text, score is numeric, and level is a pl.Enum with five ordered agreement levels. str.to_datetime() gives onset millisecond precision in Asia/Seoul. Path() names the output folder and mkdir() creates it. After write_csv(), the file text shows what was written and pl.read_csv() shows which types the reader infers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
| from pathlib import Path
agreement_levels = [
"Strongly disagree",
"Disagree",
"Neutral",
"Agree",
"Strongly agree",
]
agreement = pl.Enum(agreement_levels)
original = pl.DataFrame(
{
"id": ["0007"],
"score": [None],
"level": ["Agree"],
"onset": ["2024-03-15 12:24:21.500"],
},
schema={
"id": pl.String,
"score": pl.Float64,
"level": agreement,
"onset": pl.String,
},
).with_columns(
onset=pl.col("onset").str.to_datetime(
"%Y-%m-%d %H:%M:%S%.f", time_unit="ms", time_zone="Asia/Seoul"
)
)
original
derived = Path("data/derived/ch19")
derived.mkdir(parents=True, exist_ok=True)
csv_path = derived / "row_0007_py.csv"
original.write_csv(csv_path)
csv_path.read_text().splitlines()
pl.read_csv(csv_path)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| shape: (1, 4)
┌──────┬───────┬───────┬─────────────────────────────┐
│ id ┆ score ┆ level ┆ onset │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ enum ┆ datetime[ms, Asia/Seoul] │
╞══════╪═══════╪═══════╪═════════════════════════════╡
│ 0007 ┆ null ┆ Agree ┆ 2024-03-15 12:24:21.500 KST │
└──────┴───────┴───────┴─────────────────────────────┘
['id,score,level,onset', '0007,,Agree,2024-03-15T12:24:21.500+0900']
shape: (1, 4)
┌─────┬───────┬───────┬──────────────────────────────┐
│ id ┆ score ┆ level ┆ onset │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ str ┆ str │
╞═════╪═══════╪═══════╪══════════════════════════════╡
│ 7 ┆ null ┆ Agree ┆ 2024-03-15T12:24:21.500+0900 │
└─────┴───────┴───────┴──────────────────────────────┘
|
The file contains .500+0900, but inference turns 0007 into the integer 7 and reads the other columns as text. In pl.read_csv(), infer_schema=False reads id as text, and schema_overrides sets the numeric type for score and the ordered categories for level. The timestamp patterns %.f and %z read the fraction and offset, and converting to Seoul time restores the display zone.
The comparison checks the features specified before the round trip. order tests the enum against the five declared levels. onset_utc shows the instant to the millisecond, and zone names its display zone, so a change in display cannot be mistaken for a change in the instant.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
| onset_format = "%Y-%m-%dT%H:%M:%S%.f%z"
csv_back = pl.read_csv(
csv_path,
infer_schema=False,
schema_overrides={"score": pl.Float64, "level": agreement},
).with_columns(
onset=pl.col("onset")
.str.to_datetime(onset_format, time_unit="ms")
.dt.convert_time_zone("Asia/Seoul")
)
def describe_round_trip(table, version):
return table.select(
version=pl.lit(version),
id=pl.col("id"),
score=pl.lit(str(table.schema["score"])),
missing=pl.col("score").is_null(),
order=pl.lit(table.schema["level"] == agreement),
onset_utc=pl.col("onset")
.dt.convert_time_zone("UTC")
.dt.strftime("%Y-%m-%d %H:%M:%S%.3f"),
zone=pl.lit(table.schema["onset"].time_zone),
)
round_trips = pl.concat(
[describe_round_trip(original, "original"), describe_round_trip(csv_back, "csv")]
)
round_trips
|
1
2
3
4
5
6
7
8
9
| shape: (2, 7)
┌──────────┬──────┬─────────┬─────────┬───────┬─────────────────────────┬────────────┐
│ version ┆ id ┆ score ┆ missing ┆ order ┆ onset_utc ┆ zone │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ bool ┆ bool ┆ str ┆ str │
╞══════════╪══════╪═════════╪═════════╪═══════╪═════════════════════════╪════════════╡
│ original ┆ 0007 ┆ Float64 ┆ true ┆ true ┆ 2024-03-15 03:24:21.500 ┆ Asia/Seoul │
│ csv ┆ 0007 ┆ Float64 ┆ true ┆ true ┆ 2024-03-15 03:24:21.500 ┆ Asia/Seoul │
└──────────┴──────┴─────────┴─────────┴───────┴─────────────────────────┴────────────┘
|
The csv row now shows 0007, a missing Float64 score, the declared order, and the original instant displayed in Seoul time. The CSV reader needed the category order and zone name from the code.
These features require checks of both values and types. In Polars, equals() compares values and treats nulls in corresponding positions as equal. It can return true for columns of different types, so a separate comparison with row_schema checks the types.
1
2
3
4
5
6
7
8
9
10
| row_schema = pl.Schema(
{
"id": pl.String,
"score": pl.Float64,
"level": agreement,
"onset": pl.Datetime("ms", "Asia/Seoul"),
}
)
csv_back.schema == row_schema
csv_back.equals(original)
|
Parquet is a binary file format that stores each column’s type with its values. For the same row, pl.read_parquet_schema() shows the types in the file. Does Polars recover the values, the enum order, and the zone name without specifying them at import?
1
2
3
4
5
6
7
8
| parquet_path = derived / "row_0007_py.parquet"
original.write_parquet(parquet_path)
parquet_back = pl.read_parquet(parquet_path)
pl.read_parquet_schema(parquet_path)
parquet_back.schema == row_schema
parquet_back.equals(original)
round_trips = pl.concat([round_trips, describe_round_trip(parquet_back, "parquet")])
round_trips
|
1
2
3
4
5
6
7
8
9
10
11
12
13
| Schema({'id': String, 'score': Float64, 'level': Enum(categories=['Strongly disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly agree']), 'onset': Datetime(time_unit='ms', time_zone='Asia/Seoul')})
True
True
shape: (3, 7)
┌──────────┬──────┬─────────┬─────────┬───────┬─────────────────────────┬────────────┐
│ version ┆ id ┆ score ┆ missing ┆ order ┆ onset_utc ┆ zone │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ bool ┆ bool ┆ str ┆ str │
╞══════════╪══════╪═════════╪═════════╪═══════╪═════════════════════════╪════════════╡
│ original ┆ 0007 ┆ Float64 ┆ true ┆ true ┆ 2024-03-15 03:24:21.500 ┆ Asia/Seoul │
│ csv ┆ 0007 ┆ Float64 ┆ true ┆ true ┆ 2024-03-15 03:24:21.500 ┆ Asia/Seoul │
│ parquet ┆ 0007 ┆ Float64 ┆ true ┆ true ┆ 2024-03-15 03:24:21.500 ┆ Asia/Seoul │
└──────────┴──────┴─────────┴─────────┴───────┴─────────────────────────┴────────────┘
|
The stored schema includes all five enum categories in order and Datetime("ms", "Asia/Seoul"). Both comparisons return True. Polars reads back the original values, including Agree, with the expected column types. A round trip through a different writer or reader needs its own comparison of values and schema.
How can we tell whether timestamps that print alike agree to the millisecond? In R, as.numeric() gives seconds since 1970 for these date-times. Multiplying the difference from the original instant by 1,000 and rounding expresses it in whole milliseconds. In Polars, dt.epoch("ms") gives integer milliseconds directly.
1
2
3
| onsets <- c(original$onset, default_back$onset, csv_back$onset, restored$onset)
onsets
round((as.numeric(onsets) - as.numeric(original$onset)) * 1000)
|
1
2
3
| [1] "2024-03-15 12:24:21 KST" "2024-03-15 12:24:21 KST"
[3] "2024-03-15 12:24:21 KST" "2024-03-15 12:24:21 KST"
[1] 0 -500 0 0
|
1
2
3
| onsets = pl.concat([original, csv_back, parquet_back])["onset"]
onsets
(onsets.dt.epoch("ms") - original["onset"].dt.epoch("ms")[0]).to_list()
|
1
2
3
4
5
6
7
8
| shape: (3,)
Series: 'onset' [datetime[ms, Asia/Seoul]]
[
2024-03-15 12:24:21.500 KST
2024-03-15 12:24:21.500 KST
2024-03-15 12:24:21.500 KST
]
[0, 0, 0]
|
All four R timestamps print alike, yet the default CSV reread differs by −500 milliseconds. The explicitly formatted CSV and restored Parquet rows match. The Polars comparisons also give zero differences. Comparing the stored instants detects a loss that R’s ordinary display hides.
The old trial exports have a different limit. The first recorded onset for sub-001 ends at 09:54:27 in Korean time. What can three decimal places tell us when the recorded time stops at whole seconds?
1
2
3
4
5
6
7
8
9
10
11
| old_onset <- read_csv(
"data/raw/trials/sub-001_ses-1.csv",
col_types = cols(.default = col_character()),
na = "",
trim_ws = FALSE
) |>
select(Participant, Block, Trial, Time) |>
head(1) |>
mutate(onset = dmy_hms(Time, tz = onset_zone))
format(old_onset$onset, onset_format)
second(old_onset$onset)
|
1
2
| [1] "2024-03-26T09:54:27.000+0900"
[1] 27
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| old_onset = (
pl.read_csv("data/raw/trials/sub-001_ses-1.csv", infer_schema=False)
.select("Participant", "Block", "Trial", "Time")
.head(1)
.with_columns(
onset=pl.col("Time").str.to_datetime(
"%d/%m/%Y %H:%M:%S", time_unit="ms", time_zone="Asia/Seoul"
)
)
)
old_onset.select(
"Time",
written=pl.col("onset").dt.strftime("%Y-%m-%dT%H:%M:%S%.3f%z"),
millisecond=pl.col("onset").dt.millisecond(),
)
|
1
2
3
4
5
6
7
8
| shape: (1, 3)
┌─────────────────────┬──────────────────────────────┬─────────────┐
│ Time ┆ written ┆ millisecond │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i32 │
╞═════════════════════╪══════════════════════════════╪═════════════╡
│ 26/03/2024 09:54:27 ┆ 2024-03-26T09:54:27.000+0900 ┆ 0 │
└─────────────────────┴──────────────────────────────┴─────────────┘
|
The source records 09:54:27 to whole seconds. Formatting adds .000 even though the trial file gives no millisecond reading.
19.3 Checks that express the analytical definition
Saving and rereading a table can preserve its values even when those values have been assigned to the wrong people. In a deliberately faulty copy of the trial table, the 48 test trials from block 4 of sub-002 are assigned to sub-001. Both dplyr::if_else() and pl.when() change only the participant label. Could either the overall trial count or the overall number correct detect this error?
1
2
3
4
5
6
7
| test_trials <- filter(trial_audit, selected)
faulty_trials <- test_trials |>
mutate(
participant = if_else(participant == "sub-002" & block == 4, "sub-001", participant)
)
c(nrow(test_trials), nrow(faulty_trials))
c(sum(test_trials$correct), sum(faulty_trials$correct))
|
1
2
| [1] 7680 7680
[1] 7043 7043
|
1
2
3
4
5
6
7
8
| test_trials = trial_audit.filter(pl.col("selected"))
faulty_trials = test_trials.with_columns(
participant=pl.when((pl.col("participant") == "sub-002") & (pl.col("block") == 4))
.then(pl.lit("sub-001"))
.otherwise(pl.col("participant"))
)
(test_trials.height, faulty_trials.height)
(test_trials["correct"].sum(), faulty_trials["correct"].sum())
|
1
2
| (7680, 7680)
(7043, 7043)
|
The counts still add up to 7,680 test trials and 7,043 correct answers. Both participants still have trials under their own names, so a list of participants would miss the error too. The task calls for 192 test trials per completed run.
The checks must distinguish a complete set of participants from the correct number of trials for each person. In check_accuracy(), setequal() compares participant keys regardless of order or repetition, so n_distinct() and nrow() check uniqueness separately. The denominator check requires a nonmissing count of 192 for every participant.
Applying these checks to both accuracy tables shows which condition detects the reassigned trials. The filter then identifies the two affected participants. stopifnot() stops the script when a check fails and reports the name given to that condition.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| faulty_accuracy <- faulty_trials |>
summarise(n_test = n(), n_correct = sum(correct), .by = participant) |>
mutate(accuracy = n_correct / n_test)
expected_participants <- unique(trials$participant)
check_accuracy <- function(accuracy, expected) {
c(
coverage = setequal(accuracy$participant, expected),
unique_keys = n_distinct(accuracy$participant) == nrow(accuracy),
all_192 = all(!is.na(accuracy$n_test) & accuracy$n_test == 192)
)
}
check_accuracy(participant_accuracy, expected_participants)
check_accuracy(faulty_accuracy, expected_participants)
filter(faulty_accuracy, n_test != 192)
stopifnot("192 test trials per participant" = all(!is.na(participant_accuracy$n_test) & participant_accuracy$n_test == 192))
|
1
2
3
4
5
6
7
8
9
| coverage unique_keys all_192
TRUE TRUE TRUE
coverage unique_keys all_192
TRUE TRUE FALSE
# A tibble: 2 × 4
participant n_test n_correct accuracy
<chr> <int> <int> <dbl>
1 sub-001 240 221 0.921
2 sub-002 144 130 0.903
|
1
2
| # Deliberate error: a named check on the faulty counts
stopifnot("192 test trials per participant" = all(!is.na(faulty_accuracy$n_test) & faulty_accuracy$n_test == 192))
|
1
| Error: 192 test trials per participant
|
In Polars, group_by() and agg() count trials by their faulty participant labels. Coverage compares sorted unique identifiers with the expected list, while n_unique() == height checks that each appears only once. For denominators, comparing a missing count with 192 gives null, and all() skips nulls by default, so fill_null(False) turns that null into a failure. Python’s assert raises an AssertionError when its condition is false. The message after the comma identifies the failed check.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| faulty_accuracy = (
faulty_trials.group_by("participant")
.agg(n_test=pl.len(), n_correct=pl.col("correct").sum())
.with_columns(accuracy=pl.col("n_correct") / pl.col("n_test"))
)
expected_participants = trials["participant"].unique().sort().to_list()
def check_accuracy(accuracy, expected):
return {
"coverage": accuracy["participant"].unique().sort().to_list() == expected,
"unique_keys": accuracy["participant"].n_unique() == accuracy.height,
"all_192": (accuracy["n_test"] == 192).fill_null(False).all(),
}
check_accuracy(participant_accuracy, expected_participants)
check_accuracy(faulty_accuracy, expected_participants)
faulty_accuracy.filter(pl.col("n_test") != 192).sort("participant")
assert (participant_accuracy["n_test"] == 192).fill_null(False).all(), "192 test trials per participant"
|
1
2
3
4
5
6
7
8
9
10
11
| {'coverage': True, 'unique_keys': True, 'all_192': True}
{'coverage': True, 'unique_keys': True, 'all_192': False}
shape: (2, 4)
┌─────────────┬────────┬───────────┬──────────┐
│ participant ┆ n_test ┆ n_correct ┆ accuracy │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ i64 ┆ f64 │
╞═════════════╪════════╪═══════════╪══════════╡
│ sub-001 ┆ 240 ┆ 221 ┆ 0.920833 │
│ sub-002 ┆ 144 ┆ 130 ┆ 0.902778 │
└─────────────┴────────┴───────────┴──────────┘
|
1
2
| # Deliberate error: an assertion on the faulty counts
assert (faulty_accuracy["n_test"] == 192).fill_null(False).all(), "192 test trials per participant"
|
1
| AssertionError: 192 test trials per participant
|
All expected participants appear once in the faulty result. sub-001 has 240 test trials, 48 more than the required 192. sub-002 has 144, exactly 48 fewer. The two differences cancel in the grand total.
Keys of a lookup
Each trial should match at most one stimulus definition. In stimuli.csv, both S09 rows specify the word green. One gives it red ink and the other green ink. Both colors are allowed, so checking the ink values would miss the conflict. A check for repeated stimulus keys can stop the join before a trial acquires both definitions.
1
2
3
4
5
6
7
| stimuli <- read_csv(
"data/practice/stimuli.csv",
col_types = cols(.default = col_character()),
na = "",
trim_ws = FALSE
)
c(rows = nrow(stimuli), stimuli = n_distinct(stimuli$stim))
|
1
2
| # Deliberate error: the lookup key checked before any join
stopifnot("one row per stimulus" = n_distinct(stimuli$stim) == nrow(stimuli))
|
1
| Error: one row per stimulus
|
1
2
| stimuli = pl.read_csv("data/practice/stimuli.csv", infer_schema=False)
(stimuli.height, stimuli["stim"].n_unique())
|
1
2
| # Deliberate error: the lookup key checked before any join
assert stimuli["stim"].is_unique().all(), "one row per stimulus"
|
1
| AssertionError: one row per stimulus
|
The 17 rows contain only 16 distinct stimulus keys. Every trial with S09 would match both definitions in the file. Choosing the intended ink color requires the stimulus design.
Comparing the two languages
Do the R and Python calculations give the same accuracy for every participant? The two calculations may return participants in different orders. Matching by participant places the counts for each person side by side, allowing a comparison of the records represented as well as the proportions.
The R line below saves the reference table. For readers following Python alone, the book project includes data/derived/ch19/participant_accuracy_r.csv. If you unpacked only example_data.zip, copy that file from the project to the same path under book.
pl.read_csv() reads the R table with an explicit schema. A full join includes keys from either table, coalesce=True combines the key columns, and validate="1:1" rejects repeated participant keys. Counts should match exactly. The tolerance for proportions, 1e-12, allows for floating-point rounding and is far smaller than the change of 1/192 from scoring one more of the 192 trials as correct.
1
| write_csv(participant_accuracy, "data/derived/ch19/participant_accuracy_r.csv")
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| r_accuracy = pl.read_csv(
derived / "participant_accuracy_r.csv",
schema_overrides={
"participant": pl.String,
"n_test": pl.UInt32,
"n_correct": pl.Int64,
"accuracy": pl.Float64,
},
)
compared = participant_accuracy.join(
r_accuracy, on="participant", how="full", coalesce=True, suffix="_r", validate="1:1"
)
compared.select(
rows=pl.len(),
unmatched=(pl.col("n_test").is_null() | pl.col("n_test_r").is_null()).sum(),
same_counts=(
(pl.col("n_test") == pl.col("n_test_r"))
& (pl.col("n_correct") == pl.col("n_correct_r"))
).all(),
max_difference=(pl.col("accuracy") - pl.col("accuracy_r")).abs().max(),
within_tolerance=((pl.col("accuracy") - pl.col("accuracy_r")).abs() <= 1e-12).all(),
)
|
1
2
3
4
5
6
7
8
| shape: (1, 5)
┌──────┬───────────┬─────────────┬────────────────┬──────────────────┐
│ rows ┆ unmatched ┆ same_counts ┆ max_difference ┆ within_tolerance │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ u32 ┆ u32 ┆ bool ┆ f64 ┆ bool │
╞══════╪═══════════╪═════════════╪════════════════╪══════════════════╡
│ 40 ┆ 0 ┆ true ┆ 0.0 ┆ true │
└──────┴───────────┴─────────────┴────────────────┴──────────────────┘
|
The zero in unmatched means all 40 participants have a row in both tables. That check matters because all() skips null comparisons for participants missing from one side. For the 40 matched pairs, the trial and correct-answer counts agree exactly, and the largest difference in accuracy is zero.
The saved participant_accuracy_r.csv contains one row per participant. Could you recover those rows in a fresh session, without using any objects from the earlier calculations? The rerun starts from data/practice/trials.csv and uses the same definition: keyboard rows in blocks 1 to 4 are test trials, and accuracy is correct test trials divided by all test trials.
1
| readLines("data/derived/ch19/participant_accuracy_r.csv", n = 3)
|
1
2
3
| [1] "participant,n_test,n_correct,accuracy"
[2] "sub-001,192,180,0.9375"
[3] "sub-002,192,171,0.890625"
|
1
| Path("data/derived/ch19/participant_accuracy_r.csv").read_text().splitlines()[:3]
|
1
| ['participant,n_test,n_correct,accuracy', 'sub-001,192,180,0.9375', 'sub-002,192,171,0.890625']
|
Table 19.3 shows the order of the rerun. If the script uses a table it never creates or reads, it will stop in a fresh session. Every result must therefore follow from an input that the script names and a calculation that it performs.
The first check establishes that the input file has not changed. A checksum is a value calculated from a file’s bytes to detect changes. Before importing the trials, the script computes this value with SHA-256 and compares it with the checksum recorded for the supplied file. A mismatch stops the run. Once the participant checks pass, the script writes a separate CSV. The final comparison pairs the newly calculated rows in memory with the rows read from the saved reference file.
Table 19.3. Inputs, results, and checks for recomputing participant accuracy from the trial file.
| Step | Reads | Result | Rule or calculation |
|---|
| Check the input file | trials_path, trials_sha256 | error on mismatch | Compare the file’s SHA-256 checksum with the recorded checksum |
| Import | file at trials_path | trials | Four declared columns |
| Select | trials | test_trials | keyboard rows in blocks 1 to 4 |
| Aggregate | test_trials | accuracy | n_test and n_correct per participant |
| Ratio | n_correct, n_test | column accuracy | n_correct / n_test |
| Check participant counts | accuracy, trials | error if a check fails | Every participant appears once with 192 test trials |
| Save | accuracy | file at rerun_path | CSV with a header row |
| Compare | saved_path, accuracy | compared | matched by participant |
The book project includes both scripts in its code folder. If you started with the data archive, save the listing for your language in book/code and make sure the reference CSV is at data/derived/ch19/participant_accuracy_r.csv under book.
In code/ch19_accuracy.R, tools::sha256sum() computes the input checksum. In the final join, relationship = "one-to-one" requires each row to match at most one row in the other table. With the script open in Positron and book as the working directory, choose Interpreter: Restart Active Interpreter Session, then R: Source R File.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
| # code/ch19_accuracy.R: participant accuracy from the recorded trial file
# Run in a new R session with the book folder as the working directory.
library(tidyverse)
trials_path <- "data/practice/trials.csv"
trials_sha256 <- "347214cc35634ca1fcf04958e86fc7bd6c1fa736c3773303932fd24851d776f1"
saved_path <- "data/derived/ch19/participant_accuracy_r.csv"
rerun_path <- "data/derived/ch19/participant_accuracy_rerun_r.csv"
stopifnot("unchanged trial file" = tools::sha256sum(trials_path) == trials_sha256)
trials <- read_csv(
trials_path,
col_types = cols_only(
participant = col_character(),
block = col_integer(),
trial_type = col_character(),
correct = col_integer()
),
na = "",
trim_ws = FALSE
)
test_trials <- filter(trials, trial_type == "keyboard" & block %in% 1:4)
accuracy <- test_trials |>
summarise(n_test = n(), n_correct = sum(correct), .by = participant) |>
mutate(accuracy = n_correct / n_test)
stopifnot(
"every participant appears" = setequal(accuracy$participant, trials$participant),
"one row per participant" = n_distinct(accuracy$participant) == nrow(accuracy),
"192 test trials per participant" = all(!is.na(accuracy$n_test) & accuracy$n_test == 192)
)
write_csv(accuracy, rerun_path)
saved <- read_csv(
saved_path,
col_types = cols(
participant = col_character(),
n_test = col_integer(),
n_correct = col_integer(),
accuracy = col_double()
)
)
compared <- full_join(
saved,
accuracy,
by = join_by(participant),
suffix = c("_saved", "_rerun"),
relationship = "one-to-one"
)
print(summarise(
compared,
participants = n(),
unmatched = sum(is.na(n_test_saved) | is.na(n_test_rerun)),
same_counts = all(n_test_saved == n_test_rerun & n_correct_saved == n_correct_rerun),
max_difference = max(abs(accuracy_saved - accuracy_rerun))
))
|
1
2
3
4
| # A tibble: 1 × 4
participants unmatched same_counts max_difference
<int> <int> <lgl> <dbl>
1 40 0 TRUE 0
|
The rerun gives the same trial and correct-answer counts for all 40 participants, and the proportions match exactly. Restarting clears the earlier objects. The new session uses the same R installation and packages.
In code/ch19_accuracy.py, the standard-library hashlib module computes the input checksum from read_bytes(), and hexdigest() returns the text for the assertion. The pipeline rebuilds accuracy from four source columns and sorts participants before saving. Its full join compares the saved R table with the new result, requiring unique participant keys. With the script open in Positron and book as the working directory, choose Interpreter: Restart Active Interpreter Session, then Python: Run Python File in Console.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
| # code/ch19_accuracy.py: participant accuracy from the recorded trial file
# Run in a new Python session with the book folder as the working directory.
import hashlib
from pathlib import Path
import polars as pl
trials_path = Path("data/practice/trials.csv")
trials_sha256 = "347214cc35634ca1fcf04958e86fc7bd6c1fa736c3773303932fd24851d776f1"
saved_path = Path("data/derived/ch19/participant_accuracy_r.csv")
rerun_path = Path("data/derived/ch19/participant_accuracy_rerun_py.csv")
checksum = hashlib.sha256(trials_path.read_bytes()).hexdigest()
assert checksum == trials_sha256, "unchanged trial file"
trials = pl.read_csv(
trials_path,
columns=["participant", "block", "trial_type", "correct"],
infer_schema=False,
schema_overrides={"block": pl.Int64, "correct": pl.Int64},
)
test_trials = trials.filter(
(pl.col("trial_type") == "keyboard") & pl.col("block").is_in([1, 2, 3, 4])
)
accuracy = (
test_trials.group_by("participant")
.agg(n_test=pl.len(), n_correct=pl.col("correct").sum())
.with_columns(accuracy=pl.col("n_correct") / pl.col("n_test"))
.sort("participant")
)
expected = trials["participant"].unique().sort().to_list()
participants = accuracy["participant"]
assert participants.unique().sort().to_list() == expected, "every participant appears"
assert participants.n_unique() == accuracy.height, "one row per participant"
assert (accuracy["n_test"] == 192).fill_null(False).all(), "192 test trials per participant"
accuracy.write_csv(rerun_path)
saved = pl.read_csv(
saved_path,
schema_overrides={
"participant": pl.String,
"n_test": pl.UInt32,
"n_correct": pl.Int64,
"accuracy": pl.Float64,
},
)
compared = saved.join(
accuracy,
on="participant",
how="full",
coalesce=True,
suffix="_rerun",
validate="1:1",
)
summary = compared.select(
participants=pl.len(),
unmatched=(pl.col("n_test").is_null() | pl.col("n_test_rerun").is_null()).sum(),
same_counts=(
(pl.col("n_test") == pl.col("n_test_rerun"))
& (pl.col("n_correct") == pl.col("n_correct_rerun"))
).all(),
max_difference=(pl.col("accuracy") - pl.col("accuracy_rerun")).abs().max(),
)
print(summary)
|
1
2
3
4
5
6
7
8
| shape: (1, 4)
┌──────────────┬───────────┬─────────────┬────────────────┐
│ participants ┆ unmatched ┆ same_counts ┆ max_difference │
│ --- ┆ --- ┆ --- ┆ --- │
│ u32 ┆ u32 ┆ bool ┆ f64 │
╞══════════════╪═══════════╪═════════════╪════════════════╡
│ 40 ┆ 0 ┆ true ┆ 0.0 │
└──────────────┴───────────┴─────────────┴────────────────┘
|
The Python rerun matches the saved participant counts and proportions.
If the trial file’s checksum differs from the recorded checksum, its bytes have changed. If the script finishes but a participant’s accuracy differs, comparing that person’s trial and correct-answer counts with the saved counts shows whether the difference arose before division.
These runs used R 4.6.1 with readr 2.2.0 and dplyr 1.2.1, and Python 3.15.2 with Polars 2.1.0. Package defaults can change between versions. Here the proportions written by readr::write_csv() read back to the same values used in the calculation.
The rerun starts with the supplied synthetic trial file. Recreating the trials themselves would require the program that generated them, which the archive does not include.