An experiment records individual trials, but a question about performance may concern a participant or one block of trials. Counting rows cannot tell us how many people took part, and a mean cannot be interpreted without knowing which trials contributed. This chapter develops grouped counts and summaries by first distinguishing rows, observed values, and distinct units. We then calculate accuracy and mean response time for groups defined by one or more variables. Finally, we return group calculations to the trial rows so that each response time can be compared with that participant’s own mean.
8.1 Counting rows, values, and distinct units
In a Stroop task, the participant sees a color word printed on the screen and presses the key for the ink color. In three constructed trials, participant p1 has a response time of 300 milliseconds and a second trial with no recorded time. Participant p2 has one trial at 500 milliseconds. How many trials does the table contain, how many people took part, and how many trials have a recorded response time?
library(tidyverse) makes tibble() and n_distinct() available in a new R session. Here, nrow() counts trials and n_distinct() counts each participant label once. length() counts every position in the time column, including a missing one. In sum(!is.na(trial_examples$rt_ms)), each observed time contributes 1 and each missing time 0.
1
2
3
4
5
6
7
8
9
10
| library(tidyverse)
trial_examples <- tibble(
participant = c("p1", "p1", "p2"),
rt_ms = c(300, NA, 500)
)
nrow(trial_examples)
n_distinct(trial_examples$participant)
length(trial_examples$rt_ms)
sum(!is.na(trial_examples$rt_ms))
|
1
2
3
4
| [1] 3
[1] 2
[1] 3
[1] 2
|
There are 3 trials, 2 participants and 2 observed response times. The time column’s length is 3 because the missing measurement also occupies a position.
Here, a group consists of all trials with the same participant label. dplyr::group_by() marks which rows belong together. summarise() returns one row per group, with n() counting trials and sum(!is.na(rt_ms)) counting observed times. Sorting the trials by response time separates the two p1 rows. Will they still count as one group?
1
2
3
4
5
6
7
8
9
| group_by(trial_examples, participant)
trial_examples |>
group_by(participant) |>
summarise(n_rows = n(), n_observed = sum(!is.na(rt_ms)))
reordered <- arrange(trial_examples, rt_ms)
reordered$participant
reordered |>
group_by(participant) |>
summarise(n_rows = n(), n_observed = sum(!is.na(rt_ms)))
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| # A tibble: 3 × 2
# Groups: participant [2]
participant rt_ms
<chr> <dbl>
1 p1 300
2 p1 NA
3 p2 500
# A tibble: 2 × 3
participant n_rows n_observed
<chr> <int> <int>
1 p1 2 1
2 p2 1 1
[1] "p1" "p2" "p1"
# A tibble: 2 × 3
participant n_rows n_observed
<chr> <int> <int>
1 p1 2 1
2 p2 1 1
|
The grouped table has three trial rows. The summary has two participant rows. p1 contributes two trials and one observed time, and p2 contributes one of each. The summary includes the participant column and is now ungrouped. Both p1 trials count toward the same totals even when p2 appears between them.
Suppose p3 has one trial with a missing time and p4 has no trial. Neither has an observed time. Will both appear in the summary with a count of zero?
1
2
3
4
5
6
7
8
9
| with_p3 <- tibble(
participant = c("p1", "p1", "p2", "p3"),
rt_ms = c(300, NA, 500, NA)
)
p3_counts <- with_p3 |>
group_by(participant) |>
summarise(n_rows = n(), n_observed = sum(!is.na(rt_ms)))
p3_counts
filter(p3_counts, participant == "p4")
|
1
2
3
4
5
6
7
8
| # A tibble: 3 × 3
participant n_rows n_observed
<chr> <int> <int>
1 p1 2 1
2 p2 1 1
3 p3 1 0
# A tibble: 0 × 3
# ℹ 3 variables: participant <chr>, n_rows <int>, n_observed <int>
|
Participant p3 has one record and zero observed times. Participant p4 has no summary row at all. Grouping these text identifiers creates groups only for labels present in the input, so it cannot create a zero-count row for an absent participant.
After import polars as pl, pl.DataFrame() builds the three trial rows below. None represents the missing time. height counts rows and n_unique() counts distinct participant labels. A Series’ length includes its null positions, whereas count() counts only non-null values.
1
2
3
4
5
6
7
| import polars as pl
trial_examples = pl.DataFrame({"participant": ["p1", "p1", "p2"], "rt_ms": [300, None, 500]})
trial_examples.height
trial_examples["participant"].n_unique()
len(trial_examples["rt_ms"])
trial_examples["rt_ms"].count()
|
There are 3 trials, 2 participants and 2 observed times. len() gives 3 because it includes the null position.
Here, a group consists of all trials with the same participant label. group_by("participant") defines those groups, and agg() returns one row per group. pl.len() counts all trials in the group and pl.col("rt_ms").count() counts its observed times. Sorting the summary by participant makes the two displays easy to compare. Sorting the input by time separates the two p1 trials.
1
2
3
4
5
6
7
8
9
10
11
12
| (
trial_examples.group_by("participant")
.agg(n_rows=pl.len(), n_observed=pl.col("rt_ms").count())
.sort("participant")
)
reordered = trial_examples.sort("rt_ms", nulls_last=True)
reordered["participant"].to_list()
(
reordered.group_by("participant")
.agg(n_rows=pl.len(), n_observed=pl.col("rt_ms").count())
.sort("participant")
)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| shape: (2, 3)
┌─────────────┬────────┬────────────┐
│ participant ┆ n_rows ┆ n_observed │
│ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ u32 │
╞═════════════╪════════╪════════════╡
│ p1 ┆ 2 ┆ 1 │
│ p2 ┆ 1 ┆ 1 │
└─────────────┴────────┴────────────┘
['p1', 'p2', 'p1']
shape: (2, 3)
┌─────────────┬────────┬────────────┐
│ participant ┆ n_rows ┆ n_observed │
│ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ u32 │
╞═════════════╪════════╪════════════╡
│ p1 ┆ 2 ┆ 1 │
│ p2 ┆ 1 ┆ 1 │
└─────────────┴────────┴────────────┘
|
Each result has one row per participant, with two trials and one time for p1 and one of each for p2. Separating the two p1 rows did not change their group. The count columns use Polars’ unsigned integer type u32, which stores only nonnegative whole numbers.
Participant p3 has a trial with a null time, and p4 has no trial. The grouped counts show whether both appear with zero observed times.
1
2
3
4
5
6
7
8
9
10
| with_p3 = pl.DataFrame(
{"participant": ["p1", "p1", "p2", "p3"], "rt_ms": [300, None, 500, None]}
)
p3_counts = (
with_p3.group_by("participant")
.agg(n_rows=pl.len(), n_observed=pl.col("rt_ms").count())
.sort("participant")
)
p3_counts
p3_counts.filter(pl.col("participant") == "p4")
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| shape: (3, 3)
┌─────────────┬────────┬────────────┐
│ participant ┆ n_rows ┆ n_observed │
│ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ u32 │
╞═════════════╪════════╪════════════╡
│ p1 ┆ 2 ┆ 1 │
│ p2 ┆ 1 ┆ 1 │
│ p3 ┆ 1 ┆ 0 │
└─────────────┴────────┴────────────┘
shape: (0, 3)
┌─────────────┬────────┬────────────┐
│ participant ┆ n_rows ┆ n_observed │
│ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ u32 │
╞═════════════╪════════╪════════════╡
└─────────────┴────────┴────────────┘
|
p3 appears with one trial and zero observed times. Selecting p4 returns no rows because the table has no trial for that participant.
Records and participants in the experiment
The constructed table contains only trials, but the experiment file combines different kinds of records. Do all rows in data/practice/trials.csv belong in a count of test trials? The file covers 40 completed Stroop runs. The trial_type column identifies the kinds of records, and the smallest and largest participant counts show whether every run contains the same number of rows.
Here, readr::read_csv() reads every field as text, treats empty fields as missing and includes any surrounding spaces.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| trials <- read_csv(
"data/practice/trials.csv",
col_types = cols(.default = col_character()),
na = "",
trim_ws = FALSE
)
dim(trials)
n_distinct(trials$participant)
unique(trials$trial_type)
record_counts <- trials |>
group_by(participant) |>
summarise(n_records = n())
head(record_counts, 3)
c(min(record_counts$n_records), max(record_counts$n_records), sum(record_counts$n_records))
|
1
2
3
4
5
6
7
8
9
10
| [1] 8040 11
[1] 40
[1] "keyboard" "survey"
# A tibble: 3 × 2
participant n_records
<chr> <int>
1 sub-001 201
2 sub-002 201
3 sub-003 201
[1] 201 201 8040
|
The file has 8,040 records and 11 columns. Only three participants are shown, but the minimum and maximum of n_records are both 201 across all 40. Each person’s 201 records include a questionnaire as well as keyboard trials, so 201 cannot serve as the number of test trials.
With infer_schema=False, pl.read_csv() reads the fields as text. The shape gives the record count, and trial_type shows whether every record is a trial. min() and max() reveal unequal participant counts, if any. The sum of all participant counts should match the row count.
1
2
3
4
5
6
7
8
9
10
11
12
| trials = pl.read_csv("data/practice/trials.csv", infer_schema=False)
trials.shape
trials["participant"].n_unique()
trials["trial_type"].unique(maintain_order=True).to_list()
record_counts = (
trials.group_by("participant")
.agg(n_records=pl.len())
.sort("participant")
)
record_counts.head(3)
n_records = record_counts["n_records"]
(n_records.min(), n_records.max(), n_records.sum())
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| (8040, 11)
40
['keyboard', 'survey']
shape: (3, 2)
┌─────────────┬───────────┐
│ participant ┆ n_records │
│ --- ┆ --- │
│ str ┆ u32 │
╞═════════════╪═══════════╡
│ sub-001 ┆ 201 │
│ sub-002 ┆ 201 │
│ sub-003 ┆ 201 │
└─────────────┴───────────┘
(201, 201, 8040)
|
The 40 participant counts are all 201 and sum to 8,040. The trial_type values include both keyboard and survey. To calculate test accuracy, the denominator should count only keyboard trials from the test blocks.
8.2 Summarizing each group in one row
Accuracy is the proportion of test trials answered correctly. A value of 0.9375 could mean 15 correct trials out of 16 or 180 out of 192. Each participant’s summary therefore reports both the number correct and the total number of test trials.
A correct answer scores 1 in correct. A wrong answer or a timeout scores 0. Even if no key is pressed within 2,500 milliseconds, that trial counts toward the total.
Each completed run contains eight practice trials, four test blocks of 48 trials and a final questionnaire. Table 8.1 shows how trial_type and block distinguish them. The participant column identifies whose trials contribute to each summary row.
Table 8.1. Records in one completed run of the Stroop task.
| Records | trial_type | block | Rows per run | Used for accuracy |
|---|
| Practice trials | keyboard | 0 | 8 | No |
| Test trials | keyboard | 1 to 4 | 192 | Yes |
| Questionnaire | survey | blank | 1 | No |
With cols_only() in readr::read_csv(), only the four requested columns are imported, in file order. participant and trial_type are text, and col_integer() reads block and correct as integers. The filter selects keyboard trials in blocks 1:4, the integers from 1 to 4. The missing count and distinct values show whether every selected trial has a 0 or 1 to sum.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| trials <- read_csv(
"data/practice/trials.csv",
col_types = cols_only(
participant = col_character(),
trial_type = col_character(),
block = col_integer(),
correct = col_integer()
),
na = "",
trim_ws = FALSE
)
glimpse(trials)
test_trials <- filter(trials, trial_type == "keyboard" & block %in% 1:4)
nrow(test_trials)
sum(is.na(test_trials$correct))
sort(unique(test_trials$correct))
|
1
2
3
4
5
6
7
8
9
| Rows: 8,040
Columns: 4
$ participant <chr> "sub-001", "sub-001", "sub-001", "sub-001", "sub-001", "su…
$ block <int> 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
$ trial_type <chr> "keyboard", "keyboard", "keyboard", "keyboard", "keyboard"…
$ correct <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
[1] 7680
[1] 0
[1] 0 1
|
The filter returns 7,680 rows. Their correct values are all observed and either 0 or 1, so summing them counts correct test trials.
Within each participant group, n() counts test trials and sum(correct) counts correct responses. These counts appear as n_test and n_correct. In summarise(), .groups = "drop" returns an ungrouped table, and group_vars() lists any grouping variables.
1
2
3
4
5
| counts <- test_trials |>
group_by(participant) |>
summarise(n_test = n(), n_correct = sum(correct), .groups = "drop")
dim(counts)
group_vars(counts)
|
1
2
| [1] 40 3
character(0)
|
There are 40 participant rows and three columns. character(0), an empty character vector, confirms that the table has no grouping.
For each row of counts, the ratio n_correct / n_test gives that participant’s accuracy. glimpse() shows the two integer counts alongside the resulting double.
1
2
| participant_accuracy <- mutate(counts, accuracy = n_correct / n_test)
glimpse(participant_accuracy)
|
1
2
3
4
5
6
| Rows: 40
Columns: 4
$ participant <chr> "sub-001", "sub-002", "sub-003", "sub-004", "sub-005", "su…
$ n_test <int> 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192…
$ n_correct <int> 180, 171, 178, 177, 176, 182, 181, 182, 181, 178, 179, 174…
$ accuracy <dbl> 0.9375000, 0.8906250, 0.9270833, 0.9218750, 0.9166667, 0.9…
|
pl.read_csv() reads four columns in the order listed in columns. With type inference off, participant and trial_type are strings. schema_overrides sets block and correct to Int64. The filter selects keyboard trials in blocks 1 to 4. null_count() and unique() check the selected correct values before they are summed.
1
2
3
4
5
6
7
8
9
10
11
12
13
| trials = pl.read_csv(
"data/practice/trials.csv",
columns=["participant", "trial_type", "block", "correct"],
infer_schema=False,
schema_overrides={"block": pl.Int64, "correct": pl.Int64},
)
trials.schema
test_trials = trials.filter(
(pl.col("trial_type") == "keyboard") & pl.col("block").is_in([1, 2, 3, 4])
)
test_trials.height
test_trials["correct"].null_count()
test_trials["correct"].unique().sort().to_list()
|
1
2
3
4
| Schema({'participant': String, 'trial_type': String, 'block': Int64, 'correct': Int64})
7680
0
[0, 1]
|
The selected 7,680 trials have no missing correctness values and only 0 and 1, so their sum counts the correct trials.
With test_trials grouped by participant, agg() gives two counts per person. pl.len() counts all their test trials in n_test, and pl.col("correct").sum() counts their correct responses in n_correct. The schema shows the type of each count.
1
2
3
4
5
| counts = test_trials.group_by("participant").agg(
n_test=pl.len(), n_correct=pl.col("correct").sum()
)
counts.shape
counts.schema
|
1
2
| (40, 3)
Schema({'participant': String, 'n_test': UInt32, 'n_correct': Int64})
|
The result has 40 participant rows. n_test is UInt32, used for row counts, while n_correct has the Int64 type of the summed column.
Dividing n_correct by n_test in counts.with_columns() adds each participant’s accuracy as a Float64 column.
1
2
3
4
| participant_accuracy = counts.with_columns(
accuracy=pl.col("n_correct") / pl.col("n_test")
)
participant_accuracy.schema
|
1
| Schema({'participant': String, 'n_test': UInt32, 'n_correct': Int64, 'accuracy': Float64})
|
Sorting both tables by participant makes their first three rows refer to the same people. The Polars grouped result has no guaranteed row order.
1
| head(arrange(participant_accuracy, participant), 3)
|
1
2
3
4
5
6
| # A tibble: 3 × 4
participant n_test n_correct accuracy
<chr> <int> <int> <dbl>
1 sub-001 192 180 0.938
2 sub-002 192 171 0.891
3 sub-003 192 178 0.927
|
1
| participant_accuracy.sort("participant").head(3)
|
1
2
3
4
5
6
7
8
9
10
| shape: (3, 4)
┌─────────────┬────────┬───────────┬──────────┐
│ participant ┆ n_test ┆ n_correct ┆ accuracy │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ i64 ┆ f64 │
╞═════════════╪════════╪═══════════╪══════════╡
│ sub-001 ┆ 192 ┆ 180 ┆ 0.9375 │
│ sub-002 ┆ 192 ┆ 171 ┆ 0.890625 │
│ sub-003 ┆ 192 ┆ 178 ┆ 0.927083 │
└─────────────┴────────┴───────────┴──────────┘
|
For sub-001, 180 correct trials out of 192 give 0.9375. R’s tibble display rounds that to 0.938, while Polars shows 0.9375. The stored ratio comes from the same counts.
A total of 7,680 test trials could still hide one participant with 191 and another with 193. The smallest and largest n_test reveal whether everyone has 192.
1
2
3
4
5
6
7
8
| c(
nrow(trials), nrow(test_trials),
nrow(participant_accuracy), n_distinct(participant_accuracy$participant)
)
c(
min(participant_accuracy$n_test), max(participant_accuracy$n_test),
sum(participant_accuracy$n_test)
)
|
1
2
| [1] 8040 7680 40 40
[1] 192 192 7680
|
1
2
3
4
5
6
7
8
| (
trials.height,
test_trials.height,
participant_accuracy.height,
participant_accuracy["participant"].n_unique(),
)
n_test = participant_accuracy["n_test"]
(n_test.min(), n_test.max(), n_test.sum())
|
1
2
| (8040, 7680, 40, 40)
(192, 192, 7680)
|
Of the 8,040 records, 7,680 are test trials. The summary has 40 rows for 40 distinct participants. The smallest and largest trial counts are both 192, so every participant contributed exactly 192 test trials.
8.3 Grouping by more than one variable
sub-001 had 180 correct responses in 192 test trials. Which block had the lowest accuracy? All four blocks had 48 trials, so the block with the fewest correct responses also had the lowest accuracy. The participant summary has no block labels. Grouping test_trials by both participant and block gives the counts for each block.
With participant and block in group_by(), summarise() counts trials and correct responses for each person in each block. Its message and group_vars() show whether both grouping variables still apply to the returned rows.
1
2
3
4
5
| block_counts <- test_trials |>
group_by(participant, block) |>
summarise(n_test = n(), n_correct = sum(correct))
dim(block_counts)
group_vars(block_counts)
|
1
2
3
4
5
6
7
8
| `summarise()` has regrouped the output.
ℹ Summaries were computed grouped by participant and block.
ℹ Output is grouped by participant.
ℹ Use `summarise(.groups = "drop_last")` to silence this message.
ℹ Use `summarise(.by = c(participant, block))` for per-operation grouping
(`?dplyr::dplyr_by`) instead.
[1] 160 4
[1] "participant"
|
Each of the 160 rows describes one block for one participant. The table includes both participant and block, but group_vars() lists only "participant". A grouped sum therefore uses all four block rows for that person.
Each block’s accuracy is its own n_correct / n_test. ungroup() makes no difference to that row-by-row division. Grouping matters for a sum across rows. With the participant grouping, sum(n_test) in mutate() gives 192 for each person. After ungroup(), it gives 7,680 across the whole table.
1
2
3
4
5
6
| block_accuracy <- block_counts |>
ungroup() |>
mutate(accuracy = n_correct / n_test) |>
arrange(participant, block)
group_vars(block_accuracy)
head(block_accuracy, 4)
|
1
2
3
4
5
6
7
8
| character(0)
# A tibble: 4 × 5
participant block n_test n_correct accuracy
<chr> <int> <int> <int> <dbl>
1 sub-001 1 48 45 0.938
2 sub-001 2 48 47 0.979
3 sub-001 3 48 46 0.958
4 sub-001 4 48 42 0.875
|
For sub-001, block 4 had the lowest accuracy, with 42 correct responses out of 48. Across the four blocks, 45 + 47 + 46 + 42 gives 180, the correct count in the participant table. character(0) confirms that block_accuracy is ungrouped.
In Polars, group_by("participant", "block") defines a group for each participant and block. The row count and sum of correct now describe that block. The returned DataFrame has no attached grouping.
1
2
3
4
| block_counts = test_trials.group_by("participant", "block").agg(
n_test=pl.len(), n_correct=pl.col("correct").sum()
)
block_counts.shape
|
The (160, 4) result has two key columns and two counts. A participant appears four times, so only participant and block together identify a row.
In with_columns(), dividing n_correct by n_test gives each block’s accuracy. After sort() orders the rows by participant and block, the first four show sub-001’s results in block order.
1
2
3
4
| block_accuracy = block_counts.with_columns(
accuracy=pl.col("n_correct") / pl.col("n_test")
).sort("participant", "block")
block_accuracy.head(4)
|
1
2
3
4
5
6
7
8
9
10
11
| shape: (4, 5)
┌─────────────┬───────┬────────┬───────────┬──────────┐
│ participant ┆ block ┆ n_test ┆ n_correct ┆ accuracy │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ u32 ┆ i64 ┆ f64 │
╞═════════════╪═══════╪════════╪═══════════╪══════════╡
│ sub-001 ┆ 1 ┆ 48 ┆ 45 ┆ 0.9375 │
│ sub-001 ┆ 2 ┆ 48 ┆ 47 ┆ 0.979167 │
│ sub-001 ┆ 3 ┆ 48 ┆ 46 ┆ 0.958333 │
│ sub-001 ┆ 4 ┆ 48 ┆ 42 ┆ 0.875 │
└─────────────┴───────┴────────┴───────────┴──────────┘
|
For sub-001, block 4 had the lowest accuracy, with 42 correct responses out of 48. Block 2 had the highest, with 47 out of 48. Both contribute to the overall 180 out of 192.
Each participant and block should appear together only once. dplyr::n_distinct() and the Polars DataFrame method n_unique() count the distinct pairs. If the four blocks account for all of a person’s test trials, summing their trial and correct counts should reproduce that person’s row in counts.
1
2
3
4
5
6
7
8
9
10
| c(
nrow(block_accuracy),
n_distinct(block_accuracy$participant, block_accuracy$block),
min(block_accuracy$n_test),
max(block_accuracy$n_test)
)
recombined <- block_accuracy |>
group_by(participant) |>
summarise(n_test = sum(n_test), n_correct = sum(n_correct))
identical(recombined, counts)
|
1
2
| [1] 160 160 48 48
[1] TRUE
|
1
2
3
4
5
6
7
8
9
10
11
12
| (
block_accuracy.height,
block_accuracy.select("participant", "block").n_unique(),
block_accuracy["n_test"].min(),
block_accuracy["n_test"].max(),
)
recombined = (
block_accuracy.group_by("participant")
.agg(pl.col("n_test").sum(), pl.col("n_correct").sum())
.sort("participant")
)
recombined.equals(counts.sort("participant"))
|
1
2
| (160, 160, 48, 48)
True
|
There are 160 rows and 160 distinct participant and block pairs, each with 48 test trials. Each trial belongs to exactly one block, so adding the four block counts for each participant reproduces both totals in counts.
8.4 Returning group calculations to the original rows
How far was each trial time above or below that participant’s mean? The same time can be fast for one person and slow for another, so each trial is compared with the mean of its own participant. In six constructed trials, p1 took 300, 500 and 700 milliseconds, and p2 took 400, 600 and 800. Subtracting a participant’s mean from each of their own trial times is called centering. The trial IDs t1 through t6 let us check which trial each difference describes.
Calculating a mean
The mean response time is the sum of the observed times divided by their number. We use constructed times here because we have yet to decide which recorded response times in the experiment are suitable for analysis.
All three of p1’s times are observed, so length(complete_rt_ms) gives the denominator for the mean. If a trial had no recorded time, counting its empty position would make that denominator too large for a mean of the observed times.
1
2
3
4
5
| complete_rt_ms <- c(300, 500, 700)
sum(complete_rt_ms)
length(complete_rt_ms)
sum(complete_rt_ms) / length(complete_rt_ms)
mean(complete_rt_ms)
|
1
2
3
4
| [1] 1500
[1] 3
[1] 500
[1] 500
|
The sum is 1,500 milliseconds over three times, giving a mean of 500 milliseconds by either calculation.
The Polars Series contains the same three observed times. Its sum divided by len() gives the mean, which the Series method mean() calculates directly.
1
2
3
4
5
| complete_rt_ms = pl.Series([300, 500, 700])
complete_rt_ms.sum()
len(complete_rt_ms)
complete_rt_ms.sum() / len(complete_rt_ms)
complete_rt_ms.mean()
|
1
2
3
4
| 1500
3
500.0
500.0
|
Both routes give 500.0 milliseconds. Division and the mean return floating-point values, even though these source times are integers.
One mean per participant
Grouping the six trials by participant gives two means. In dplyr, summarise() calculates mean(rt_ms) within each group. In Polars, agg() calculates the mean for each group defined by group_by().
1
2
3
4
5
6
7
8
| trial_examples <- tibble(
trial_id = c("t1", "t2", "t3", "t4", "t5", "t6"),
participant = c("p1", "p1", "p1", "p2", "p2", "p2"),
rt_ms = c(300, 500, 700, 400, 600, 800)
)
trial_examples |>
group_by(participant) |>
summarise(mean_rt_ms = mean(rt_ms))
|
1
2
3
4
5
| # A tibble: 2 × 2
participant mean_rt_ms
<chr> <dbl>
1 p1 500
2 p2 600
|
1
2
3
4
5
6
7
8
9
10
11
12
| trial_examples = pl.DataFrame(
{
"trial_id": ["t1", "t2", "t3", "t4", "t5", "t6"],
"participant": ["p1", "p1", "p1", "p2", "p2", "p2"],
"rt_ms": [300, 500, 700, 400, 600, 800],
}
)
(
trial_examples.group_by("participant")
.agg(mean_rt_ms=pl.col("rt_ms").mean())
.sort("participant")
)
|
1
2
3
4
5
6
7
8
9
| shape: (2, 2)
┌─────────────┬────────────┐
│ participant ┆ mean_rt_ms │
│ --- ┆ --- │
│ str ┆ f64 │
╞═════════════╪════════════╡
│ p1 ┆ 500.0 │
│ p2 ┆ 600.0 │
└─────────────┴────────────┘
|
The summary gives p1 a mean of 500 ms and p2 a mean of 600 ms. It has no row for an individual trial.
In R, subtracting the two means by position repeats 500, 600 across the six trials without a warning. On t2, that would give 500 − 600 = −100 ms even though p1 responded at their own mean. On a table grouped by participant, mutate() puts the result of mean(rt_ms) beside each of that person’s trials.
1
2
3
4
| with_means <- trial_examples |>
group_by(participant) |>
mutate(mean_rt_ms = mean(rt_ms))
with_means
|
1
2
3
4
5
6
7
8
9
10
| # A tibble: 6 × 4
# Groups: participant [2]
trial_id participant rt_ms mean_rt_ms
<chr> <chr> <dbl> <dbl>
1 t1 p1 300 500
2 t2 p1 500 500
3 t3 p1 700 500
4 t4 p2 400 600
5 t5 p2 600 600
6 t6 p2 800 600
|
All six trial IDs are in the result. The mean 500 appears beside each p1 trial and 600 beside each p2 trial. The table is still grouped, as the display’s Groups line shows.
deviation_ms is the trial’s rt_ms minus its participant’s mean_rt_ms. ungroup() removes the grouping afterward so later operations can use the full table unless a new grouping is specified.
1
2
3
4
| centered <- with_means |>
mutate(deviation_ms = rt_ms - mean_rt_ms) |>
ungroup()
centered
|
1
2
3
4
5
6
7
8
9
| # A tibble: 6 × 5
trial_id participant rt_ms mean_rt_ms deviation_ms
<chr> <chr> <dbl> <dbl> <dbl>
1 t1 p1 300 500 -200
2 t2 p1 500 500 0
3 t3 p1 700 500 200
4 t4 p2 400 600 -200
5 t5 p2 600 600 0
6 t6 p2 800 600 200
|
On t1, p1 responded 200 ms faster than their mean. On t3, the response was 200 ms slower. Participant p2 has the same deviations around a different mean. Within each person, the deviations should sum to zero. Comparing the original columns with trial_examples also checks trial identity and order.
1
2
3
4
5
| centered |>
group_by(participant) |>
summarise(n_rows = n(), total_deviation_ms = sum(deviation_ms))
n_distinct(centered$participant)
identical(select(centered, trial_id, participant, rt_ms), trial_examples)
|
1
2
3
4
5
6
7
| # A tibble: 2 × 3
participant n_rows total_deviation_ms
<chr> <int> <dbl>
1 p1 3 0
2 p2 3 0
[1] 2
[1] TRUE
|
The deviations sum to zero for each person. TRUE confirms that the original trial IDs, participant labels and times appear in the same order. The three copies of 500 ms all describe p1. Adding them would count that participant’s mean three times.
In Polars, a window expression returns a group calculation to its member rows. pl.col("rt_ms").mean().over("participant") computes each participant’s mean and repeats it on that participant’s trials within with_columns(). The labels in over() define membership even when matching rows are not adjacent. Without over(), the expression would use all six times and repeat their overall mean, 550.0.
1
2
3
4
| with_means = trial_examples.with_columns(
mean_rt_ms=pl.col("rt_ms").mean().over("participant")
)
with_means
|
1
2
3
4
5
6
7
8
9
10
11
12
13
| shape: (6, 4)
┌──────────┬─────────────┬───────┬────────────┐
│ trial_id ┆ participant ┆ rt_ms ┆ mean_rt_ms │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ f64 │
╞══════════╪═════════════╪═══════╪════════════╡
│ t1 ┆ p1 ┆ 300 ┆ 500.0 │
│ t2 ┆ p1 ┆ 500 ┆ 500.0 │
│ t3 ┆ p1 ┆ 700 ┆ 500.0 │
│ t4 ┆ p2 ┆ 400 ┆ 600.0 │
│ t5 ┆ p2 ┆ 600 ┆ 600.0 │
│ t6 ┆ p2 ┆ 800 ┆ 600.0 │
└──────────┴─────────────┴───────┴────────────┘
|
The six rows now have 500.0 for p1 and 600.0 for p2, with each trial’s original time beside its participant’s mean.
Subtracting mean_rt_ms from rt_ms in each row gives that trial’s deviation in milliseconds.
1
2
3
4
| centered = with_means.with_columns(
deviation_ms=pl.col("rt_ms") - pl.col("mean_rt_ms")
)
centered
|
1
2
3
4
5
6
7
8
9
10
11
12
13
| shape: (6, 5)
┌──────────┬─────────────┬───────┬────────────┬──────────────┐
│ trial_id ┆ participant ┆ rt_ms ┆ mean_rt_ms ┆ deviation_ms │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ f64 ┆ f64 │
╞══════════╪═════════════╪═══════╪════════════╪══════════════╡
│ t1 ┆ p1 ┆ 300 ┆ 500.0 ┆ -200.0 │
│ t2 ┆ p1 ┆ 500 ┆ 500.0 ┆ 0.0 │
│ t3 ┆ p1 ┆ 700 ┆ 500.0 ┆ 200.0 │
│ t4 ┆ p2 ┆ 400 ┆ 600.0 ┆ -200.0 │
│ t5 ┆ p2 ┆ 600 ┆ 600.0 ┆ 0.0 │
│ t6 ┆ p2 ┆ 800 ┆ 600.0 ┆ 200.0 │
└──────────┴─────────────┴───────┴────────────┴──────────────┘
|
For each participant, the first response was 200 ms faster than their mean, the second was at the mean, and the third was 200 ms slower. The deviations should sum to zero within each person.
1
2
3
4
5
6
7
| (
centered.group_by("participant")
.agg(n_rows=pl.len(), total_deviation_ms=pl.col("deviation_ms").sum())
.sort("participant")
)
centered["participant"].n_unique()
centered.select("trial_id", "participant", "rt_ms").equals(trial_examples)
|
1
2
3
4
5
6
7
8
9
10
11
| shape: (2, 3)
┌─────────────┬────────┬────────────────────┐
│ participant ┆ n_rows ┆ total_deviation_ms │
│ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ f64 │
╞═════════════╪════════╪════════════════════╡
│ p1 ┆ 3 ┆ 0.0 │
│ p2 ┆ 3 ┆ 0.0 │
└─────────────┴────────┴────────────────────┘
2
True
|
Each participant’s three deviations sum to zero. The final True confirms that the trial IDs, participant labels and original times are unchanged. The six rows describe two people, with each person’s mean repeated once beside each of their three trials.
If the mean is stored only approximately, the deviations can sum to a value slightly above or below zero. A check can use a tolerance, the largest distance from zero it will accept.
Filtering trials or filtering participant means
The centered table distinguishes each trial’s time from its participant’s mean. A cutoff applied to these two columns therefore asks different questions. Filtering trial times changes which observations contribute to each mean; filtering participant means selects people after their means have been calculated. Do the same participants appear under the two rules when the cutoff is 500 milliseconds?
With dplyr, filtering rt_ms before summarise() means only trials above 500 ms contribute to each mean. Filtering mean_rt_ms after summarise() tests the mean of all three trials for each person.
1
2
3
4
5
6
7
8
| trial_examples |>
filter(rt_ms > 500) |>
group_by(participant) |>
summarise(mean_above_ms = mean(rt_ms))
participant_means <- trial_examples |>
group_by(participant) |>
summarise(mean_rt_ms = mean(rt_ms))
filter(participant_means, mean_rt_ms > 500)
|
1
2
3
4
5
6
7
8
9
| # A tibble: 2 × 2
participant mean_above_ms
<chr> <dbl>
1 p1 700
2 p2 700
# A tibble: 1 × 2
participant mean_rt_ms
<chr> <dbl>
1 p2 600
|
In Polars, filtering rt_ms before group_by() selects individual trials. Filtering mean_rt_ms after agg() selects participants by their average time.
1
2
3
4
5
6
7
8
9
10
11
12
| (
trial_examples.filter(pl.col("rt_ms") > 500)
.group_by("participant")
.agg(mean_above_ms=pl.col("rt_ms").mean())
.sort("participant")
)
participant_means = (
trial_examples.group_by("participant")
.agg(mean_rt_ms=pl.col("rt_ms").mean())
.sort("participant")
)
participant_means.filter(pl.col("mean_rt_ms") > 500)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| shape: (2, 2)
┌─────────────┬───────────────┐
│ participant ┆ mean_above_ms │
│ --- ┆ --- │
│ str ┆ f64 │
╞═════════════╪═══════════════╡
│ p1 ┆ 700.0 │
│ p2 ┆ 700.0 │
└─────────────┴───────────────┘
shape: (1, 2)
┌─────────────┬────────────┐
│ participant ┆ mean_rt_ms │
│ --- ┆ --- │
│ str ┆ f64 │
╞═════════════╪════════════╡
│ p2 ┆ 600.0 │
└─────────────┴────────────┘
|
For p1, only t3 exceeds 500 ms, at 700 ms. For p2, t5 and t6 take 600 and 800 ms. Both participants therefore average 700 ms on trials above the cutoff. Across all three trials per person, p1 averages exactly 500 ms and p2 averages 600 ms. Only p2 has a mean above 500 ms.