Two participants restarted the Stroop task, so combining every trial file would count part of their performance twice. Describing each person’s performance requires selecting one complete run and determining how its responses should be scored. Accuracy and mean reaction time also need different inclusion rules: a correct response can contribute to accuracy even when its recorded time is unusable. We assemble the analysis from the session files in this chapter, beginning with an inventory and a common representation of their records. We then select runs, resolve stimulus descriptions, and summarize performance by condition before comparing conditions and combining the results with participants’ questionnaire answers.
21.1 Inventorying and harmonizing session exports
An empty file and a failed import can both contribute no trial rows, so the combined table alone cannot show what happened to every source. We first list the session files in data/raw/trials/, including the empty export. The pattern sub-*.csv matches those files, and the header of each nonempty file identifies its export format.
1
2
3
4
5
6
7
| library(tidyverse)
trial_dir <- "data/raw/trials"
folder_files <- list.files(trial_dir)
trial_paths <- Sys.glob(file.path(trial_dir, "sub-*.csv"))
c(folder = length(folder_files), participant_files = length(trial_paths))
setdiff(folder_files, basename(trial_paths))
|
1
2
3
| folder participant_files
44 43
[1] "stimuli.csv"
|
1
2
3
4
5
6
7
8
9
10
11
| import re
from pathlib import Path
import polars as pl
trial_dir = Path("data/raw/trials")
folder_files = sorted(path.name for path in trial_dir.iterdir())
trial_paths = sorted(trial_dir.glob("sub-*.csv"))
participant_names = [path.name for path in trial_paths]
(len(folder_files), len(trial_paths))
[name for name in folder_files if name not in participant_names]
|
1
2
| (44, 43)
['stimuli.csv']
|
Of the 44 files, 43 match the pattern. The other file is the stimulus lookup, stimuli.csv. The exports for sub-001 to sub-005 use older column names. Table 21.1 maps both formats to the columns in the combined table.
The filename identifies the participant, session, and run. A session is a lab visit, and a run is one attempt at the task during that visit. A filename without a run suffix denotes the first attempt, and _run-2 denotes the second. In the combined table, file and source_row locate each record in the original export, counting the first data row as 1.
Table 21.1. How the old and new session exports map to fields in the combined table.
| Combined field | Old export | New export | Meaning |
|---|
file, source_row | file name, row position | file name, row position | where the record was read |
run_recorded, run | number in the run suffix | same filename convention | without a suffix, run_recorded is missing and run is 1 |
participant | file name | file name | identity for analysis |
participant_recorded | Participant | participant | identity written in the file |
session, block, trial, trial_type, stim, resp, response_json | Session, Block, Trial, TrialType, Stim, Resp, Survey | same names as the combined fields | recorded text |
rt | RT_ms | rt | milliseconds recorded as text, from stimulus onset to key press on a keyboard trial or time on the questionnaire screen |
correct_recorded, correct | Correct, True or False | correct, 1 or 0 | recorded text, then 1 or 0 |
time_recorded, onset, time_precision | Time, day first, whole seconds | timestamp, year first, milliseconds | recorded text, instant in Korean time, recorded precision |
version | old header | new header | mapping applied |
The inventory distinguishes the reasons a file contributes no records. A zero-byte file is verified empty. A nonempty file with an unrecognized header is listed separately. For recognized headers, map2() passes each path and its schema to read_export(). If that function raises an error, tryCatch() returns NULL. compact() removes that NULL from exports, and the inventory marks the file as failed read.
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
| file_pattern <- "^(sub-[0-9]{3})_ses-([0-9]+)(?:_run-([0-9]+))?\\.csv\\z"
name_parts <- str_match(basename(trial_paths), file_pattern)
old_header <- paste0(
"Participant,Session,Block,Trial,TrialType,Stim,Resp,Correct,RT_ms,Time,",
"Survey"
)
new_header <- paste0(
"participant,session,block,trial,trial_type,stim,resp,correct,rt,timestamp,",
"response_json"
)
first_line <- function(path) {
if (file.size(path) == 0) NA_character_ else read_lines(path, n_max = 1)
}
inventory <- tibble(
path = trial_paths,
file = basename(trial_paths),
file_participant = name_parts[, 2],
run_recorded = name_parts[, 4],
run = coalesce(as.integer(run_recorded), 1L),
bytes = file.size(trial_paths),
header = map_chr(trial_paths, first_line)
) |>
mutate(
version = case_when(header == old_header ~ "old", header == new_header ~ "new"),
status = case_when(
bytes == 0 ~ "verified empty",
is.na(version) ~ "unrecognized header",
.default = "to read"
)
)
|
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
| old_to_canonical <- c(
participant_recorded = "Participant",
session = "Session",
block = "Block",
trial = "Trial",
trial_type = "TrialType",
stim = "Stim",
resp = "Resp",
correct_recorded = "Correct",
rt = "RT_ms",
time_recorded = "Time",
response_json = "Survey"
)
new_to_canonical <- c(
participant_recorded = "participant",
correct_recorded = "correct",
time_recorded = "timestamp"
)
mappings <- list(old = old_to_canonical, new = new_to_canonical)
read_export <- function(path, version) {
read_csv(
path,
col_types = cols(.default = col_character()),
na = "",
trim_ws = FALSE
) |>
rename(all_of(mappings[[version]])) |>
mutate(
file = basename(path),
source_row = row_number(),
version = version,
.before = 1
)
}
to_read <- filter(inventory, status == "to read")
exports <- map2(to_read$path, to_read$version, \(path, version) {
tryCatch(read_export(path, version), error = \(e) NULL)
})
names(exports) <- to_read$file
exports <- compact(exports)
inventory <- inventory |>
mutate(
rows = map_int(file, \(f) NROW(exports[[f]])),
status = case_when(
status != "to read" ~ status,
file %in% names(exports) ~ "read",
.default = "failed read"
)
)
inventory |>
summarise(files = n(), rows = sum(rows), .by = c(status, version))
identical(names(exports[["sub-001_ses-1.csv"]]), names(exports[["sub-006_ses-1.csv"]]))
|
1
2
3
4
5
6
7
| # A tibble: 3 × 4
status version files rows
<chr> <chr> <int> <int>
1 read old 5 1005
2 read new 37 7147
3 verified empty <NA> 1 0
[1] TRUE
|
Five old and 37 new files contributed records. sub-041_ses-1.csv is empty. The final TRUE confirms that the two example tables now share column names.
Their values also need a common interpretation. The old True and False correspond to the new 1 and 0. Both clocks use Korean time, but the old dates start with the day and the new ones with the year. time_precision distinguishes readings recorded to seconds from those recorded to milliseconds.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| align_values <- function(records) {
old <- records$version[1] == "old"
records |>
mutate(
correct = recode_values(
correct_recorded,
from = c("True", "False", "1", "0"),
to = c(1L, 0L, 1L, 0L)
),
onset = if (old) {
dmy_hms(time_recorded, tz = "Asia/Seoul")
} else {
ymd_hms(time_recorded, tz = "Asia/Seoul")
},
time_precision = if (old) "second" else "millisecond"
)
}
exports <- map(exports, align_values)
example_files <- c("sub-001_ses-1.csv", "sub-006_ses-1.csv")
example_rows <- bind_rows(exports[example_files]) |>
filter(block == "1", trial == "1")
select(example_rows, file, source_row, correct_recorded, correct)
select(example_rows, file, time_recorded, onset, time_precision)
format(example_rows$onset, "%H:%M:%OS3 %Z")
|
1
2
3
4
5
6
7
8
9
10
11
| # A tibble: 2 × 4
file source_row correct_recorded correct
<chr> <int> <chr> <int>
1 sub-001_ses-1.csv 9 True 1
2 sub-006_ses-1.csv 9 1 1
# A tibble: 2 × 4
file time_recorded onset time_precision
<chr> <chr> <dttm> <chr>
1 sub-001_ses-1.csv 26/03/2024 09:55:11 2024-03-26 09:55:11 second
2 sub-006_ses-1.csv 2024-03-15 12:25:08.549 2024-03-15 12:25:08 millisecond
[1] "09:55:11.000 KST" "12:25:08.549 KST"
|
The .549 in the new export was recorded by the task. Formatting the old time to three decimal places adds .000 to a reading recorded only to the second.
In the filename match, parts.group(1) gives the participant and parts.group(3) is None when there is no run suffix. The inventory records a null header for a zero-byte file and identifies each recognized export format from its header.
read_export() uses the field names for that format. A successful read adds a table to exports under its filename. If that call raises a Polars or file I/O error, the file remains in the inventory as failed read.
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
| file_pattern = r"(sub-[0-9]{3})_ses-([0-9]+)(?:_run-([0-9]+))?\.csv"
old_header = (
"Participant,Session,Block,Trial,TrialType,Stim,Resp,Correct,RT_ms,Time,Survey"
)
new_header = (
"participant,session,block,trial,trial_type,stim,resp,correct,rt,timestamp,"
"response_json"
)
entries = []
for path in trial_paths:
parts = re.fullmatch(file_pattern, path.name)
size = path.stat().st_size
header = None
if size > 0:
header = path.read_text().splitlines()[0]
entries.append(
{
"path": str(path),
"file": path.name,
"file_participant": parts.group(1),
"run_recorded": parts.group(3),
"bytes": size,
"header": header,
}
)
inventory_schema = {
"path": pl.String,
"file": pl.String,
"file_participant": pl.String,
"run_recorded": pl.String,
"bytes": pl.Int64,
"header": pl.String,
}
inventory = (
pl.DataFrame(entries, schema=inventory_schema)
.with_columns(
run=pl.col("run_recorded").cast(pl.Int64).fill_null(1),
version=pl.when(pl.col("header") == old_header)
.then(pl.lit("old"))
.when(pl.col("header") == new_header)
.then(pl.lit("new")),
)
.with_columns(
status=pl.when(pl.col("bytes") == 0)
.then(pl.lit("verified empty"))
.when(pl.col("version").is_null())
.then(pl.lit("unrecognized header"))
.otherwise(pl.lit("to read"))
)
)
|
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
| old_to_canonical = {
"Participant": "participant_recorded",
"Session": "session",
"Block": "block",
"Trial": "trial",
"TrialType": "trial_type",
"Stim": "stim",
"Resp": "resp",
"Correct": "correct_recorded",
"RT_ms": "rt",
"Time": "time_recorded",
"Survey": "response_json",
}
new_to_canonical = {
"participant": "participant_recorded",
"correct": "correct_recorded",
"timestamp": "time_recorded",
}
mappings = {"old": old_to_canonical, "new": new_to_canonical}
def read_export(path, version):
return (
pl.read_csv(path, infer_schema=False)
.rename(mappings[version])
.with_row_index("source_row", offset=1)
.with_columns(file=pl.lit(Path(path).name), version=pl.lit(version))
)
to_read = inventory.filter(pl.col("status") == "to read")
exports = {}
for path, file, version in zip(to_read["path"], to_read["file"], to_read["version"]):
try:
exports[file] = read_export(path, version)
except (pl.exceptions.PolarsError, OSError):
pass
row_counts = {}
for file in exports:
row_counts[file] = exports[file].height
inventory = inventory.with_columns(
rows=pl.col("file").replace_strict(row_counts, default=0, return_dtype=pl.Int64),
status=pl.when(pl.col("status") != "to read")
.then(pl.col("status"))
.when(pl.col("file").is_in(list(exports)))
.then(pl.lit("read"))
.otherwise(pl.lit("failed read")),
)
inventory.group_by("status", "version").agg(
files=pl.len(), rows=pl.col("rows").sum()
).sort("status", "version")
exports["sub-001_ses-1.csv"].columns == exports["sub-006_ses-1.csv"].columns
|
1
2
3
4
5
6
7
8
9
10
11
| shape: (3, 4)
┌────────────────┬─────────┬───────┬──────┐
│ status ┆ version ┆ files ┆ rows │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ u32 ┆ i64 │
╞════════════════╪═════════╪═══════╪══════╡
│ read ┆ new ┆ 37 ┆ 7147 │
│ read ┆ old ┆ 5 ┆ 1005 │
│ verified empty ┆ null ┆ 1 ┆ 0 │
└────────────────┴─────────┴───────┴──────┘
True
|
The Python inventory accounts for five old files, 37 new files, and one empty file. The final True shows that renaming gives an old and a new export the same column names.
align_values() then maps correctness codes and chooses the timestamp format by version. For either format, str.to_datetime() uses time_unit="ms" and time_zone="Asia/Seoul" so the tables can be stacked. The time_precision field records whether the source file gave seconds or milliseconds; storing both with a millisecond type does not change their recorded precision.
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
| correct_codes = {"True": 1, "False": 0, "1": 1, "0": 0}
time_formats = {"old": "%d/%m/%Y %H:%M:%S", "new": "%Y-%m-%d %H:%M:%S%.3f"}
precisions = {"old": "second", "new": "millisecond"}
def align_values(records):
version = records["version"][0]
return records.with_columns(
correct=pl.col("correct_recorded").replace_strict(
correct_codes, default=None, return_dtype=pl.Int64
),
onset=pl.col("time_recorded").str.to_datetime(
time_formats[version], time_unit="ms", time_zone="Asia/Seoul"
),
time_precision=pl.lit(precisions[version]),
)
for file in exports:
exports[file] = align_values(exports[file])
example_rows = pl.concat(
[exports["sub-001_ses-1.csv"], exports["sub-006_ses-1.csv"]], how="vertical"
).filter((pl.col("block") == "1") & (pl.col("trial") == "1"))
example_rows.select("file", "source_row", "correct_recorded", "correct")
example_rows.select("file", "time_recorded", "onset", "time_precision")
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| shape: (2, 4)
┌───────────────────┬────────────┬──────────────────┬─────────┐
│ file ┆ source_row ┆ correct_recorded ┆ correct │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ str ┆ i64 │
╞═══════════════════╪════════════╪══════════════════╪═════════╡
│ sub-001_ses-1.csv ┆ 9 ┆ True ┆ 1 │
│ sub-006_ses-1.csv ┆ 9 ┆ 1 ┆ 1 │
└───────────────────┴────────────┴──────────────────┴─────────┘
shape: (2, 4)
┌───────────────────┬─────────────────────────┬─────────────────────────────┬────────────────┐
│ file ┆ time_recorded ┆ onset ┆ time_precision │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ datetime[ms, Asia/Seoul] ┆ str │
╞═══════════════════╪═════════════════════════╪═════════════════════════════╪════════════════╡
│ sub-001_ses-1.csv ┆ 26/03/2024 09:55:11 ┆ 2024-03-26 09:55:11 KST ┆ second │
│ sub-006_ses-1.csv ┆ 2024-03-15 12:25:08.549 ┆ 2024-03-15 12:25:08.549 KST ┆ millisecond │
└───────────────────┴─────────────────────────┴─────────────────────────────┴────────────────┘
|
Identity from the file name
Every row in sub-023_ses-1.csv names sub-032, who also has a file. The filenames identify the participants correctly in these exports. Grouping by the ID inside the files would combine two people’s trials. The join assigns participant and run from the filename, while participant_recorded shows the original ID and id_corrected marks a discrepancy.
1
2
3
4
5
6
7
8
| identity <- select(inventory, file, participant = file_participant, run_recorded, run)
exports <- map(exports, \(records) {
records |>
left_join(identity, by = join_by(file), relationship = "many-to-one") |>
mutate(id_corrected = participant != participant_recorded)
})
bind_rows(exports[c("sub-023_ses-1.csv", "sub-032_ses-1.csv")]) |>
count(file, participant, participant_recorded, id_corrected)
|
1
2
3
4
5
| # A tibble: 2 × 5
file participant participant_recorded id_corrected n
<chr> <chr> <chr> <lgl> <int>
1 sub-023_ses-1.csv sub-023 sub-032 TRUE 201
2 sub-032_ses-1.csv sub-032 sub-032 FALSE 201
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| identity = inventory.select(
"file", "run_recorded", "run", participant=pl.col("file_participant")
)
for file in exports:
exports[file] = (
exports[file]
.join(identity, on="file", how="left", validate="m:1")
.with_columns(
id_corrected=pl.col("participant") != pl.col("participant_recorded")
)
)
pl.concat(
[exports["sub-023_ses-1.csv"], exports["sub-032_ses-1.csv"]], how="vertical"
).group_by("file", "participant", "participant_recorded", "id_corrected").agg(
n=pl.len()
).sort("file")
|
1
2
3
4
5
6
7
8
9
| shape: (2, 5)
┌───────────────────┬─────────────┬──────────────────────┬──────────────┬─────┐
│ file ┆ participant ┆ participant_recorded ┆ id_corrected ┆ n │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ bool ┆ u32 │
╞═══════════════════╪═════════════╪══════════════════════╪══════════════╪═════╡
│ sub-023_ses-1.csv ┆ sub-023 ┆ sub-032 ┆ true ┆ 201 │
│ sub-032_ses-1.csv ┆ sub-032 ┆ sub-032 ┆ false ┆ 201 │
└───────────────────┴─────────────┴──────────────────────┴──────────────┴─────┘
|
Combining the records
The correction assigns the 201 rows in sub-023_ses-1.csv to sub-023. After bind_rows() stacks the R tables, the total should match both the inventory’s row count and the number of distinct file and source_row pairs. Counts by file and run distinguish the two attempts for each participant who restarted.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| trials <- bind_rows(exports)
c(
rows = nrow(trials),
contributed = sum(inventory$rows),
sources = n_distinct(trials$file, trials$source_row),
corrected = sum(trials$id_corrected),
from_empty = sum(trials$file == "sub-041_ses-1.csv")
)
trials |>
filter(participant %in% c("sub-007", "sub-018")) |>
count(participant, run, run_recorded, file)
inventory |>
filter(status != "read") |>
select(file, bytes, status, rows)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
| rows contributed sources corrected from_empty
8152 8152 8152 201 0
# A tibble: 4 × 5
participant run run_recorded file n
<chr> <int> <chr> <chr> <int>
1 sub-007 1 <NA> sub-007_ses-1.csv 56
2 sub-007 2 2 sub-007_ses-1_run-2.csv 201
3 sub-018 1 <NA> sub-018_ses-1.csv 56
4 sub-018 2 2 sub-018_ses-1_run-2.csv 201
# A tibble: 1 × 4
file bytes status rows
<chr> <dbl> <chr> <int>
1 sub-041_ses-1.csv 0 verified empty 0
|
pl.concat(..., how="vertical") stacks tables with matching column names, order, and types. The resulting row count should equal the inventory total and the number of distinct file/row pairs. Restarted runs have separate counts. The empty file appears only in the inventory.
1
2
3
4
5
6
7
8
9
10
11
12
| trials = pl.concat([exports[file] for file in exports], how="vertical")
{
"rows": trials.height,
"contributed": inventory["rows"].sum(),
"sources": trials.select("file", "source_row").n_unique(),
"corrected": trials["id_corrected"].sum(),
"from_empty": (trials["file"] == "sub-041_ses-1.csv").sum(),
}
trials.filter(pl.col("participant").is_in(["sub-007", "sub-018"])).group_by(
"participant", "run", "run_recorded", "file"
).agg(n=pl.len()).sort("participant", "run")
inventory.filter(pl.col("status") != "read").select("file", "bytes", "status", "rows")
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| {'rows': 8152, 'contributed': 8152, 'sources': 8152, 'corrected': 201, 'from_empty': 0}
shape: (4, 5)
┌─────────────┬─────┬──────────────┬─────────────────────────┬─────┐
│ participant ┆ run ┆ run_recorded ┆ file ┆ n │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ str ┆ str ┆ u32 │
╞═════════════╪═════╪══════════════╪═════════════════════════╪═════╡
│ sub-007 ┆ 1 ┆ null ┆ sub-007_ses-1.csv ┆ 56 │
│ sub-007 ┆ 2 ┆ 2 ┆ sub-007_ses-1_run-2.csv ┆ 201 │
│ sub-018 ┆ 1 ┆ null ┆ sub-018_ses-1.csv ┆ 56 │
│ sub-018 ┆ 2 ┆ 2 ┆ sub-018_ses-1_run-2.csv ┆ 201 │
└─────────────┴─────┴──────────────┴─────────────────────────┴─────┘
shape: (1, 4)
┌───────────────────┬───────┬────────────────┬──────┐
│ file ┆ bytes ┆ status ┆ rows │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ str ┆ i64 │
╞═══════════════════╪═══════╪════════════════╪══════╡
│ sub-041_ses-1.csv ┆ 0 ┆ verified empty ┆ 0 │
└───────────────────┴───────┴────────────────┴──────┘
|
All 8,152 rows have distinct file/row pairs. The inventory tells us only that the sub-041 file is empty. For both sub-007 and sub-018, run 1 has 56 rows and run 2 has 201. Their lengths alone cannot tell us which scheduled trials they contain.
21.2 Identifying and selecting completed runs
What makes a run complete? Within one run, the block and trial numbers together identify a keyboard trial. The schedule calls for trials 1 to 8 in practice block 0, trials 1 to 48 in each of test blocks 1 to 4, and one questionnaire. Each scheduled trial must appear exactly once, with no extra trials. A file could have 201 rows even if one trial appeared twice and another was absent. A timeout counts toward completion because the task presented the stimulus, even though no key press was recorded in time.
tidyr::expand_grid() generates the expected test keys by pairing each of four blocks with each trial number. The practice keys complete the schedule. distinct() gives runs one row per file, participant, and run. With cross_join(), every scheduled key has a row for each run. On those rows, a missing observed count means a trial is absent and a count above one means it repeats.
A complete run must also contain no extra records. An anti join finds unscheduled keyboard keys. complete requires exactly one questionnaire, which has no keyboard key, and no rows with missing or unrecognized types.
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
| expected_keys <- bind_rows(
tibble(block = "0", trial = as.character(1:8)),
expand_grid(block = as.character(1:4), trial = as.character(1:48))
)
runs <- distinct(trials, file, participant, run)
key_counts <- trials |>
filter(trial_type == "keyboard") |>
count(file, block, trial, name = "copies")
coverage <- cross_join(runs, expected_keys) |>
left_join(
key_counts,
by = join_by(file, block, trial),
relationship = "one-to-one"
) |>
summarise(
missing = sum(is.na(copies)),
repeated = sum(copies > 1, na.rm = TRUE),
.by = c(file, participant, run)
)
unexpected <- key_counts |>
anti_join(expected_keys, by = join_by(block, trial)) |>
count(file, name = "unexpected")
row_types <- trials |>
summarise(
questionnaires = sum(trial_type == "survey", na.rm = TRUE),
other_types = sum(!trial_type %in% c("keyboard", "survey")),
.by = file
)
run_checks <- coverage |>
left_join(unexpected, by = join_by(file), relationship = "one-to-one") |>
left_join(row_types, by = join_by(file), relationship = "one-to-one") |>
mutate(
unexpected = coalesce(unexpected, 0L),
complete = missing == 0 & repeated == 0 & unexpected == 0 &
questionnaires == 1 & other_types == 0
)
run_checks |>
filter(participant %in% c("sub-006", "sub-007", "sub-018")) |>
select(participant, run, missing, repeated, unexpected, questionnaires, complete)
count(run_checks, complete)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
| # A tibble: 5 × 7
participant run missing repeated unexpected questionnaires complete
<chr> <int> <int> <int> <int> <int> <lgl>
1 sub-006 1 0 0 0 1 TRUE
2 sub-007 1 144 0 0 0 FALSE
3 sub-007 2 0 0 0 1 TRUE
4 sub-018 1 144 0 0 0 FALSE
5 sub-018 2 0 0 0 1 TRUE
# A tibble: 2 × 2
complete n
<lgl> <int>
1 FALSE 2
2 TRUE 40
|
In Polars, a cross join gives each run one comparison row for every scheduled trial. After joining the observed counts with validate="1:1", null marks a missing key and a count above one marks a repeat. An anti join finds unexpected keys. Questionnaires are counted separately. A blank or unrecognized trial_type counts as an unknown row type and disqualifies the run.
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
| practice_keys = pl.DataFrame(
{"block": ["0"] * 8, "trial": [str(n) for n in range(1, 9)]}
)
test_keys = pl.DataFrame({"block": ["1", "2", "3", "4"]}).join(
pl.DataFrame({"trial": [str(n) for n in range(1, 49)]}), how="cross"
)
expected_keys = pl.concat([practice_keys, test_keys], how="vertical")
runs = trials.select("file", "participant", "run").unique()
key_counts = (
trials.filter(pl.col("trial_type") == "keyboard")
.group_by("file", "block", "trial")
.agg(copies=pl.len())
)
coverage = (
runs.join(expected_keys, how="cross")
.join(key_counts, on=["file", "block", "trial"], how="left", validate="1:1")
.group_by("file", "participant", "run")
.agg(
missing=pl.col("copies").is_null().sum(),
repeated=(pl.col("copies") > 1).sum(),
)
)
unexpected = (
key_counts.join(expected_keys, on=["block", "trial"], how="anti")
.group_by("file")
.agg(unexpected=pl.len())
)
row_types = trials.group_by("file").agg(
questionnaires=(pl.col("trial_type") == "survey").sum(),
other_types=(~pl.col("trial_type").is_in(["keyboard", "survey"])).fill_null(True).sum(),
)
run_checks = (
coverage.join(unexpected, on="file", how="left", validate="1:1")
.join(row_types, on="file", how="left", validate="1:1")
.with_columns(pl.col("unexpected").fill_null(0))
.with_columns(
complete=(pl.col("missing") == 0)
& (pl.col("repeated") == 0)
& (pl.col("unexpected") == 0)
& (pl.col("questionnaires") == 1)
& (pl.col("other_types") == 0)
)
)
check_columns = [
"participant",
"run",
"missing",
"repeated",
"unexpected",
"questionnaires",
"complete",
]
run_checks.filter(
pl.col("participant").is_in(["sub-006", "sub-007", "sub-018"])
).select(check_columns).sort("participant", "run")
run_checks.group_by("complete").agg(n=pl.len()).sort("complete")
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| shape: (5, 7)
┌─────────────┬─────┬─────────┬──────────┬────────────┬────────────────┬──────────┐
│ participant ┆ run ┆ missing ┆ repeated ┆ unexpected ┆ questionnaires ┆ complete │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ u32 ┆ u32 ┆ u32 ┆ u32 ┆ bool │
╞═════════════╪═════╪═════════╪══════════╪════════════╪════════════════╪══════════╡
│ sub-006 ┆ 1 ┆ 0 ┆ 0 ┆ 0 ┆ 1 ┆ true │
│ sub-007 ┆ 1 ┆ 144 ┆ 0 ┆ 0 ┆ 0 ┆ false │
│ sub-007 ┆ 2 ┆ 0 ┆ 0 ┆ 0 ┆ 1 ┆ true │
│ sub-018 ┆ 1 ┆ 144 ┆ 0 ┆ 0 ┆ 0 ┆ false │
│ sub-018 ┆ 2 ┆ 0 ┆ 0 ┆ 0 ┆ 1 ┆ true │
└─────────────┴─────┴─────────┴──────────┴────────────┴────────────────┴──────────┘
shape: (2, 2)
┌──────────┬─────┐
│ complete ┆ n │
│ --- ┆ --- │
│ bool ┆ u32 │
╞══════════╪═════╡
│ false ┆ 2 │
│ true ┆ 40 │
└──────────┴─────┘
|
The first runs of sub-007 and sub-018 are missing the 144 trials in test blocks 2 to 4 and the questionnaire. Their second runs are complete. What would happen if records were grouped by participant before choosing a run? Grouping by participant, block, and trial puts copies from both files under the same key.
1
2
3
4
| trials |>
filter(participant %in% c("sub-007", "sub-018"), trial_type == "keyboard") |>
count(participant, block, trial, name = "copies") |>
count(participant, copies, name = "keys")
|
1
2
3
4
5
6
7
| # A tibble: 4 × 3
participant copies keys
<chr> <int> <int>
1 sub-007 1 144
2 sub-007 2 56
3 sub-018 1 144
4 sub-018 2 56
|
1
2
3
4
5
6
| trials.filter(
pl.col("participant").is_in(["sub-007", "sub-018"]),
pl.col("trial_type") == "keyboard",
).group_by("participant", "block", "trial").agg(copies=pl.len()).group_by(
"participant", "copies"
).agg(keys=pl.len()).sort("participant", "copies")
|
1
2
3
4
5
6
7
8
9
10
11
| shape: (4, 3)
┌─────────────┬────────┬──────┐
│ participant ┆ copies ┆ keys │
│ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ u32 │
╞═════════════╪════════╪══════╡
│ sub-007 ┆ 1 ┆ 144 │
│ sub-007 ┆ 2 ┆ 56 │
│ sub-018 ┆ 1 ┆ 144 │
│ sub-018 ┆ 2 ┆ 56 │
└─────────────┴────────┴──────┘
|
For each of the two participants, the 56 keys with copies equal to 2 are the eight practice trials and the 48 trials in test block 1. Selecting complete runs counts each of those trials once here. The participant count below includes people with trial records. The empty export for sub-041 has an entry in the file inventory only.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| complete_runs <- filter(run_checks, complete)
selected_runs <- select(complete_runs, file, participant, run)
c(
participants = n_distinct(runs$participant),
with_complete_run = n_distinct(complete_runs$participant),
selected_runs = nrow(selected_runs)
)
run_decisions <- inventory |>
select(file, file_participant, run, status) |>
left_join(
select(run_checks, file, complete),
by = join_by(file),
relationship = "one-to-one"
) |>
mutate(
decision = case_when(
status != "read" ~ status,
complete ~ "selected",
.default = "incomplete run"
)
)
count(run_decisions, status, decision)
|
1
2
3
4
5
6
7
8
| participants with_complete_run selected_runs
40 40 40
# A tibble: 3 × 3
status decision n
<chr> <chr> <int>
1 read incomplete run 2
2 read selected 40
3 verified empty verified empty 1
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| complete_runs = run_checks.filter(pl.col("complete"))
selected_runs = complete_runs.select("file", "participant", "run")
{
"participants": runs["participant"].n_unique(),
"with_complete_run": complete_runs["participant"].n_unique(),
"selected_runs": selected_runs.height,
}
run_decisions = (
inventory.select("file", "file_participant", "run", "status")
.join(run_checks.select("file", "complete"), on="file", how="left", validate="1:1")
.with_columns(
decision=pl.when(pl.col("status") != "read")
.then(pl.col("status"))
.when(pl.col("complete"))
.then(pl.lit("selected"))
.otherwise(pl.lit("incomplete run"))
)
)
run_decisions.group_by("status", "decision").agg(n=pl.len()).sort("status", "decision")
|
1
2
3
4
5
6
7
8
9
10
11
| {'participants': 40, 'with_complete_run': 40, 'selected_runs': 40}
shape: (3, 3)
┌────────────────┬────────────────┬─────┐
│ status ┆ decision ┆ n │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ u32 │
╞════════════════╪════════════════╪═════╡
│ read ┆ incomplete run ┆ 2 │
│ read ┆ selected ┆ 40 │
│ verified empty ┆ verified empty ┆ 1 │
└────────────────┴────────────────┴─────┘
|
The 40 selected runs belong to 40 distinct participants, so each person with records has exactly one complete run. In R, a many-to-one inner join on file, participant, and run returns each selected record once. selected_records distinguishes practice trials, test trials, and questionnaires.
Only the tests enter test_trials, including any that ended in a timeout. The example shows what the file records when no key is pressed within the response window.
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
| selected_records <- trials |>
inner_join(
selected_runs,
by = join_by(file, participant, run),
relationship = "many-to-one"
) |>
mutate(
row_type = case_when(
trial_type == "keyboard" & block == "0" ~ "practice",
trial_type == "keyboard" & block %in% c("1", "2", "3", "4") ~ "test",
trial_type == "survey" ~ "questionnaire",
.default = "other"
)
)
count(selected_records, row_type)
test_trials <- filter(selected_records, row_type == "test")
test_trials |>
filter(is.na(resp)) |>
head(1) |>
select(participant, block, trial, resp, rt, correct_recorded, correct)
c(
timeouts = sum(is.na(test_trials$resp)),
timeouts_without_rt = sum(is.na(test_trials$resp) & is.na(test_trials$rt)),
timeouts_correct = sum(test_trials$correct[is.na(test_trials$resp)])
)
|
1
2
3
4
5
6
7
8
9
10
11
12
| # A tibble: 3 × 2
row_type n
<chr> <int>
1 practice 320
2 questionnaire 40
3 test 7680
# A tibble: 1 × 7
participant block trial resp rt correct_recorded correct
<chr> <chr> <chr> <chr> <chr> <chr> <int>
1 sub-001 3 3 <NA> <NA> False 0
timeouts timeouts_without_rt timeouts_correct
86 86 0
|
A Polars inner join with validate="m:1" matches each record to at most one selected run. selected_records distinguishes practice trials, tests, and questionnaires. Only the tests enter test_trials, including timeouts. Sorting timeouts by file and source row identifies the first example, and the counts show how many timeouts also have a missing time.
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
| selected_records = trials.join(
selected_runs, on=["file", "participant", "run"], how="inner", validate="m:1"
).with_columns(
row_type=pl.when((pl.col("trial_type") == "keyboard") & (pl.col("block") == "0"))
.then(pl.lit("practice"))
.when(
(pl.col("trial_type") == "keyboard")
& pl.col("block").is_in(["1", "2", "3", "4"])
)
.then(pl.lit("test"))
.when(pl.col("trial_type") == "survey")
.then(pl.lit("questionnaire"))
.otherwise(pl.lit("other"))
)
selected_records.group_by("row_type").agg(n=pl.len()).sort("row_type")
test_trials = selected_records.filter(pl.col("row_type") == "test")
timeouts = test_trials.filter(pl.col("resp").is_null())
timeouts.sort("file", "source_row").head(1).select(
"participant", "block", "trial", "resp", "rt", "correct_recorded", "correct"
)
{
"timeouts": timeouts.height,
"timeouts_without_rt": timeouts["rt"].null_count(),
"timeouts_correct": timeouts["correct"].sum(),
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| shape: (3, 2)
┌───────────────┬──────┐
│ row_type ┆ n │
│ --- ┆ --- │
│ str ┆ u32 │
╞═══════════════╪══════╡
│ practice ┆ 320 │
│ questionnaire ┆ 40 │
│ test ┆ 7680 │
└───────────────┴──────┘
shape: (1, 7)
┌─────────────┬───────┬───────┬──────┬──────┬──────────────────┬─────────┐
│ participant ┆ block ┆ trial ┆ resp ┆ rt ┆ correct_recorded ┆ correct │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str ┆ str ┆ str ┆ i64 │
╞═════════════╪═══════╪═══════╪══════╪══════╪══════════════════╪═════════╡
│ sub-001 ┆ 3 ┆ 3 ┆ null ┆ null ┆ False ┆ 0 │
└─────────────┴───────┴───────┴──────┴──────┴──────────────────┴─────────┘
{'timeouts': 86, 'timeouts_without_rt': 86, 'timeouts_correct': 0}
|
The timeout example has no response or reaction time but recorded correctness 0. All 86 timeouts have this form and are part of test_trials. Each complete run should contribute 192 test trials, and choosing one run per participant should give unique participant/block/trial keys.
1
2
3
4
5
6
7
8
9
| per_run <- count(test_trials, file, name = "tests")
c(
runs = nrow(selected_runs),
records = nrow(selected_records),
tests = nrow(test_trials),
test_keys = n_distinct(test_trials$participant, test_trials$block, test_trials$trial),
min_tests = min(per_run$tests),
max_tests = max(per_run$tests)
)
|
1
2
| runs records tests test_keys min_tests max_tests
40 8040 7680 7680 192 192
|
1
2
3
4
5
6
7
8
9
| per_run = test_trials.group_by("file").agg(tests=pl.len())
{
"runs": selected_runs.height,
"records": selected_records.height,
"tests": test_trials.height,
"test_keys": test_trials.select("participant", "block", "trial").n_unique(),
"min_tests": per_run["tests"].min(),
"max_tests": per_run["tests"].max(),
}
|
1
| {'runs': 40, 'records': 8040, 'tests': 7680, 'test_keys': 7680, 'min_tests': 192, 'max_tests': 192}
|
The selected runs contain 8,040 records, including 7,680 uniquely keyed test trials. Every run contributes 192 tests.
The selected runs establish which test trials belong to the analysis. Each trial identifies its stimulus in stim, but stimuli.csv gives two definitions of S09 with different ink colors and correct keys. The response cannot be checked against a unique correct key until that conflict is resolved.
The duplicate also affects the size of a join. lookup_row identifies each source definition, and a trial with two matching definitions would yield two rows. Summing each trial’s number of definitions predicts the size of the join.
1
2
3
4
5
6
7
8
9
10
11
12
13
| stimuli <- read_csv(
file.path(trial_dir, "stimuli.csv"),
col_types = cols(.default = col_character()),
na = "",
trim_ws = FALSE
) |>
mutate(lookup_row = row_number(), .before = 1)
lookup_rows <- count(stimuli, stim, name = "lookup_rows")
c(rows = nrow(stimuli), stimuli = nrow(lookup_rows))
filter(lookup_rows, lookup_rows > 1)
test_trials |>
left_join(lookup_rows, by = join_by(stim), relationship = "many-to-one") |>
summarise(tests = n(), s09_tests = sum(stim == "S09"), pairings = sum(lookup_rows))
|
1
2
3
4
5
6
7
8
9
10
| rows stimuli
17 16
# A tibble: 1 × 2
stim lookup_rows
<chr> <int>
1 S09 2
# A tibble: 1 × 3
tests s09_tests pairings
<int> <int> <int>
1 7680 320 8000
|
1
2
3
4
5
6
7
8
9
10
11
| stimuli = pl.read_csv(trial_dir / "stimuli.csv", infer_schema=False).with_row_index(
"lookup_row", offset=1
)
lookup_rows = stimuli.group_by("stim").agg(lookup_rows=pl.len())
{"rows": stimuli.height, "stimuli": lookup_rows.height}
lookup_rows.filter(pl.col("lookup_rows") > 1)
test_trials.join(lookup_rows, on="stim", how="left", validate="m:1").select(
tests=pl.len(),
s09_tests=(pl.col("stim") == "S09").sum(),
pairings=pl.col("lookup_rows").sum(),
)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| {'rows': 17, 'stimuli': 16}
shape: (1, 2)
┌──────┬─────────────┐
│ stim ┆ lookup_rows │
│ --- ┆ --- │
│ str ┆ u32 │
╞══════╪═════════════╡
│ S09 ┆ 2 │
└──────┴─────────────┘
shape: (1, 3)
┌───────┬───────────┬──────────┐
│ tests ┆ s09_tests ┆ pairings │
│ --- ┆ --- ┆ --- │
│ u32 ┆ u32 ┆ u32 │
╞═══════╪═══════════╪══════════╡
│ 7680 ┆ 320 ┆ 8000 │
└───────┴───────────┴──────────┘
|
The S09 stimulus design
Matching each of the 320 S09 trials twice would turn 7,680 trial rows into 8,000 joined rows. The task specification identifies S09 as the word green printed in red ink. Its condition is incongruent and its correct key is d.
1
| filter(stimuli, stim == "S09")
|
1
2
3
4
5
| # A tibble: 2 × 6
lookup_row stim word ink cond correct_key
<int> <chr> <chr> <chr> <chr> <chr>
1 9 S09 green red incongruent d
2 17 S09 green green congruent j
|
1
| stimuli.filter(pl.col("stim") == "S09")
|
1
2
3
4
5
6
7
8
9
| shape: (2, 6)
┌────────────┬──────┬───────┬───────┬─────────────┬─────────────┐
│ lookup_row ┆ stim ┆ word ┆ ink ┆ cond ┆ correct_key │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ u32 ┆ str ┆ str ┆ str ┆ str ┆ str │
╞════════════╪══════╪═══════╪═══════╪═════════════╪═════════════╡
│ 9 ┆ S09 ┆ green ┆ red ┆ incongruent ┆ d │
│ 17 ┆ S09 ┆ green ┆ green ┆ congruent ┆ j │
└────────────┴──────┴───────┴───────┴─────────────┴─────────────┘
|
A stimulus is congruent when the printed word names its ink color and incongruent when they differ. The correct key depends on the ink color, with d for red, f for blue, j for green, and k for yellow. The design pairs each of four words with each of four ink colors exactly once.
These rules provide two checks on each lookup row and one on the set of rows. In R, if_else() derives the condition and ink_keys[ink] derives the key. Polars uses pl.when() and replace_strict(). Counting distinct word/ink pairs then checks the combinations represented in the lookup.
1
2
3
4
5
6
7
8
9
10
11
12
13
| ink_keys <- c(red = "d", blue = "f", green = "j", yellow = "k")
stimulus_rules <- stimuli |>
mutate(
rule_cond = if_else(word == ink, "congruent", "incongruent"),
rule_key = unname(ink_keys[ink])
)
c(
rows = nrow(stimulus_rules),
cond_agrees = sum(stimulus_rules$cond == stimulus_rules$rule_cond),
key_agrees = sum(stimulus_rules$correct_key == stimulus_rules$rule_key),
word_ink_pairs = n_distinct(stimuli$word, stimuli$ink)
)
filter(stimuli, n() > 1, .by = c(word, ink))
|
1
2
3
4
5
6
7
| rows cond_agrees key_agrees word_ink_pairs
17 17 17 16
# A tibble: 2 × 6
lookup_row stim word ink cond correct_key
<int> <chr> <chr> <chr> <chr> <chr>
1 11 S11 green green congruent j
2 17 S09 green green congruent j
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| ink_keys = {"red": "d", "blue": "f", "green": "j", "yellow": "k"}
stimulus_rules = stimuli.with_columns(
rule_cond=pl.when(pl.col("word") == pl.col("ink"))
.then(pl.lit("congruent"))
.otherwise(pl.lit("incongruent")),
rule_key=pl.col("ink").replace_strict(ink_keys),
)
{
"rows": stimulus_rules.height,
"cond_agrees": (stimulus_rules["cond"] == stimulus_rules["rule_cond"]).sum(),
"key_agrees": (stimulus_rules["correct_key"] == stimulus_rules["rule_key"]).sum(),
"word_ink_pairs": stimuli.select("word", "ink").n_unique(),
}
stimuli.filter(pl.len().over("word", "ink") > 1)
|
1
2
3
4
5
6
7
8
9
10
| {'rows': 17, 'cond_agrees': 17, 'key_agrees': 17, 'word_ink_pairs': 16}
shape: (2, 6)
┌────────────┬──────┬───────┬───────┬───────────┬─────────────┐
│ lookup_row ┆ stim ┆ word ┆ ink ┆ cond ┆ correct_key │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ u32 ┆ str ┆ str ┆ str ┆ str ┆ str │
╞════════════╪══════╪═══════╪═══════╪═══════════╪═════════════╡
│ 11 ┆ S11 ┆ green ┆ green ┆ congruent ┆ j │
│ 17 ┆ S09 ┆ green ┆ green ┆ congruent ┆ j │
└────────────┴──────┴───────┴───────┴───────────┴─────────────┘
|
Both S09 rows give the correct condition and response key for the word and ink they list, so those checks alone cannot identify the intended row. Row 17 repeats the green-on-green combination already assigned to S11. Of the two candidates, only row 9 has the red ink specified for S09.
In R, a semi join matches S09 on word, ink, condition, and correct key. stimulus_audit records which definition was accepted and which was rejected. The resulting lookup should contain one row for each of the 16 stimuli and one for each word/ink combination.
The many-to-one join then allows many trials to share a definition. The without_stimulus count checks whether any trial is missing its condition, and identical() compares the source file and row before and after the join.
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
| specification <- tibble(
stim = "S09",
word = "green",
ink = "red",
cond = "incongruent",
correct_key = "d"
)
specified_rows <- semi_join(
stimuli,
specification,
by = join_by(stim, word, ink, cond, correct_key)
)$lookup_row
stimulus_audit <- stimuli |>
left_join(lookup_rows, by = join_by(stim), relationship = "many-to-one") |>
mutate(
decision = case_when(
lookup_rows == 1 ~ "sole row",
lookup_row %in% specified_rows ~ "accepted",
.default = "rejected"
),
authority = if_else(lookup_rows == 1, "lookup", "stated S09 design")
)
stimulus_audit |>
filter(stim == "S09") |>
select(lookup_row, stim, ink, cond, correct_key, decision, authority)
count(stimulus_audit, decision, authority)
stimulus_lookup <- stimulus_audit |>
filter(decision != "rejected") |>
select(stim, word, ink, cond, correct_key)
c(
rows = nrow(stimulus_lookup),
stimuli = n_distinct(stimulus_lookup$stim),
word_ink_pairs = n_distinct(stimulus_lookup$word, stimulus_lookup$ink)
)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
| # A tibble: 2 × 7
lookup_row stim ink cond correct_key decision authority
<int> <chr> <chr> <chr> <chr> <chr> <chr>
1 9 S09 red incongruent d accepted stated S09 design
2 17 S09 green congruent j rejected stated S09 design
# A tibble: 3 × 3
decision authority n
<chr> <chr> <int>
1 accepted stated S09 design 1
2 rejected stated S09 design 1
3 sole row lookup 15
rows stimuli word_ink_pairs
16 16 16
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| test_stimuli <- left_join(
test_trials,
stimulus_lookup,
by = join_by(stim),
relationship = "many-to-one"
)
c(
tests = nrow(test_trials),
joined = nrow(test_stimuli),
trial_keys = n_distinct(
test_stimuli$participant,
test_stimuli$block,
test_stimuli$trial
),
without_stimulus = sum(is.na(test_stimuli$cond))
)
identical(select(test_stimuli, file, source_row), select(test_trials, file, source_row))
test_stimuli |>
filter(stim == "S09") |>
head(1) |>
select(participant, block, trial, stim, word, ink, cond, correct_key)
|
1
2
3
4
5
6
7
| tests joined trial_keys without_stimulus
7680 7680 7680 0
[1] TRUE
# A tibble: 1 × 8
participant block trial stim word ink cond correct_key
<chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 sub-001 1 29 S09 green red incongruent d
|
All 7,680 trials have a matching condition, and sub-001’s first S09 trial has the red-ink key d. Each selected trial now has the information needed to check its recorded correctness.
The task records a blank resp if no key is pressed within 2,500 ms. case_when() scores that timeout as 0. For a recorded key press, it compares resp with correct_key. A match scores 1, even if the recorded time is unusable. agree compares that result with the recorded correctness.
1
2
3
4
5
6
7
8
9
10
11
| checked_tests <- test_stimuli |>
mutate(
correct_rule = case_when(
is.na(resp) ~ 0L,
resp == correct_key ~ 1L,
.default = 0L
),
response = if_else(is.na(resp), "timeout", "response"),
agree = correct == correct_rule
)
count(checked_tests, response, correct, correct_rule)
|
1
2
3
4
5
6
| # A tibble: 3 × 4
response correct correct_rule n
<chr> <int> <int> <int>
1 response 0 0 551
2 response 1 1 7043
3 timeout 0 0 86
|
In Polars, a semi join finds the row that matches the S09 specification. The lookup includes that row and the 15 stimuli with a single definition. stimulus_audit also records the rejected row.
The trial join uses validate="m:1" so each trial matches at most one definition. With both sets of file/row pairs sorted, equals() tests whether they identify the same trials. Sorting by file and source row identifies the first S09 trial.
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
| specification = pl.DataFrame(
{
"stim": ["S09"],
"word": ["green"],
"ink": ["red"],
"cond": ["incongruent"],
"correct_key": ["d"],
}
)
specified_rows = stimuli.join(
specification, on=["stim", "word", "ink", "cond", "correct_key"], how="semi"
)["lookup_row"].to_list()
stimulus_audit = (
stimuli.join(lookup_rows, on="stim", how="left", validate="m:1")
.with_columns(
decision=pl.when(pl.col("lookup_rows") == 1)
.then(pl.lit("sole row"))
.when(pl.col("lookup_row").is_in(specified_rows))
.then(pl.lit("accepted"))
.otherwise(pl.lit("rejected")),
authority=pl.when(pl.col("lookup_rows") == 1)
.then(pl.lit("lookup"))
.otherwise(pl.lit("stated S09 design")),
)
.sort("lookup_row")
)
stimulus_audit.filter(pl.col("stim") == "S09").select(
"lookup_row", "stim", "ink", "cond", "correct_key", "decision", "authority"
)
stimulus_audit.group_by("decision", "authority").agg(n=pl.len()).sort("decision")
stimulus_lookup = stimulus_audit.filter(pl.col("decision") != "rejected").select(
"stim", "word", "ink", "cond", "correct_key"
)
{
"rows": stimulus_lookup.height,
"stimuli": stimulus_lookup["stim"].n_unique(),
"word_ink_pairs": stimulus_lookup.select("word", "ink").n_unique(),
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| shape: (2, 7)
┌────────────┬──────┬───────┬─────────────┬─────────────┬──────────┬───────────────────┐
│ lookup_row ┆ stim ┆ ink ┆ cond ┆ correct_key ┆ decision ┆ authority │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ u32 ┆ str ┆ str ┆ str ┆ str ┆ str ┆ str │
╞════════════╪══════╪═══════╪═════════════╪═════════════╪══════════╪═══════════════════╡
│ 9 ┆ S09 ┆ red ┆ incongruent ┆ d ┆ accepted ┆ stated S09 design │
│ 17 ┆ S09 ┆ green ┆ congruent ┆ j ┆ rejected ┆ stated S09 design │
└────────────┴──────┴───────┴─────────────┴─────────────┴──────────┴───────────────────┘
shape: (3, 3)
┌──────────┬───────────────────┬─────┐
│ decision ┆ authority ┆ n │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ u32 │
╞══════════╪═══════════════════╪═════╡
│ accepted ┆ stated S09 design ┆ 1 │
│ rejected ┆ stated S09 design ┆ 1 │
│ sole row ┆ lookup ┆ 15 │
└──────────┴───────────────────┴─────┘
{'rows': 16, 'stimuli': 16, 'word_ink_pairs': 16}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| test_stimuli = test_trials.join(stimulus_lookup, on="stim", how="left", validate="m:1")
sources = ["file", "source_row"]
{
"tests": test_trials.height,
"joined": test_stimuli.height,
"trial_keys": test_stimuli.select("participant", "block", "trial").n_unique(),
"without_stimulus": test_stimuli["cond"].null_count(),
"same_sources": test_stimuli.select(sources)
.sort(sources)
.equals(test_trials.select(sources).sort(sources)),
}
test_stimuli.filter(pl.col("stim") == "S09").sort(sources).head(1).select(
"participant", "block", "trial", "stim", "word", "ink", "cond", "correct_key"
)
|
1
2
3
4
5
6
7
8
9
| {'tests': 7680, 'joined': 7680, 'trial_keys': 7680, 'without_stimulus': 0, 'same_sources': True}
shape: (1, 8)
┌─────────────┬───────┬───────┬──────┬───────┬─────┬─────────────┬─────────────┐
│ participant ┆ block ┆ trial ┆ stim ┆ word ┆ ink ┆ cond ┆ correct_key │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str ┆ str ┆ str ┆ str ┆ str │
╞═════════════╪═══════╪═══════╪══════╪═══════╪═════╪═════════════╪═════════════╡
│ sub-001 ┆ 1 ┆ 29 ┆ S09 ┆ green ┆ red ┆ incongruent ┆ d │
└─────────────┴───────┴───────┴──────┴───────┴─────┴─────────────┴─────────────┘
|
All 7,680 trials have a matching condition and the same source rows as before the join. The displayed S09 trial has the red-ink key d. Each selected trial now has the information needed to check its recorded correctness.
The task records a blank resp if no key is pressed within 2,500 ms. pl.when() scores a blank as 0 and any recorded key by whether it matches correct_key. The recorded time is not used in this comparison. A second with_columns() compares correct_rule with the recorded correct value.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| checked_tests = test_stimuli.with_columns(
correct_rule=pl.when(pl.col("resp").is_null())
.then(0)
.when(pl.col("resp") == pl.col("correct_key"))
.then(1)
.otherwise(0)
.cast(pl.Int64),
response=pl.when(pl.col("resp").is_null())
.then(pl.lit("timeout"))
.otherwise(pl.lit("response")),
).with_columns(agree=pl.col("correct") == pl.col("correct_rule"))
checked_tests.group_by("response", "correct", "correct_rule").agg(n=pl.len()).sort(
"response", "correct", "correct_rule"
)
|
1
2
3
4
5
6
7
8
9
10
| shape: (3, 4)
┌──────────┬─────────┬──────────────┬──────┐
│ response ┆ correct ┆ correct_rule ┆ n │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 ┆ u32 │
╞══════════╪═════════╪══════════════╪══════╡
│ response ┆ 0 ┆ 0 ┆ 551 │
│ response ┆ 1 ┆ 1 ┆ 7043 │
│ timeout ┆ 0 ┆ 0 ┆ 86 │
└──────────┴─────────┴──────────────┴──────┘
|
The grouped counts show 551 wrong key presses, 7,043 correct ones, and 86 timeouts. The next two rows show how the key comparison and the timeout rule each reproduce a recorded score.
1
2
3
4
5
6
7
8
9
10
11
12
13
| bind_rows(
head(filter(checked_tests, stim == "S09"), 1),
head(filter(checked_tests, response == "timeout"), 1)
) |>
select(participant, block, trial, stim, resp, correct_key, correct, correct_rule)
checked_tests |>
summarise(
tests = n(),
responses = sum(response == "response"),
agreements = sum(agree),
s09_tests = sum(stim == "S09"),
s09_agreements = sum(agree[stim == "S09"])
)
|
1
2
3
4
5
6
7
8
9
| # A tibble: 2 × 8
participant block trial stim resp correct_key correct correct_rule
<chr> <chr> <chr> <chr> <chr> <chr> <int> <int>
1 sub-001 1 29 S09 d d 1 1
2 sub-001 3 3 S12 <NA> k 0 0
# A tibble: 1 × 5
tests responses agreements s09_tests s09_agreements
<int> <int> <int> <int> <int>
1 7680 7594 7680 320 320
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| pl.concat(
[
checked_tests.filter(pl.col("stim") == "S09").sort(sources).head(1),
checked_tests.filter(pl.col("response") == "timeout").sort(sources).head(1),
],
how="vertical",
).select(
"participant", "block", "trial", "stim", "resp", "correct_key", "correct",
"correct_rule",
)
checked_tests.select(
tests=pl.len(),
responses=(pl.col("response") == "response").sum(),
agreements=pl.col("agree").sum(),
s09_tests=(pl.col("stim") == "S09").sum(),
s09_agreements=pl.col("agree").filter(pl.col("stim") == "S09").sum(),
)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| shape: (2, 8)
┌─────────────┬───────┬───────┬──────┬──────┬─────────────┬─────────┬──────────────┐
│ participant ┆ block ┆ trial ┆ stim ┆ resp ┆ correct_key ┆ correct ┆ correct_rule │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str ┆ str ┆ str ┆ i64 ┆ i64 │
╞═════════════╪═══════╪═══════╪══════╪══════╪═════════════╪═════════╪══════════════╡
│ sub-001 ┆ 1 ┆ 29 ┆ S09 ┆ d ┆ d ┆ 1 ┆ 1 │
│ sub-001 ┆ 3 ┆ 3 ┆ S12 ┆ null ┆ k ┆ 0 ┆ 0 │
└─────────────┴───────┴───────┴──────┴──────┴─────────────┴─────────┴──────────────┘
shape: (1, 5)
┌───────┬───────────┬────────────┬───────────┬────────────────┐
│ tests ┆ responses ┆ agreements ┆ s09_tests ┆ s09_agreements │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ u32 ┆ u32 ┆ u32 ┆ u32 ┆ u32 │
╞═══════╪═══════════╪════════════╪═══════════╪════════════════╡
│ 7680 ┆ 7594 ┆ 7680 ┆ 320 ┆ 320 │
└───────┴───────────┴────────────┴───────────┴────────────────┘
|
The d response to S09 agrees with the red-ink key; the rejected definition would mark it wrong. The timeout rule assigns 0 to the S12 trial with no key press. Applying the resolved stimulus definitions and this timeout rule reproduces all 7,680 recorded outcomes.
21.4 Summarizing accuracy and reaction time
The verified outcomes provide a score for every test, including a timeout. For each participant and condition, accuracy divides the number of correct tests by all scheduled tests. A reaction-time mean uses a separate rule for eligible responses. For each participant, each block presents the four congruent stimuli six times each and the twelve incongruent stimuli twice each. That gives 24 trials per condition in each block and 96 across the four blocks.
The task allows 2,500 ms for a key press. For the mean reaction time, we include only correct responses with usable times from our chosen lower limit of 200 ms to the task limit of 2,500 ms. The recorded value 65535 marks a timer overflow. Both dplyr::between() and Polars’ is_between() include the two endpoints.
1
2
3
4
| rt_lower <- 200L
rt_upper <- 2500L
timer_overflow <- 65535L
between(c(199L, 200L, 2500L, 2501L), rt_lower, rt_upper)
|
1
| [1] FALSE TRUE TRUE FALSE
|
1
2
3
4
| rt_lower = 200
rt_upper = 2500
timer_overflow = 65535
pl.Series("rt_ms", [199, 200, 2500, 2501]).is_between(rt_lower, rt_upper).to_list()
|
1
| [False, True, True, False]
|
A recorded duration is valid here if it is present, nonnegative, and different from the overflow marker. Does every valid time belong in the mean? The six examples include a wrong key with a valid time and a correct key with a time below 200 ms.
as.integer(rt) reads the recorded milliseconds as integers in rt_ms. time_reason marks a missing, negative, overflow, or valid time. This classification describes the recorded duration, independently of whether the response was correct.
rt_reason then checks in order for a timeout, an error, an invalid time, and times below or above the limits. The remaining trials are eligible. Thus a negative time on an incorrect response can receive both negative and error. The separate rt_eligible test of correctness, validity, and bounds should agree with the eligible label.
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
| trial_decisions <- checked_tests |>
mutate(
rt_ms = as.integer(rt),
time_reason = case_when(
is.na(rt_ms) ~ "missing",
rt_ms < 0 ~ "negative",
rt_ms == timer_overflow ~ "timer overflow",
.default = "valid"
),
time_valid = time_reason == "valid",
rt_reason = case_when(
response == "timeout" ~ "timeout",
correct == 0 ~ "error",
!time_valid ~ "invalid time",
rt_ms < rt_lower ~ "below 200 ms",
rt_ms > rt_upper ~ "above 2,500 ms",
.default = "eligible"
),
rt_eligible = correct == 1 & time_valid & between(rt_ms, rt_lower, rt_upper)
)
cases <- tribble(
~case, ~participant, ~block, ~trial,
"correct", "sub-001", "1", "1",
"error", "sub-001", "1", "26",
"timeout", "sub-001", "3", "3",
"short", "sub-006", "2", "28",
"negative", "sub-027", "1", "37",
"overflow", "sub-013", "2", "7"
)
cases |>
left_join(
trial_decisions,
by = join_by(participant, block, trial),
relationship = "one-to-one"
) |>
select(case, participant, correct, rt_ms, time_reason, rt_reason, rt_eligible)
count(trial_decisions, time_reason, rt_reason)
sum(trial_decisions$rt_eligible != (trial_decisions$rt_reason == "eligible"))
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| # A tibble: 6 × 7
case participant correct rt_ms time_reason rt_reason rt_eligible
<chr> <chr> <int> <int> <chr> <chr> <lgl>
1 correct sub-001 1 541 valid eligible TRUE
2 error sub-001 0 594 valid error FALSE
3 timeout sub-001 0 NA missing timeout FALSE
4 short sub-006 1 137 valid below 200 ms FALSE
5 negative sub-027 1 -12 negative invalid time FALSE
6 overflow sub-013 1 65535 timer overflow invalid time FALSE
# A tibble: 7 × 3
time_reason rt_reason n
<chr> <chr> <int>
1 missing timeout 86
2 negative error 1
3 negative invalid time 2
4 timer overflow invalid time 3
5 valid below 200 ms 4
6 valid eligible 7034
7 valid error 550
[1] 0
|
The 594 ms response was wrong, so its time is excluded from the mean for correct responses. sub-027 and sub-013 both pressed the correct key. Their trials count as correct, but the recorded times of −12 and 65535 cannot be averaged as reaction times. Within each participant and condition, accuracy is the sum of correct divided by the trial count.
1
2
3
4
5
6
| accuracy <- trial_decisions |>
summarise(n_correct = sum(correct), n_tests = n(), .by = c(participant, cond)) |>
mutate(accuracy = n_correct / n_tests) |>
arrange(participant, cond)
filter(accuracy, participant %in% c("sub-001", "sub-029"))
count(accuracy, n_tests, name = "units")
|
1
2
3
4
5
6
7
8
9
10
11
| # A tibble: 4 × 5
participant cond n_correct n_tests accuracy
<chr> <chr> <int> <int> <dbl>
1 sub-001 congruent 89 96 0.927
2 sub-001 incongruent 91 96 0.948
3 sub-029 congruent 27 96 0.281
4 sub-029 incongruent 29 96 0.302
# A tibble: 1 × 2
n_tests units
<int> <int>
1 96 80
|
Each of the 80 participant/condition pairs in units has 96 tests. summarize_times() joins the eligible-time counts and means back to all those pairs. If no time qualifies, the count becomes zero and the mean stays missing. A constructed example tests this by setting rt_eligible to false for every congruent trial of 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
28
| units <- select(accuracy, participant, cond)
summarize_times <- function(decisions, units) {
eligible_times <- decisions |>
filter(rt_eligible) |>
summarise(n_rt = n(), mean_rt = mean(rt_ms), .by = c(participant, cond))
units |>
left_join(
eligible_times,
by = join_by(participant, cond),
relationship = "one-to-one"
) |>
mutate(n_rt = coalesce(n_rt, 0L))
}
rt_summary <- summarize_times(trial_decisions, units)
filter(rt_summary, participant %in% c("sub-001", "sub-029"))
c(
units = nrow(rt_summary),
eligible = sum(rt_summary$n_rt),
fewest = min(rt_summary$n_rt)
)
constructed <- trial_decisions |>
mutate(rt_eligible = rt_eligible & !(participant == "sub-001" & cond == "congruent"))
zero_check <- summarize_times(constructed, units)
filter(zero_check, participant == "sub-001")
c(
filtered_units = nrow(distinct(filter(constructed, rt_eligible), participant, cond)),
kept_units = nrow(zero_check)
)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| # A tibble: 4 × 4
participant cond n_rt mean_rt
<chr> <chr> <int> <dbl>
1 sub-001 congruent 89 645.
2 sub-001 incongruent 91 688.
3 sub-029 congruent 27 390.
4 sub-029 incongruent 29 404.
units eligible fewest
80 7034 27
# A tibble: 2 × 4
participant cond n_rt mean_rt
<chr> <chr> <int> <dbl>
1 sub-001 congruent 0 NA
2 sub-001 incongruent 91 688.
filtered_units kept_units
79 80
|
In Polars, successive with_columns() calls build rt_ms, time_reason, time_valid, and the eligibility fields so each expression can use earlier results. rt_reason checks for a timeout first, then an error, an invalid time, a time below the lower limit, or one above the upper limit. The remaining trials are eligible.
For a timeout, the missing time cannot be compared with the bounds, but correct == 1 and time_valid are both false, making the trial ineligible. maintain_order="left" displays the six cases in the order listed in cases.
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
| trial_decisions = (
checked_tests.with_columns(rt_ms=pl.col("rt").cast(pl.Int64))
.with_columns(
time_reason=pl.when(pl.col("rt_ms").is_null())
.then(pl.lit("missing"))
.when(pl.col("rt_ms") < 0)
.then(pl.lit("negative"))
.when(pl.col("rt_ms") == timer_overflow)
.then(pl.lit("timer overflow"))
.otherwise(pl.lit("valid"))
)
.with_columns(time_valid=pl.col("time_reason") == "valid")
.with_columns(
rt_reason=pl.when(pl.col("response") == "timeout")
.then(pl.lit("timeout"))
.when(pl.col("correct") == 0)
.then(pl.lit("error"))
.when(~pl.col("time_valid"))
.then(pl.lit("invalid time"))
.when(pl.col("rt_ms") < rt_lower)
.then(pl.lit("below 200 ms"))
.when(pl.col("rt_ms") > rt_upper)
.then(pl.lit("above 2,500 ms"))
.otherwise(pl.lit("eligible")),
rt_eligible=(pl.col("correct") == 1)
& pl.col("time_valid")
& pl.col("rt_ms").is_between(rt_lower, rt_upper),
)
)
cases = pl.DataFrame(
{
"case": ["correct", "error", "timeout", "short", "negative", "overflow"],
"participant": [
"sub-001", "sub-001", "sub-001", "sub-006", "sub-027", "sub-013"
],
"block": ["1", "1", "3", "2", "1", "2"],
"trial": ["1", "26", "3", "28", "37", "7"],
}
)
cases.join(
trial_decisions,
on=["participant", "block", "trial"],
how="left",
validate="1:1",
maintain_order="left",
).select(
"case", "participant", "correct", "rt_ms", "time_reason", "rt_reason", "rt_eligible"
)
trial_decisions.group_by("time_reason", "rt_reason").agg(n=pl.len()).sort(
"time_reason", "rt_reason"
)
(trial_decisions["rt_eligible"] != (trial_decisions["rt_reason"] == "eligible")).sum()
|
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
| shape: (6, 7)
┌──────────┬─────────────┬─────────┬───────┬────────────────┬──────────────┬─────────────┐
│ case ┆ participant ┆ correct ┆ rt_ms ┆ time_reason ┆ rt_reason ┆ rt_eligible │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ i64 ┆ str ┆ str ┆ bool │
╞══════════╪═════════════╪═════════╪═══════╪════════════════╪══════════════╪═════════════╡
│ correct ┆ sub-001 ┆ 1 ┆ 541 ┆ valid ┆ eligible ┆ true │
│ error ┆ sub-001 ┆ 0 ┆ 594 ┆ valid ┆ error ┆ false │
│ timeout ┆ sub-001 ┆ 0 ┆ null ┆ missing ┆ timeout ┆ false │
│ short ┆ sub-006 ┆ 1 ┆ 137 ┆ valid ┆ below 200 ms ┆ false │
│ negative ┆ sub-027 ┆ 1 ┆ -12 ┆ negative ┆ invalid time ┆ false │
│ overflow ┆ sub-013 ┆ 1 ┆ 65535 ┆ timer overflow ┆ invalid time ┆ false │
└──────────┴─────────────┴─────────┴───────┴────────────────┴──────────────┴─────────────┘
shape: (7, 3)
┌────────────────┬──────────────┬──────┐
│ time_reason ┆ rt_reason ┆ n │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ u32 │
╞════════════════╪══════════════╪══════╡
│ missing ┆ timeout ┆ 86 │
│ negative ┆ error ┆ 1 │
│ negative ┆ invalid time ┆ 2 │
│ timer overflow ┆ invalid time ┆ 3 │
│ valid ┆ below 200 ms ┆ 4 │
│ valid ┆ eligible ┆ 7034 │
│ valid ┆ error ┆ 550 │
└────────────────┴──────────────┴──────┘
0
|
The 137 ms response was correct. Its time is valid but too fast for the mean. For each participant and condition, pl.col("correct").sum() counts correct trials and pl.len() counts all tests, including this one. Dividing the first count by the second gives accuracy.
1
2
3
4
5
6
7
8
| accuracy = (
trial_decisions.group_by("participant", "cond")
.agg(n_correct=pl.col("correct").sum(), n_tests=pl.len())
.with_columns(accuracy=pl.col("n_correct") / pl.col("n_tests"))
.sort("participant", "cond")
)
accuracy.filter(pl.col("participant").is_in(["sub-001", "sub-029"]))
accuracy.group_by("n_tests").agg(units=pl.len())
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| shape: (4, 5)
┌─────────────┬─────────────┬───────────┬─────────┬──────────┐
│ participant ┆ cond ┆ n_correct ┆ n_tests ┆ accuracy │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ u32 ┆ f64 │
╞═════════════╪═════════════╪═══════════╪═════════╪══════════╡
│ sub-001 ┆ congruent ┆ 89 ┆ 96 ┆ 0.927083 │
│ sub-001 ┆ incongruent ┆ 91 ┆ 96 ┆ 0.947917 │
│ sub-029 ┆ congruent ┆ 27 ┆ 96 ┆ 0.28125 │
│ sub-029 ┆ incongruent ┆ 29 ┆ 96 ┆ 0.302083 │
└─────────────┴─────────────┴───────────┴─────────┴──────────┘
shape: (1, 2)
┌─────────┬───────┐
│ n_tests ┆ units │
│ --- ┆ --- │
│ u32 ┆ u32 │
╞═════════╪═══════╡
│ 96 ┆ 80 │
└─────────┴───────┘
|
A participant with no eligible times in one condition still needs a row for that condition. The left join starts with all pairs in units. Only the count gets fill_null(0) because no mean exists for zero observations. The constructed example marks all congruent trials for sub-001 ineligible for the mean.
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
| units = accuracy.select("participant", "cond")
def summarize_times(decisions, units):
eligible_times = (
decisions.filter(pl.col("rt_eligible"))
.group_by("participant", "cond")
.agg(n_rt=pl.len(), mean_rt=pl.col("rt_ms").mean())
)
return (
units.join(
eligible_times, on=["participant", "cond"], how="left", validate="1:1"
)
.with_columns(pl.col("n_rt").fill_null(0))
.sort("participant", "cond")
)
rt_summary = summarize_times(trial_decisions, units)
rt_summary.filter(pl.col("participant").is_in(["sub-001", "sub-029"]))
{
"units": rt_summary.height,
"eligible": rt_summary["n_rt"].sum(),
"fewest": rt_summary["n_rt"].min(),
}
constructed = trial_decisions.with_columns(
rt_eligible=pl.col("rt_eligible")
& ~((pl.col("participant") == "sub-001") & (pl.col("cond") == "congruent"))
)
zero_check = summarize_times(constructed, units)
zero_check.filter(pl.col("participant") == "sub-001")
{
"filtered_units": constructed.filter(pl.col("rt_eligible"))
.select("participant", "cond")
.n_unique(),
"kept_units": zero_check.height,
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| shape: (4, 4)
┌─────────────┬─────────────┬──────┬────────────┐
│ participant ┆ cond ┆ n_rt ┆ mean_rt │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ u32 ┆ f64 │
╞═════════════╪═════════════╪══════╪════════════╡
│ sub-001 ┆ congruent ┆ 89 ┆ 645.224719 │
│ sub-001 ┆ incongruent ┆ 91 ┆ 688.252747 │
│ sub-029 ┆ congruent ┆ 27 ┆ 390.333333 │
│ sub-029 ┆ incongruent ┆ 29 ┆ 404.344828 │
└─────────────┴─────────────┴──────┴────────────┘
{'units': 80, 'eligible': 7034, 'fewest': 27}
shape: (2, 4)
┌─────────────┬─────────────┬──────┬────────────┐
│ participant ┆ cond ┆ n_rt ┆ mean_rt │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ u32 ┆ f64 │
╞═════════════╪═════════════╪══════╪════════════╡
│ sub-001 ┆ congruent ┆ 0 ┆ null │
│ sub-001 ┆ incongruent ┆ 91 ┆ 688.252747 │
└─────────────┴─────────────┴──────┴────────────┘
{'filtered_units': 79, 'kept_units': 80}
|
Of the 7,043 correct responses, 7,034 contribute to the time means. Four had valid times below 200 ms, two had negative recorded times, and three had the overflow code. All 80 participant/condition pairs still have eligible times.
In the constructed example, filtering leaves only 79 pairs. The join restores the pair for sub-001 in the congruent condition with a count of zero and a missing mean. Joining the actual time summaries to accuracy should likewise preserve every participant/condition pair. In each resulting row, n_rt should be at most n_correct.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| condition_summary <- left_join(
accuracy,
rt_summary,
by = join_by(participant, cond),
relationship = "one-to-one"
)
filter(condition_summary, participant == "sub-029")
condition_summary |>
summarise(tests = sum(n_tests), .by = participant) |>
count(tests, name = "participants")
c(
units = nrow(condition_summary),
denominators_96 = sum(condition_summary$n_tests == 96),
eligible_within_correct = sum(condition_summary$n_rt <= condition_summary$n_correct)
)
|
1
2
3
4
5
6
7
8
9
10
11
| # A tibble: 2 × 7
participant cond n_correct n_tests accuracy n_rt mean_rt
<chr> <chr> <int> <int> <dbl> <int> <dbl>
1 sub-029 congruent 27 96 0.281 27 390.
2 sub-029 incongruent 29 96 0.302 29 404.
# A tibble: 1 × 2
tests participants
<int> <int>
1 192 40
units denominators_96 eligible_within_correct
80 80 80
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| condition_summary = accuracy.join(
rt_summary, on=["participant", "cond"], how="left", validate="1:1"
).sort("participant", "cond")
condition_summary.filter(pl.col("participant") == "sub-029")
condition_summary.group_by("participant").agg(tests=pl.col("n_tests").sum()).group_by(
"tests"
).agg(participants=pl.len())
{
"units": condition_summary.height,
"denominators_96": (condition_summary["n_tests"] == 96).sum(),
"eligible_within_correct": (
condition_summary["n_rt"] <= condition_summary["n_correct"]
).sum(),
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| shape: (2, 7)
┌─────────────┬─────────────┬───────────┬─────────┬──────────┬──────┬────────────┐
│ participant ┆ cond ┆ n_correct ┆ n_tests ┆ accuracy ┆ n_rt ┆ mean_rt │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ u32 ┆ f64 ┆ u32 ┆ f64 │
╞═════════════╪═════════════╪═══════════╪═════════╪══════════╪══════╪════════════╡
│ sub-029 ┆ congruent ┆ 27 ┆ 96 ┆ 0.28125 ┆ 27 ┆ 390.333333 │
│ sub-029 ┆ incongruent ┆ 29 ┆ 96 ┆ 0.302083 ┆ 29 ┆ 404.344828 │
└─────────────┴─────────────┴───────────┴─────────┴──────────┴──────┴────────────┘
shape: (1, 2)
┌───────┬──────────────┐
│ tests ┆ participants │
│ --- ┆ --- │
│ u32 ┆ u32 │
╞═══════╪══════════════╡
│ 192 ┆ 40 │
└───────┴──────────────┘
{'units': 80, 'denominators_96': 80, 'eligible_within_correct': 80}
|
For sub-029, 27 of 96 congruent trials and 29 of 96 incongruent trials were correct. Only those responses contribute to the means of about 390 and 404 ms, respectively. The run met the completion rule, which has no accuracy cutoff. These counts cannot tell us how the participant chose the keys.
Condition differences
Each participant now has a summary for both conditions, allowing a comparison within that person. We subtract the congruent value from the incongruent value. A positive time difference means that eligible responses were slower on average when word and ink differed. A negative accuracy difference means a smaller proportion of correct responses when word and ink differed.
Each difference requires both condition values for the measure being compared. If one condition has no eligible times, its time difference is unavailable even when both accuracies can be compared.
Widening the R table puts the unrounded accuracy, mean time, and eligible count for each condition on one participant row. rt_difference requires an eligible time in both conditions. In the constructed case, sub-001 has no eligible congruent time. That affects the time difference even though both accuracies are still available.
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
| pair_conditions <- function(summary) {
summary |>
select(participant, cond, accuracy, mean_rt, n_rt) |>
pivot_wider(names_from = cond, values_from = c(accuracy, mean_rt, n_rt)) |>
mutate(
accuracy_difference = accuracy_incongruent - accuracy_congruent,
rt_available = n_rt_incongruent > 0 & n_rt_congruent > 0,
rt_difference = if_else(
rt_available,
mean_rt_incongruent - mean_rt_congruent,
NA_real_
)
)
}
differences <- pair_conditions(condition_summary)
differences |>
filter(participant == "sub-001") |>
select(participant, mean_rt_incongruent, mean_rt_congruent, rt_difference)
differences |>
filter(participant == "sub-001") |>
select(participant, accuracy_incongruent, accuracy_congruent, accuracy_difference)
c(
pairs = nrow(differences),
accuracy_differences = sum(!is.na(differences$accuracy_difference)),
rt_differences = sum(!is.na(differences$rt_difference))
)
constructed_summary <- left_join(
accuracy,
zero_check,
by = join_by(participant, cond),
relationship = "one-to-one"
)
constructed_differences <- pair_conditions(constructed_summary)
constructed_differences |>
filter(participant == "sub-001") |>
select(participant, n_rt_congruent, rt_available, rt_difference, accuracy_difference)
c(
accuracy_differences = sum(!is.na(constructed_differences$accuracy_difference)),
rt_differences = sum(!is.na(constructed_differences$rt_difference))
)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| # A tibble: 1 × 4
participant mean_rt_incongruent mean_rt_congruent rt_difference
<chr> <dbl> <dbl> <dbl>
1 sub-001 688. 645. 43.0
# A tibble: 1 × 4
participant accuracy_incongruent accuracy_congruent accuracy_difference
<chr> <dbl> <dbl> <dbl>
1 sub-001 0.948 0.927 0.0208
pairs accuracy_differences rt_differences
40 40 40
# A tibble: 1 × 5
participant n_rt_congruent rt_available rt_difference accuracy_difference
<chr> <int> <lgl> <dbl> <dbl>
1 sub-001 0 FALSE NA 0.0208
accuracy_differences rt_differences
40 39
|
Sorting before pivot() gives the Polars columns a stable condition order. Accuracy differences need both accuracies. For mean times, rt_available also requires an eligible time in each condition. A later pl.when() uses that test. In the constructed example, only time eligibility changes, so the two accuracy values for sub-001 are the same as before.
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
| def pair_conditions(summary):
return (
summary.sort("participant", "cond")
.pivot(
on="cond", index="participant", values=["accuracy", "mean_rt", "n_rt"]
)
.with_columns(
accuracy_difference=pl.col("accuracy_incongruent")
- pl.col("accuracy_congruent"),
rt_available=(pl.col("n_rt_incongruent") > 0)
& (pl.col("n_rt_congruent") > 0),
)
.with_columns(
rt_difference=pl.when(pl.col("rt_available")).then(
pl.col("mean_rt_incongruent") - pl.col("mean_rt_congruent")
)
)
)
differences = pair_conditions(condition_summary)
sub_001 = pl.col("participant") == "sub-001"
differences.filter(sub_001).select(
"participant", "mean_rt_incongruent", "mean_rt_congruent", "rt_difference"
)
differences.filter(sub_001).select(
"participant", "accuracy_incongruent", "accuracy_congruent", "accuracy_difference"
)
{
"pairs": differences.height,
"accuracy_differences": differences["accuracy_difference"].is_not_null().sum(),
"rt_differences": differences["rt_difference"].is_not_null().sum(),
}
constructed_summary = accuracy.join(
zero_check, on=["participant", "cond"], how="left", validate="1:1"
)
constructed_differences = pair_conditions(constructed_summary)
constructed_differences.filter(sub_001).select(
"participant", "n_rt_congruent", "rt_available", "rt_difference",
"accuracy_difference",
)
{
"accuracy_differences": constructed_differences["accuracy_difference"]
.is_not_null()
.sum(),
"rt_differences": constructed_differences["rt_difference"].is_not_null().sum(),
}
|
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
| shape: (1, 4)
┌─────────────┬─────────────────────┬───────────────────┬───────────────┐
│ participant ┆ mean_rt_incongruent ┆ mean_rt_congruent ┆ rt_difference │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 │
╞═════════════╪═════════════════════╪═══════════════════╪═══════════════╡
│ sub-001 ┆ 688.252747 ┆ 645.224719 ┆ 43.028028 │
└─────────────┴─────────────────────┴───────────────────┴───────────────┘
shape: (1, 4)
┌─────────────┬──────────────────────┬────────────────────┬─────────────────────┐
│ participant ┆ accuracy_incongruent ┆ accuracy_congruent ┆ accuracy_difference │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 │
╞═════════════╪══════════════════════╪════════════════════╪═════════════════════╡
│ sub-001 ┆ 0.947917 ┆ 0.927083 ┆ 0.020833 │
└─────────────┴──────────────────────┴────────────────────┴─────────────────────┘
{'pairs': 40, 'accuracy_differences': 40, 'rt_differences': 40}
shape: (1, 5)
┌─────────────┬────────────────┬──────────────┬───────────────┬─────────────────────┐
│ participant ┆ n_rt_congruent ┆ rt_available ┆ rt_difference ┆ accuracy_difference │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ bool ┆ f64 ┆ f64 │
╞═════════════╪════════════════╪══════════════╪═══════════════╪═════════════════════╡
│ sub-001 ┆ 0 ┆ false ┆ null ┆ 0.020833 │
└─────────────┴────────────────┴──────────────┴───────────────┴─────────────────────┘
{'accuracy_differences': 40, 'rt_differences': 39}
|
For sub-001, eligible responses averaged about 43.03 ms longer in the incongruent condition. Accuracy was also higher in that condition, with 91 correct answers out of 96 versus 89 out of 96. The difference is 2/96, about 2.08 percentage points. In the constructed example, the missing congruent time mean leaves 39 time differences and all 40 accuracy differences.
21.5 Combining trial summaries and questionnaire responses
To describe performance alongside participants’ ratings of the task, we need to combine two condition summaries with one questionnaire from each selected run. The questionnaire records difficulty in Q0 and concentration in Q1, using the digits 1 to 7 as text. Joining by the selected run puts the same difficulty rating beside both conditions. To count how many people gave a rating, we use the questionnaire table, where each person has one row.
1
2
3
4
5
6
| count(condition_summary, participant, name = "condition_rows") |>
count(condition_rows, name = "participants")
selected_records |>
filter(row_type == "questionnaire") |>
count(file, name = "questionnaires") |>
count(questionnaires, name = "runs")
|
1
2
3
4
5
6
7
8
| # A tibble: 1 × 2
condition_rows participants
<int> <int>
1 2 40
# A tibble: 1 × 2
questionnaires runs
<int> <int>
1 1 40
|
1
2
3
4
5
6
| condition_summary.group_by("participant").agg(condition_rows=pl.len()).group_by(
"condition_rows"
).agg(participants=pl.len())
selected_records.filter(pl.col("row_type") == "questionnaire").group_by("file").agg(
questionnaires=pl.len()
).group_by("questionnaires").agg(runs=pl.len())
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| shape: (1, 2)
┌────────────────┬──────────────┐
│ condition_rows ┆ participants │
│ --- ┆ --- │
│ u32 ┆ u32 │
╞════════════════╪══════════════╡
│ 2 ┆ 40 │
└────────────────┴──────────────┘
shape: (1, 2)
┌────────────────┬──────┐
│ questionnaires ┆ runs │
│ --- ┆ --- │
│ u32 ┆ u32 │
╞════════════════╪══════╡
│ 1 ┆ 40 │
└────────────────┴──────┘
|
jsonlite::fromJSON() parses each questionnaire’s response_json. hoist() extracts Q0 and Q1 as text, giving NA for an absent field. Before integer conversion, the code counts the nonmissing answers to each question and how many match the allowed digits in rating_codes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| rating_codes <- as.character(1:7)
questionnaires <- selected_records |>
filter(row_type == "questionnaire") |>
select(file, participant, run, response_json) |>
mutate(answers = map(response_json, jsonlite::fromJSON)) |>
hoist(
answers,
Q0 = "Q0",
Q1 = "Q1",
.ptype = list(Q0 = character(), Q1 = character())
)
c(
rows = nrow(questionnaires),
runs = n_distinct(questionnaires$file),
q0_observed = sum(!is.na(questionnaires$Q0)),
q0_valid = sum(questionnaires$Q0 %in% rating_codes),
q1_observed = sum(!is.na(questionnaires$Q1)),
q1_valid = sum(questionnaires$Q1 %in% rating_codes)
)
questionnaires <- questionnaires |>
mutate(difficulty = as.integer(Q0), concentration = as.integer(Q1))
questionnaires |>
filter(participant == "sub-015") |>
select(file, Q0, Q1, difficulty, concentration)
|
1
2
3
4
5
6
| rows runs q0_observed q0_valid q1_observed q1_valid
40 40 40 40 39 39
# A tibble: 1 × 5
file Q0 Q1 difficulty concentration
<chr> <chr> <chr> <int> <int>
1 sub-015_ses-1.csv 7 <NA> 7 NA
|
The questionnaire for sub-015 contains a difficulty rating of 7 and no Q1 entry for concentration. Each condition row first joins to the selected run for its participant, then to that run’s questionnaire by file, participant, and run. Both joins are many-to-one because the two conditions share a run and a questionnaire.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| condition_ratings <- condition_summary |>
left_join(selected_runs, by = join_by(participant), relationship = "many-to-one") |>
left_join(
select(questionnaires, file, participant, run, difficulty, concentration),
by = join_by(file, participant, run),
relationship = "many-to-one"
)
c(rows = nrow(condition_ratings), questionnaires = nrow(questionnaires))
identical(
select(condition_ratings, participant, cond),
select(condition_summary, participant, cond)
)
condition_ratings |>
filter(participant == "sub-015") |>
select(participant, cond, accuracy, n_rt, mean_rt, difficulty, concentration)
|
1
2
3
4
5
6
7
8
| rows questionnaires
80 40
[1] TRUE
# A tibble: 2 × 7
participant cond accuracy n_rt mean_rt difficulty concentration
<chr> <chr> <dbl> <int> <dbl> <int> <int>
1 sub-015 congruent 0.990 95 689. 7 NA
2 sub-015 incongruent 0.927 89 814. 7 NA
|
In Polars, str.json_decode() reads response_json as a struct with text fields Q0 and Q1. After unnest(), an absent component is null. Before integer conversion, every observed string should belong to rating_codes. File, participant, and run identify the questionnaire behind both ratings.
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
| rating_codes = [str(n) for n in range(1, 8)]
questionnaire_fields = pl.Struct({"Q0": pl.String, "Q1": pl.String})
questionnaires = (
selected_records.filter(pl.col("row_type") == "questionnaire")
.select("file", "participant", "run", "response_json")
.with_columns(
answers=pl.col("response_json").str.json_decode(dtype=questionnaire_fields)
)
.unnest("answers")
.sort("file")
)
{
"rows": questionnaires.height,
"runs": questionnaires["file"].n_unique(),
"q0_observed": questionnaires["Q0"].is_not_null().sum(),
"q0_valid": questionnaires["Q0"].is_in(rating_codes).sum(),
"q1_observed": questionnaires["Q1"].is_not_null().sum(),
"q1_valid": questionnaires["Q1"].is_in(rating_codes).sum(),
}
questionnaires = questionnaires.with_columns(
difficulty=pl.col("Q0").cast(pl.Int64), concentration=pl.col("Q1").cast(pl.Int64)
)
questionnaires.filter(pl.col("participant") == "sub-015").select(
"file", "Q0", "Q1", "difficulty", "concentration"
)
|
1
2
3
4
5
6
7
8
9
| {'rows': 40, 'runs': 40, 'q0_observed': 40, 'q0_valid': 40, 'q1_observed': 39, 'q1_valid': 39}
shape: (1, 5)
┌───────────────────┬─────┬──────┬────────────┬───────────────┐
│ file ┆ Q0 ┆ Q1 ┆ difficulty ┆ concentration │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ i64 ┆ i64 │
╞═══════════════════╪═════╪══════╪════════════╪═══════════════╡
│ sub-015_ses-1.csv ┆ 7 ┆ null ┆ 7 ┆ null │
└───────────────────┴─────┴──────┴────────────┴───────────────┘
|
For sub-015, the difficulty rating is 7 and concentration is null. The first join identifies the selected run for each condition row. The second attaches that run’s ratings. select(*run_keys, ...) passes each key as an argument. Sorting by participant and condition lets equals() compare keys regardless of join order.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| run_keys = ["file", "participant", "run"]
condition_ratings = (
condition_summary.join(selected_runs, on="participant", how="left", validate="m:1")
.join(
questionnaires.select(*run_keys, "difficulty", "concentration"),
on=run_keys,
how="left",
validate="m:1",
)
.sort("participant", "cond")
)
{
"rows": condition_ratings.height,
"questionnaires": questionnaires.height,
"same_keys": condition_ratings.select("participant", "cond").equals(
condition_summary.select("participant", "cond")
),
}
condition_ratings.filter(pl.col("participant") == "sub-015").select(
"participant", "cond", "accuracy", "n_rt", "mean_rt", "difficulty", "concentration"
)
|
1
2
3
4
5
6
7
8
9
10
| {'rows': 80, 'questionnaires': 40, 'same_keys': True}
shape: (2, 7)
┌─────────────┬─────────────┬──────────┬──────┬────────────┬────────────┬───────────────┐
│ participant ┆ cond ┆ accuracy ┆ n_rt ┆ mean_rt ┆ difficulty ┆ concentration │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ f64 ┆ u32 ┆ f64 ┆ i64 ┆ i64 │
╞═════════════╪═════════════╪══════════╪══════╪════════════╪════════════╪═══════════════╡
│ sub-015 ┆ congruent ┆ 0.989583 ┆ 95 ┆ 689.136842 ┆ 7 ┆ null │
│ sub-015 ┆ incongruent ┆ 0.927083 ┆ 89 ┆ 814.247191 ┆ 7 ┆ null │
└─────────────┴─────────────┴──────────┴──────┴────────────┴────────────┴───────────────┘
|
The two sevens for sub-015 come from a single difficulty rating. Concentration is missing on both rows because the questionnaire has no Q1 answer.
Summaries at the participant level
The joined table has two rows per person, so its row count cannot serve as the number of questionnaire respondents. Each condition’s mean accuracy uses one accuracy value per participant. The concentration mean uses one rating from each person who answered Q1, taken from questionnaires before the join.
The first summaries count these contributions. The final two outputs trace sub-001 from the selected run to the trials included in each time mean, connecting the completed analysis to its source records.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| condition_summary |>
summarise(
units = n(),
mean_accuracy = mean(accuracy),
units_with_rt = sum(n_rt > 0),
.by = cond
)
questionnaires |>
summarise(
runs = n(),
difficulty_n = sum(!is.na(difficulty)),
difficulty_mean = mean(difficulty, na.rm = TRUE),
concentration_n = sum(!is.na(concentration)),
concentration_mean = mean(concentration, na.rm = TRUE)
)
c(
rating_rows = sum(!is.na(condition_ratings$concentration)),
respondents = sum(!is.na(questionnaires$concentration))
)
filter(run_decisions, file_participant == "sub-001")
trial_decisions |>
filter(participant == "sub-001") |>
count(cond, rt_reason)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| # A tibble: 2 × 4
cond units mean_accuracy units_with_rt
<chr> <int> <dbl> <int>
1 congruent 40 0.946 40
2 incongruent 40 0.888 40
# A tibble: 1 × 5
runs difficulty_n difficulty_mean concentration_n concentration_mean
<int> <int> <dbl> <int> <dbl>
1 40 40 4.7 39 5.10
rating_rows respondents
78 39
# A tibble: 1 × 6
file file_participant run status complete decision
<chr> <chr> <int> <chr> <lgl> <chr>
1 sub-001_ses-1.csv sub-001 1 read TRUE selected
# A tibble: 5 × 3
cond rt_reason n
<chr> <chr> <int>
1 congruent eligible 89
2 congruent error 7
3 incongruent eligible 91
4 incongruent error 4
5 incongruent timeout 1
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| condition_summary.group_by("cond").agg(
units=pl.len(),
mean_accuracy=pl.col("accuracy").mean(),
units_with_rt=(pl.col("n_rt") > 0).sum(),
).sort("cond")
questionnaires.select(
runs=pl.len(),
difficulty_n=pl.col("difficulty").count(),
difficulty_mean=pl.col("difficulty").mean(),
concentration_n=pl.col("concentration").count(),
concentration_mean=pl.col("concentration").mean(),
)
{
"rating_rows": condition_ratings["concentration"].count(),
"respondents": questionnaires["concentration"].count(),
}
run_decisions.filter(pl.col("file_participant") == "sub-001")
trial_decisions.filter(sub_001).group_by("cond", "rt_reason").agg(n=pl.len()).sort(
"cond", "rt_reason"
)
|
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
| shape: (2, 4)
┌─────────────┬───────┬───────────────┬───────────────┐
│ cond ┆ units ┆ mean_accuracy ┆ units_with_rt │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ f64 ┆ u32 │
╞═════════════╪═══════╪═══════════════╪═══════════════╡
│ congruent ┆ 40 ┆ 0.945833 ┆ 40 │
│ incongruent ┆ 40 ┆ 0.888281 ┆ 40 │
└─────────────┴───────┴───────────────┴───────────────┘
shape: (1, 5)
┌──────┬──────────────┬─────────────────┬─────────────────┬────────────────────┐
│ runs ┆ difficulty_n ┆ difficulty_mean ┆ concentration_n ┆ concentration_mean │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ u32 ┆ u32 ┆ f64 ┆ u32 ┆ f64 │
╞══════╪══════════════╪═════════════════╪═════════════════╪════════════════════╡
│ 40 ┆ 40 ┆ 4.7 ┆ 39 ┆ 5.102564 │
└──────┴──────────────┴─────────────────┴─────────────────┴────────────────────┘
{'rating_rows': 78, 'respondents': 39}
shape: (1, 6)
┌───────────────────┬──────────────────┬─────┬────────┬──────────┬──────────┐
│ file ┆ file_participant ┆ run ┆ status ┆ complete ┆ decision │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ str ┆ bool ┆ str │
╞═══════════════════╪══════════════════╪═════╪════════╪══════════╪══════════╡
│ sub-001_ses-1.csv ┆ sub-001 ┆ 1 ┆ read ┆ true ┆ selected │
└───────────────────┴──────────────────┴─────┴────────┴──────────┴──────────┘
shape: (5, 3)
┌─────────────┬───────────┬─────┐
│ cond ┆ rt_reason ┆ n │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ u32 │
╞═════════════╪═══════════╪═════╡
│ congruent ┆ eligible ┆ 89 │
│ congruent ┆ error ┆ 7 │
│ incongruent ┆ eligible ┆ 91 │
│ incongruent ┆ error ┆ 4 │
│ incongruent ┆ timeout ┆ 1 │
└─────────────┴───────────┴─────┘
|
The 39 concentration ratings average about 5.10. Each appears twice after the join, so the 78 entries have the same mean but still represent only 39 respondents. Across 40 participants, mean accuracy was about 94.6 percent when word and ink matched and 88.8 percent when they differed.
For sub-001, the selected run supplies all 96 tests in each accuracy denominator. The time means use 89 congruent and 91 incongruent trials. The other 12 trials were 11 wrong key presses and one timeout. The run selection, response scoring, and time-eligibility decisions together explain which records contribute to each result.