Combining Tables With Keys
To compare responses to different stimuli, we need to know what each participant saw. The trial records give stimulus codes, but the words and ink colors are described in a separate table. We therefore need to connect each trial to the right description. This chapter shows how to assemble records from several tables, first by adding batches of trials and then by matching related information. We examine how the matching fields determine which records are connected, why some matches repeat a trial, and how to handle records with no match.
13.1 Adding rows with compatible columns
To analyze trials from separate batches together, we first need their measurements in the same columns. The three constructed batches in Table 13.1 each record trials, with one row for a stimulus presentation and any response to it. A participant who completed two trials contributes two rows. Which fields belong in the same column?
Table 13.1. Fields of three constructed trial batches.
| Batch | Fields in source order | Response time | Accuracy |
|---|---|---|---|
| a | participant, trial, rt, correct | rt, milliseconds | correct |
| b | rt, correct, trial, participant | rt, milliseconds | correct |
| c | participant, trial, RT_ms | RT_ms, milliseconds | absent |
Batches a and b have the same four fields in different orders. Batch c uses RT_ms where the others use rt. Both names refer here to the time from stimulus onset to response in integer milliseconds, so RT_ms can be renamed rt without changing its values. A field measured in seconds would also need a unit conversion. The target columns are participant, trial, rt, and correct, with participant stored as text and the others as whole numbers.
A 0 in correct records an incorrect response. Batch c has no correct field, so accuracy is unknown for its trials.
dplyr::rename() changes RT_ms to rt in batch c, and NA_integer_ gives its correct column the intended integer type. bind_rows() aligns columns by name, even when batch b lists them in a different order. It can also fill an absent column with NA.
To trace a combined row to its source, .id = "batch" records the argument name a, b, or c. Within each batch, row_number() numbers the source rows from 1.
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
library(tidyverse)
batch_a <- tibble(
participant = c("sub-101", "sub-101", "sub-102"),
trial = c(1L, 2L, 1L),
rt = c(512L, 634L, 701L),
correct = c(1L, 1L, 0L)
)
batch_b <- tibble(
rt = c(455L, 590L),
correct = c(1L, 1L),
trial = c(1L, 2L),
participant = c("sub-103", "sub-103")
)
batch_c <- tibble(
participant = c("sub-104", "sub-104"),
trial = c(1L, 2L),
RT_ms = c(820L, 760L)
)
standard_c <- batch_c |>
rename(rt = RT_ms) |>
mutate(correct = NA_integer_)
trials_all <- bind_rows(
a = mutate(batch_a, source_row = row_number()),
b = mutate(batch_b, source_row = row_number()),
c = mutate(standard_c, source_row = row_number()),
.id = "batch"
)
filter(trials_all, source_row == 1)
count(trials_all, batch)
c(nrow(trials_all), n_distinct(trials_all$participant))
1
2
3
4
5
6
7
8
9
10
11
12
13
# A tibble: 3 × 6
batch participant trial rt correct source_row
<chr> <chr> <int> <int> <int> <int>
1 a sub-101 1 512 1 1
2 b sub-103 1 455 1 1
3 c sub-104 1 820 NA 1
# A tibble: 3 × 2
batch n
<chr> <int>
1 a 3
2 b 2
3 c 2
[1] 7 4
In the first row from batch b, 455 is the response time in milliseconds and 1 marks a correct response. In the first row from batch c, rt is 820 and correct is NA. The batch counts add up to seven trials from four participants. For any trial, batch and source_row identify its original row.
The three batches need the same column names, order, and types for pl.concat(..., how="vertical") here. In batch c, RT_ms becomes rt and the absent correct field is represented by an Int64 null. select(columns) orders the columns consistently across the batches.
To identify the source of each combined row, the comprehension unpacks each (name, batch) pair, adds its label with pl.lit(name), and numbers its source rows with with_row_index("source_row", offset=1). pl.concat() then stacks the resulting tables.
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
import polars as pl
batch_a = pl.DataFrame(
{
"participant": ["sub-101", "sub-101", "sub-102"],
"trial": [1, 2, 1],
"rt": [512, 634, 701],
"correct": [1, 1, 0],
}
)
batch_b = pl.DataFrame(
{
"rt": [455, 590],
"correct": [1, 1],
"trial": [1, 2],
"participant": ["sub-103", "sub-103"],
}
)
batch_c = pl.DataFrame(
{"participant": ["sub-104", "sub-104"], "trial": [1, 2], "RT_ms": [820, 760]}
)
standard_c = batch_c.rename({"RT_ms": "rt"}).with_columns(
correct=pl.lit(None, dtype=pl.Int64)
)
columns = ["participant", "trial", "rt", "correct"]
trials_all = pl.concat(
[
batch.select(columns)
.with_row_index("source_row", offset=1)
.with_columns(batch=pl.lit(name))
for name, batch in [("a", batch_a), ("b", batch_b), ("c", standard_c)]
],
how="vertical",
)
trials_all.filter(pl.col("source_row") == 1)
1
2
3
4
5
6
7
8
9
10
shape: (3, 6)
┌────────────┬─────────────┬───────┬─────┬─────────┬───────┐
│ source_row ┆ participant ┆ trial ┆ rt ┆ correct ┆ batch │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ u32 ┆ str ┆ i64 ┆ i64 ┆ i64 ┆ str │
╞════════════╪═════════════╪═══════╪═════╪═════════╪═══════╡
│ 1 ┆ sub-101 ┆ 1 ┆ 512 ┆ 1 ┆ a │
│ 1 ┆ sub-103 ┆ 1 ┆ 455 ┆ 1 ┆ b │
│ 1 ┆ sub-104 ┆ 1 ┆ 820 ┆ null ┆ c │
└────────────┴─────────────┴───────┴─────┴─────────┴───────┘
Batch c’s first row has 820 under rt and null under correct because its source had no accuracy field. The batch and source row identify that record. Counting rows by batch gives the number of trials. Counting distinct participant values tells us how many people contributed them.
1
2
trials_all.group_by("batch").agg(n=pl.len()).sort("batch")
(trials_all.height, trials_all["participant"].n_unique())
1
2
3
4
5
6
7
8
9
10
11
shape: (3, 2)
┌───────┬─────┐
│ batch ┆ n │
│ --- ┆ --- │
│ str ┆ u32 │
╞═══════╪═════╡
│ a ┆ 3 │
│ b ┆ 2 │
│ c ┆ 2 │
└───────┴─────┘
(7, 4)
The batches contribute 3, 2, and 2 records, giving seven trials from four participants. sub-101, sub-103, and sub-104 each contribute two trials.
13.2 Matching keys and predicting row multiplication
Combining trial batches adds observations. Attaching a stimulus description adds information about an observation already recorded. A trial record stores a stimulus code, while a lookup table describes the word, ink, and condition. In this constructed example, trials t1, t2, and t3 presented S01, S01, and S02. The lookup has one description per stimulus. After matching on stim, each trial should still occupy one row, even though t1 and t2 share a stimulus code.
An equality join pairs rows with equal values in specified columns. The column or combination of columns used for this match is the join key. Here, stim identifies the stimulus description to attach. A separate column, trial_id, identifies the trial, so we can check whether each trial appears once after the join.
A left join includes every row of the first table, even when it has no match in the second. dplyr::left_join() uses by = join_by(stim) to match the trials in trials_small to the descriptions in stim_info. Each matching description adds word, ink, and cond to the trial.
1
2
3
4
5
6
7
8
trials_small <- tibble(trial_id = c("t1", "t2", "t3"), stim = c("S01", "S01", "S02"))
stim_info <- tibble(
stim = c("S01", "S02"),
word = c("red", "red"),
ink = c("red", "blue"),
cond = c("congruent", "incongruent")
)
left_join(trials_small, stim_info, by = join_by(stim))
1
2
3
4
5
6
# A tibble: 3 × 5
trial_id stim word ink cond
<chr> <chr> <chr> <chr> <chr>
1 t1 S01 red red congruent
2 t2 S01 red red congruent
3 t3 S02 red blue incongruent
Trials t1 and t2 both receive the sole S01 description. The result has three rows because each trial found exactly one lookup row, even though two trials used the same stimulus.
A second S01 description gives the ink as green. bind_rows() adds it to the lookup, so the same trial table and join call now encounter two descriptions for S01.
1
2
3
4
5
stim_info_dup <- bind_rows(
stim_info,
tibble(stim = "S01", word = "red", ink = "green", cond = "incongruent")
)
left_join(trials_small, stim_info_dup, by = join_by(stim))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# A tibble: 5 × 5
trial_id stim word ink cond
<chr> <chr> <chr> <chr> <chr>
1 t1 S01 red red congruent
2 t1 S01 red green incongruent
3 t2 S01 red red congruent
4 t2 S01 red green incongruent
5 t3 S02 red blue incongruent
Warning message:
In left_join(trials_small, stim_info_dup, by = join_by(stim)) :
Detected an unexpected many-to-many relationship between `x` and `y`.
ℹ Row 1 of `x` matches multiple rows in `y`.
ℹ Row 1 of `y` matches multiple rows in `x`.
ℹ If a many-to-many relationship is expected, set `relationship =
"many-to-many"` to silence this warning.
Both t1 and t2 now appear twice, once for each S01 description. The warning calls this many-to-many because an S01 trial matches several lookup rows and an S01 lookup row matches several trials. Setting relationship = "many-to-many" would accept that result. It would not choose between the two descriptions.
In trials_small.join(stim_info, on="stim", how="left"), on names the shared stimulus code and how="left" includes every trial. Each matching description adds the word, ink color, and condition. This join does not guarantee row order by default, so sort("trial_id") puts the trials in ID order for display.
1
2
3
4
5
6
7
8
9
10
11
12
trials_small = pl.DataFrame(
{"trial_id": ["t1", "t2", "t3"], "stim": ["S01", "S01", "S02"]}
)
stim_info = pl.DataFrame(
{
"stim": ["S01", "S02"],
"word": ["red", "red"],
"ink": ["red", "blue"],
"cond": ["congruent", "incongruent"],
}
)
trials_small.join(stim_info, on="stim", how="left").sort("trial_id")
1
2
3
4
5
6
7
8
9
10
shape: (3, 5)
┌──────────┬──────┬──────┬──────┬─────────────┐
│ trial_id ┆ stim ┆ word ┆ ink ┆ cond │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str ┆ str │
╞══════════╪══════╪══════╪══════╪═════════════╡
│ t1 ┆ S01 ┆ red ┆ red ┆ congruent │
│ t2 ┆ S01 ┆ red ┆ red ┆ congruent │
│ t3 ┆ S02 ┆ red ┆ blue ┆ incongruent │
└──────────┴──────┴──────┴──────┴─────────────┘
The two S01 trials each receive red ink and a congruent condition, where the word names its own ink color. Their trial identifiers differ, and each occurs once.
With a second S01 description in green ink, the lookup built by pl.concat() now has two possible matches for each S01 trial. Sorting the joined rows by trial_id and ink places each trial’s pairings together.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
stim_info_dup = pl.concat(
[
stim_info,
pl.DataFrame(
{
"stim": ["S01"],
"word": ["red"],
"ink": ["green"],
"cond": ["incongruent"],
}
),
],
how="vertical",
)
trials_small.join(stim_info_dup, on="stim", how="left").sort("trial_id", "ink")
1
2
3
4
5
6
7
8
9
10
11
12
shape: (5, 5)
┌──────────┬──────┬──────┬───────┬─────────────┐
│ trial_id ┆ stim ┆ word ┆ ink ┆ cond │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str ┆ str │
╞══════════╪══════╪══════╪═══════╪═════════════╡
│ t1 ┆ S01 ┆ red ┆ green ┆ incongruent │
│ t1 ┆ S01 ┆ red ┆ red ┆ congruent │
│ t2 ┆ S01 ┆ red ┆ green ┆ incongruent │
│ t2 ┆ S01 ┆ red ┆ red ┆ congruent │
│ t3 ┆ S02 ┆ red ┆ blue ┆ incongruent │
└──────────┴──────┴──────┴───────┴─────────────┘
The duplicate lookup produces five rows in both languages, although Polars issues no warning. Each of the two S01 trials finds two lookup rows, giving four pairings, and S02 adds one. The intended relationship is many-to-one, which means that many trials may use a stimulus but each stimulus should have one description. One lookup row per stimulus prevents the trial multiplication seen here.
The S09 conflict
The constructed lookup shows why a repeated code needs examination before a join. Does any stimulus in data/practice/stimuli.csv have two descriptions? For a repeated code, we need to compare the descriptions that a trial would receive.
The fields are read as text. In dplyr, count() followed by filter(n > 1) finds repeated stim codes. In Polars, group_by() with pl.len() gives the count to filter.
1
2
3
4
5
6
7
8
9
stimuli <- read_csv(
"data/practice/stimuli.csv",
col_types = cols(.default = col_character()),
na = "",
trim_ws = FALSE
)
count(stimuli, stim) |>
filter(n > 1)
filter(stimuli, stim == "S09")
1
2
3
4
5
6
7
8
9
# A tibble: 1 × 2
stim n
<chr> <int>
1 S09 2
# A tibble: 2 × 5
stim word ink cond correct_key
<chr> <chr> <chr> <chr> <chr>
1 S09 green red incongruent d
2 S09 green green congruent j
1
2
3
stimuli = pl.read_csv("data/practice/stimuli.csv", infer_schema=False)
stimuli.group_by("stim").agg(n=pl.len()).filter(pl.col("n") > 1)
stimuli.filter(pl.col("stim") == "S09")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
shape: (1, 2)
┌──────┬─────┐
│ stim ┆ n │
│ --- ┆ --- │
│ str ┆ u32 │
╞══════╪═════╡
│ S09 ┆ 2 │
└──────┴─────┘
shape: (2, 5)
┌──────┬───────┬───────┬─────────────┬─────────────┐
│ stim ┆ word ┆ ink ┆ cond ┆ correct_key │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str ┆ str │
╞══════╪═══════╪═══════╪═════════════╪═════════════╡
│ S09 ┆ green ┆ red ┆ incongruent ┆ d │
│ S09 ┆ green ┆ green ┆ congruent ┆ j │
└──────┴───────┴───────┴─────────────┴─────────────┘
Both S09 rows show the word green. One lists red ink and the other green ink. The task specifies green in red ink, an incongruent stimulus with d as the correct key. That identifies the red-ink row whichever order the lookup uses.
The accepted flag records which description agrees with the task. All codes other than S09 have a single lookup row. For S09, the word, ink, condition, and correct key must all match the specification. stimuli_accepted contains the selected rows.
The left join adds these descriptions to the keyboard trials, both practice and test. relationship = "many-to-one" raises an error if any trial matches several lookup rows. The combination of participant, block, and trial number identifies each trial, allowing us to check that the join neither omits nor repeats one.
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
stimuli_audit <- stimuli |>
mutate(
accepted = stim != "S09" |
(word == "green" & ink == "red" & cond == "incongruent" & correct_key == "d")
)
filter(stimuli_audit, stim == "S09")
stimuli_accepted <- stimuli_audit |>
filter(accepted) |>
select(-accepted)
c(nrow(stimuli_accepted), n_distinct(stimuli_accepted$stim))
trials <- read_csv(
"data/practice/trials.csv",
col_types = cols(.default = col_character()),
na = "",
trim_ws = FALSE
) |>
filter(trial_type == "keyboard")
trial_stim <- left_join(
trials,
stimuli_accepted,
by = join_by(stim),
relationship = "many-to-one"
)
c(
nrow(trials),
nrow(trial_stim),
n_distinct(trial_stim$participant, trial_stim$block, trial_stim$trial),
sum(is.na(trial_stim$cond)),
sum(trials$stim == "S09")
)
1
2
3
4
5
6
7
# A tibble: 2 × 6
stim word ink cond correct_key accepted
<chr> <chr> <chr> <chr> <chr> <lgl>
1 S09 green red incongruent d TRUE
2 S09 green green congruent j FALSE
[1] 16 16
[1] 8000 8000 8000 0 335
In Polars, the accepted expression tests the four S09 fields together. Both candidates appear in stimuli_audit, and the filter selects the lookup rows for the join. validate="m:1" requires unique lookup keys. The final counts show how many keyboard trials went into the join, how many rows and distinct trials came out, how many conditions are missing, and how many trials used S09.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
stimuli_audit = stimuli.with_columns(
accepted=(pl.col("stim") != "S09")
| (
(pl.col("word") == "green")
& (pl.col("ink") == "red")
& (pl.col("cond") == "incongruent")
& (pl.col("correct_key") == "d")
)
)
stimuli_audit.filter(pl.col("stim") == "S09")
stimuli_accepted = stimuli_audit.filter(pl.col("accepted")).drop("accepted")
(stimuli_accepted.height, stimuli_accepted["stim"].n_unique())
trials = pl.read_csv("data/practice/trials.csv", infer_schema=False).filter(
pl.col("trial_type") == "keyboard"
)
trial_stim = trials.join(stimuli_accepted, on="stim", how="left", validate="m:1")
(
trials.height,
trial_stim.height,
trial_stim.select("participant", "block", "trial").unique().height,
trial_stim["cond"].null_count(),
(trials["stim"] == "S09").sum(),
)
1
2
3
4
5
6
7
8
9
10
11
shape: (2, 6)
┌──────┬───────┬───────┬─────────────┬─────────────┬──────────┐
│ stim ┆ word ┆ ink ┆ cond ┆ correct_key ┆ accepted │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str ┆ str ┆ bool │
╞══════╪═══════╪═══════╪═════════════╪═════════════╪══════════╡
│ S09 ┆ green ┆ red ┆ incongruent ┆ d ┆ true │
│ S09 ┆ green ┆ green ┆ congruent ┆ j ┆ false │
└──────┴───────┴───────┴─────────────┴─────────────┴──────────┘
(16, 16)
(8000, 8000, 8000, 0, 335)
The lookup has 16 rows for 16 stimulus codes. All 8,000 keyboard trials appear once and have a condition. Using both S09 descriptions would count each of its 335 trials twice, giving 8,335 rows. Choosing the green-ink description alone would give 8,000 rows, but it would label all 335 trials congruent. The task specifies green in red ink, so those trials are incongruent.
13.3 Unmatched records and matched missing values
The stimulus join found a description for every trial. Other sources may cover different sets of records, so a join must also express which records belong in the result. A report on everyone enrolled, for example, needs a row even for someone without a questionnaire.
In a constructed trial study, the enrolled participants are p1, p2, and p3. The questionnaire table has a score of 4 for p1, a missing score for p2, and a score of 5 for p4. Each identifier occurs at most once in each source.
Both a questionnaire with no score and a missing questionnaire record produce a blank score after a left join. Marking every questionnaire row before the join lets us tell the two cases apart.
In R, mutate() adds the marker to scores. A left join returns every participant row and attaches the matching score fields. The following mutate() uses !is.na(in_scores) to turn the marker into TRUE for a match and FALSE otherwise.
1
2
3
4
5
6
participants <- tibble(id = c("p1", "p2", "p3"))
scores <- tibble(id = c("p1", "p2", "p4"), score = c(4, NA, 5))
scores_marked <- mutate(scores, in_scores = TRUE)
participant_scores <- left_join(participants, scores_marked, by = join_by(id)) |>
mutate(in_scores = !is.na(in_scores))
participant_scores
1
2
3
4
5
6
# A tibble: 3 × 3
id score in_scores
<chr> <dbl> <lgl>
1 p1 4 TRUE
2 p2 NA TRUE
3 p3 NA FALSE
Both p2 and p3 have NA in score. For p2, in_scores is TRUE because a questionnaire record exists. For p3, it is FALSE because there is no questionnaire record.
An inner join returns rows with IDs found in both tables. A full join also includes the unmatched rows from each table.
1
2
inner_join(participants, scores_marked, by = join_by(id))$id
full_join(participants, scores_marked, by = join_by(id))$id
1
2
[1] "p1" "p2"
[1] "p1" "p2" "p3" "p4"
The inner join removes p3, who has no score record. The full join adds p4, who has a score but is not in the enrollment table. Only the left join gives the requested enrolled population.
semi_join() lists enrolled participants who have a matching questionnaire record, and anti_join() lists those without one. Both return columns from the participant table only.
1
2
semi_join(participants, scores_marked, by = join_by(id))
anti_join(participants, scores_marked, by = join_by(id))
1
2
3
4
5
6
7
8
9
# A tibble: 2 × 1
id
<chr>
1 p1
2 p2
# A tibble: 1 × 1
id
<chr>
1 p3
The semi join includes p2 because the questionnaire record exists even though the score is missing. Only p3 appears in the anti join, just as only p3 had in_scores = FALSE.
In Polars, pl.lit(True) marks every score record before the left join on id. After the join, is_not_null() turns that marker into a Boolean flag for questionnaire coverage. The rows are displayed in id order.
1
2
3
4
5
6
7
8
9
participants = pl.DataFrame({"id": ["p1", "p2", "p3"]})
scores = pl.DataFrame({"id": ["p1", "p2", "p4"], "score": [4, None, 5]})
scores_marked = scores.with_columns(in_scores=pl.lit(True))
participant_scores = (
participants.join(scores_marked, on="id", how="left")
.with_columns(in_scores=pl.col("in_scores").is_not_null())
.sort("id")
)
participant_scores
1
2
3
4
5
6
7
8
9
10
shape: (3, 3)
┌─────┬───────┬───────────┐
│ id ┆ score ┆ in_scores │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ bool │
╞═════╪═══════╪═══════════╡
│ p1 ┆ 4 ┆ true │
│ p2 ┆ null ┆ true │
│ p3 ┆ null ┆ false │
└─────┴───────┴───────────┘
The three enrolled participants appear in the result. Both p2 and p3 have null scores. in_scores is true for p2, who has a questionnaire record, and false for p3, who has none.
In DataFrame.join(), how="inner" returns rows with matching keys and how="full" includes records from either source. A Polars full join normally returns two key columns, id and id_right. With coalesce=True, identifiers from both sources appear in one column.
1
2
3
4
5
6
inner = participants.join(scores_marked, on="id", how="inner")
inner["id"].sort().to_list()
full_split = participants.join(scores_marked, on="id", how="full")
full_split.select("id", "id_right").sort("id", nulls_last=True)
full_one = participants.join(scores_marked, on="id", how="full", coalesce=True)
full_one["id"].sort().to_list()
1
2
3
4
5
6
7
8
9
10
11
12
13
['p1', 'p2']
shape: (4, 2)
┌──────┬──────────┐
│ id ┆ id_right │
│ --- ┆ --- │
│ str ┆ str │
╞══════╪══════════╡
│ p1 ┆ p1 │
│ p2 ┆ p2 │
│ p3 ┆ null │
│ null ┆ p4 │
└──────┴──────────┘
['p1', 'p2', 'p3', 'p4']
The inner join returns p1 and p2. In the full join, p3 appears only in id, the enrollment column, and p4 only in id_right, the questionnaire column. With coalesce=True, the result has one ID column containing all four people.
The "semi" and "anti" join options select participant rows with and without a score-source match. They do not attach a score column.
1
2
participants.join(scores_marked, on="id", how="semi").sort("id")
participants.join(scores_marked, on="id", how="anti")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
shape: (2, 1)
┌─────┐
│ id │
│ --- │
│ str │
╞═════╡
│ p1 │
│ p2 │
└─────┘
shape: (1, 1)
┌─────┐
│ id │
│ --- │
│ str │
╞═════╡
│ p3 │
└─────┘
The semi join includes p2 because a questionnaire row exists. The anti join returns only p3, the enrolled participant with no questionnaire row.
Records without identifiers
Suppose the enrollment list also has a participant without an identifier, and an unidentified questionnaire has a score of 9. There is no evidence that these records belong to the same person. The in_participants and in_scores markers show which source contributed each row.
By default, dplyr::full_join() matches missing keys to one another. With na_matches = "never", the two unidentified records cannot match. The outputs show just the rows with missing identifiers.
1
2
3
4
5
6
7
8
9
10
participants_na <- bind_rows(participants, tibble(id = NA_character_)) |>
mutate(in_participants = TRUE)
scores_na <- bind_rows(
scores_marked,
tibble(id = NA_character_, score = 9, in_scores = TRUE)
)
full_join(participants_na, scores_na, by = join_by(id)) |>
filter(is.na(id))
full_join(participants_na, scores_na, by = join_by(id), na_matches = "never") |>
filter(is.na(id))
1
2
3
4
5
6
7
8
9
# A tibble: 1 × 4
id in_participants score in_scores
<chr> <lgl> <dbl> <lgl>
1 <NA> TRUE 9 TRUE
# A tibble: 2 × 4
id in_participants score in_scores
<chr> <lgl> <dbl> <lgl>
1 <NA> TRUE NA NA
2 <NA> NA 9 TRUE
The default join combines the unidentified records into one row with score 9 and both indicators set to TRUE. With na_matches = "never", it returns two separate rows. The participant row has no score, and the questionnaire row has no participant-source marker.
In Polars, nulls_equal=False makes the default rule explicit. Two missing IDs do not match. coalesce=True combines the ID columns, while the two source markers distinguish the unidentified rows.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
participants_na = pl.concat(
[participants, pl.DataFrame({"id": [None]}, schema=participants.schema)]
).with_columns(in_participants=pl.lit(True))
scores_na = pl.concat(
[
scores_marked,
pl.DataFrame(
{"id": [None], "score": [9], "in_scores": [True]},
schema=scores_marked.schema,
),
]
)
(
participants_na.join(
scores_na, on="id", how="full", coalesce=True, nulls_equal=False
)
.filter(pl.col("id").is_null())
.sort("score")
)
1
2
3
4
5
6
7
8
9
shape: (2, 4)
┌──────┬─────────────────┬───────┬───────────┐
│ id ┆ in_participants ┆ score ┆ in_scores │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ bool ┆ i64 ┆ bool │
╞══════╪═════════════════╪═══════╪═══════════╡
│ null ┆ true ┆ null ┆ null │
│ null ┆ null ┆ 9 ┆ true │
└──────┴─────────────────┴───────┴───────────┘
The row with in_scores set to true has the score of 9. The separate row with in_participants set to true has no score. Nothing in either source identifies the respondent who scored 9 as the unnamed enrollee.
13.4 Composite keys and category correspondence
A recorded name need not identify a single entity. The practice file data/practice/population.csv lists 229 districts, and Seoul and Busan both have a district named Jung-gu. To attach the right five-digit textbook code from region_codes.csv, we need to establish which fields distinguish these districts.
The first output counts repeated district names; the second lists the codes assigned to districts named Jung-gu. In dplyr, count() followed by filter(n > 1) finds the repeated names. In Polars, group_by() with pl.len() produces those counts. Reading the codes as text also preserves their leading zeros: 01002 is the recorded code, not the number 1002.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
population <- read_csv(
"data/practice/population.csv",
col_types = cols(.default = col_character()),
na = "",
trim_ws = FALSE
)
codes <- read_csv(
"data/practice/region_codes.csv",
col_types = cols(.default = col_character()),
na = "",
trim_ws = FALSE
)
count(population, sigungu) |>
filter(n > 1)
filter(codes, `District name` == "Jung-gu")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# A tibble: 7 × 2
sigungu n
<chr> <int>
1 Buk-gu 4
2 Dong-gu 6
3 Gangseo-gu 2
4 Goseong-gun 2
5 Jung-gu 6
6 Nam-gu 4
7 Seo-gu 5
# A tibble: 6 × 4
`Province code` `Province name` `District code` `District name`
<chr> <chr> <chr> <chr>
1 01 Seoul 01002 Jung-gu
2 02 Busan 02001 Jung-gu
3 03 Daegu 03001 Jung-gu
4 04 Incheon 04001 Jung-gu
5 06 Daejeon 06002 Jung-gu
6 07 Ulsan 07001 Jung-gu
1
2
3
4
population = pl.read_csv("data/practice/population.csv", infer_schema=False)
codes = pl.read_csv("data/practice/region_codes.csv", infer_schema=False)
population.group_by("sigungu").agg(n=pl.len()).filter(pl.col("n") > 1).sort("sigungu")
codes.filter(pl.col("District name") == "Jung-gu").sort("District code")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
shape: (7, 2)
┌─────────────┬─────┐
│ sigungu ┆ n │
│ --- ┆ --- │
│ str ┆ u32 │
╞═════════════╪═════╡
│ Buk-gu ┆ 4 │
│ Dong-gu ┆ 6 │
│ Gangseo-gu ┆ 2 │
│ Goseong-gun ┆ 2 │
│ Jung-gu ┆ 6 │
│ Nam-gu ┆ 4 │
│ Seo-gu ┆ 5 │
└─────────────┴─────┘
shape: (6, 4)
┌───────────────┬───────────────┬───────────────┬───────────────┐
│ Province code ┆ Province name ┆ District code ┆ District name │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str │
╞═══════════════╪═══════════════╪═══════════════╪═══════════════╡
│ 01 ┆ Seoul ┆ 01002 ┆ Jung-gu │
│ 02 ┆ Busan ┆ 02001 ┆ Jung-gu │
│ 03 ┆ Daegu ┆ 03001 ┆ Jung-gu │
│ 04 ┆ Incheon ┆ 04001 ┆ Jung-gu │
│ 06 ┆ Daejeon ┆ 06002 ┆ Jung-gu │
│ 07 ┆ Ulsan ┆ 07001 ┆ Jung-gu │
└───────────────┴───────────────┴───────────────┴───────────────┘
Jung-gu occurs in six regions. Its textbook code is 01002 in Seoul and 02001 in Busan. Matching on district name alone would give each of the six districts all six codes. Region and district together form a composite key.
The population table calls these columns sido and sigungu, and the code table calls them Province name and District name. Counting distinct pairs tests whether this combination identifies one row in each table. In R, n_distinct() accepts both columns. In Polars, n_unique() counts pairs after both columns are selected.
1
2
3
4
5
6
7
8
9
10
c(
nrow(population),
n_distinct(population$sigungu),
n_distinct(population$sido, population$sigungu)
)
c(
nrow(codes),
n_distinct(codes$`District name`),
n_distinct(codes$`Province name`, codes$`District name`)
)
1
2
[1] 229 207 229
[1] 229 207 229
1
2
3
4
5
6
7
8
9
10
(
population.height,
population["sigungu"].n_unique(),
population.select("sido", "sigungu").n_unique(),
)
(
codes.height,
codes["District name"].n_unique(),
codes.select("Province name", "District name").n_unique(),
)
1
2
(229, 207, 229)
(229, 207, 229)
Each table has 229 rows but only 207 district names. All 229 pairs of region and district are distinct, so a join on both fields can match each district to at most one code record.
Unique keys prevent multiple matches, but they do not guarantee that names for the same place agree across sources. Invisible characters can prevent a match. The first test finds population names that change when trailing whitespace is removed. The second looks for a zero-width space, U+200B, in the code table.
intToUtf8(0x200B) in R and chr(0x200B) in Python produce that character. stringr::str_remove_all() with fixed(zwsp) and Polars str.replace_all() with literal=True remove that exact character for comparison. In escaped output, it appears as \u200b.
1
2
3
4
5
6
zwsp <- intToUtf8(0x200B)
spaced <- filter(population, str_trim(sigungu, side = "right") != sigungu)
spaced$sigungu
zero_width <- codes |>
filter(str_remove_all(`District name`, fixed(zwsp)) != `District name`)
writeLines(stringi::stri_escape_unicode(zero_width$`District name`))
1
2
[1] "Haeundae-gu "
Chuncheon-si\u200b
1
2
3
4
5
6
7
8
zwsp = chr(0x200B)
spaced = population.filter(pl.col("sigungu").str.strip_chars_end() != pl.col("sigungu"))
spaced["sigungu"].to_list()
zero_width = codes.filter(
pl.col("District name").str.replace_all(zwsp, "", literal=True)
!= pl.col("District name")
)
zero_width["District name"].to_list()
1
2
['Haeundae-gu ']
['Chuncheon-si\u200b']
In the population file, Haeundae-gu ends with an extra space. In the code table, Chuncheon-si ends with U+200B. Whitespace trimming does not remove U+200B because Unicode does not classify it as whitespace. The join uses a new district_key in each table, trimming the population name and removing U+200B from the code-table name.
In R, mutate() creates district_key alongside each recorded name. join_by(sido == `Province name`, district_key) matches region to region and compares the two district keys. The left join includes every population row. relationship = "one-to-one" rejects multiple matches in either direction. nchar() measures the two original names.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
population_keyed <- mutate(
population,
district_key = str_trim(sigungu, side = "right")
)
codes_keyed <- mutate(
codes,
district_key = str_remove_all(`District name`, fixed(zwsp))
)
district_codes <- left_join(
population_keyed,
codes_keyed,
by = join_by(sido == `Province name`, district_key),
relationship = "one-to-one"
)
district_codes |>
filter(district_key %in% c("Haeundae-gu", "Chuncheon-si")) |>
mutate(population_chars = nchar(sigungu), code_chars = nchar(`District name`)) |>
select(sido, district_key, `District code`, population_chars, code_chars)
1
2
3
4
5
# A tibble: 2 × 5
sido district_key `District code` population_chars code_chars
<chr> <chr> <chr> <int> <int>
1 Busan Haeundae-gu 02009 12 11
2 Gangwon State Chuncheon-si 10001 12 13
Busan’s Haeundae-gu matches 02009. The population name has 12 characters and the code-table name has 11 because of the trailing space in the population file. For Chuncheon-si, code 10001, the extra character is in the code table, where the name has 13 characters instead of 12.
An anti join on the original names shows whether any other districts needed repair. The final vector compares input rows, joined rows, distinct district identities, missing codes, and distinct attached codes.
1
2
3
4
5
6
7
8
9
original_by <- join_by(sido == `Province name`, sigungu == `District name`)
sort(anti_join(population, codes, by = original_by)$sigungu)
c(
nrow(population),
nrow(district_codes),
n_distinct(district_codes$sido, district_codes$district_key),
sum(is.na(district_codes$`District code`)),
n_distinct(district_codes$`District code`)
)
1
2
[1] "Chuncheon-si" "Haeundae-gu "
[1] 229 229 229 0 229
Only the two inspected names were unmatched before repair. Afterward, all 229 districts occur once and have 229 distinct codes, with no missing code. The joined table therefore covers exactly the districts of the input.
In Polars, str.strip_chars_end() trims the population name. In the code table, str.replace_all() removes the literal zwsp character. left_on and right_on pair sido with Province name, then district_key with district_key. validate="1:1" checks uniqueness on both sides. str.len_chars() measures the original names 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
population_keyed = population.with_columns(
district_key=pl.col("sigungu").str.strip_chars_end()
)
codes_keyed = codes.with_columns(
district_key=pl.col("District name").str.replace_all(zwsp, "", literal=True)
)
district_codes = population_keyed.join(
codes_keyed,
left_on=["sido", "district_key"],
right_on=["Province name", "district_key"],
how="left",
validate="1:1",
)
(
district_codes.filter(
pl.col("district_key").is_in(["Haeundae-gu", "Chuncheon-si"])
)
.select(
"sido",
"district_key",
"District code",
population_chars=pl.col("sigungu").str.len_chars(),
code_chars=pl.col("District name").str.len_chars(),
)
.sort("sido")
)
1
2
3
4
5
6
7
8
9
shape: (2, 5)
┌───────────────┬──────────────┬───────────────┬──────────────────┬────────────┐
│ sido ┆ district_key ┆ District code ┆ population_chars ┆ code_chars │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ u32 ┆ u32 │
╞═══════════════╪══════════════╪═══════════════╪══════════════════╪════════════╡
│ Busan ┆ Haeundae-gu ┆ 02009 ┆ 12 ┆ 11 │
│ Gangwon State ┆ Chuncheon-si ┆ 10001 ┆ 12 ┆ 13 │
└───────────────┴──────────────┴───────────────┴──────────────────┴────────────┘
Busan’s Haeundae-gu matches 02009. The population name has 12 characters, one more than the code-table name. For Chuncheon-si, code 10001, the code-table name has 13 characters, one more than the population name.
The anti join identifies districts whose original names failed to match. After repair, the tuple checks whether every input district still appears once and has a nonmissing code used by no other district.
1
2
3
4
5
6
7
8
9
10
11
12
13
population.join(
codes,
left_on=["sido", "sigungu"],
right_on=["Province name", "District name"],
how="anti",
)["sigungu"].sort().to_list()
(
population.height,
district_codes.height,
district_codes.select("sido", "district_key").n_unique(),
district_codes["District code"].null_count(),
district_codes["District code"].n_unique(),
)
1
2
['Chuncheon-si', 'Haeundae-gu ']
(229, 229, 229, 0, 229)
Only Chuncheon-si and the population file’s Haeundae-gu with its trailing space failed to match on the original names. After the two repairs, all 229 districts occur once, with no null code and 229 distinct codes.
Region labels
Some corresponding names differ intentionally rather than because of an extra character. The survey records Chungbuk in Region, while the code table uses Chungcheongbuk-do for the same region. To make these labels comparable, a dictionary pairs each of the 17 survey labels with its code-table name. Both files use Seoul as written. A blank Region has no name to look up.
In R, tribble() defines the name pairs row by row, with column names after ~. count(survey, Region) counts submissions under each label. dplyr::recode_values() looks up its full name, which mutate() adds as province. The first check counts nonmissing labels without a mapping. The second counts mapped names found in the code table.
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
province_labels <- tribble(
~short, ~full,
"Seoul", "Seoul",
"Busan", "Busan",
"Daegu", "Daegu",
"Incheon", "Incheon",
"Gwangju", "Gwangju",
"Daejeon", "Daejeon",
"Ulsan", "Ulsan",
"Sejong", "Sejong",
"Gyeonggi", "Gyeonggi-do",
"Gangwon", "Gangwon State",
"Chungbuk", "Chungcheongbuk-do",
"Chungnam", "Chungcheongnam-do",
"Jeonbuk", "Jeonbuk State",
"Jeonnam", "Jeollanam-do",
"Gyeongbuk", "Gyeongsangbuk-do",
"Gyeongnam", "Gyeongsangnam-do",
"Jeju", "Jeju-do"
)
survey <- read_csv(
"data/practice/survey.csv",
col_types = cols(.default = col_character()),
na = "",
trim_ws = FALSE
)
region_labels <- count(survey, Region) |>
mutate(
province = recode_values(
Region,
from = province_labels$short,
to = province_labels$full
)
)
filter(region_labels, Region %in% c("Seoul", "Gyeonggi", "Gangwon", "Chungbuk"))
c(
sum(!is.na(region_labels$Region) & is.na(region_labels$province)),
sum(region_labels$province %in% codes$`Province name`)
)
1
2
3
4
5
6
7
8
# A tibble: 4 × 3
Region n province
<chr> <int> <chr>
1 Chungbuk 15 Chungcheongbuk-do
2 Gangwon 12 Gangwon State
3 Gyeonggi 133 Gyeonggi-do
4 Seoul 90 Seoul
[1] 0 17
For Chungbuk, 15 is the number of submissions and Chungcheongbuk-do is the corresponding name. All 17 nonblank labels have a mapping, and all 17 mapped names occur in Province name.
In Python, province_labels maps each short name to its full name. After the count by Region, replace_strict() maps each label and with_columns() adds the result as province. default=None makes an unrecognized label null. A null beside a nonblank source label signals a missing correspondence. is_in() tests whether the mapped names occur in the code table’s Province name column.
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
province_labels = {
"Seoul": "Seoul",
"Busan": "Busan",
"Daegu": "Daegu",
"Incheon": "Incheon",
"Gwangju": "Gwangju",
"Daejeon": "Daejeon",
"Ulsan": "Ulsan",
"Sejong": "Sejong",
"Gyeonggi": "Gyeonggi-do",
"Gangwon": "Gangwon State",
"Chungbuk": "Chungcheongbuk-do",
"Chungnam": "Chungcheongnam-do",
"Jeonbuk": "Jeonbuk State",
"Jeonnam": "Jeollanam-do",
"Gyeongbuk": "Gyeongsangbuk-do",
"Gyeongnam": "Gyeongsangnam-do",
"Jeju": "Jeju-do",
}
survey = pl.read_csv("data/practice/survey.csv", infer_schema=False)
region_labels = (
survey.group_by("Region")
.agg(n=pl.len())
.with_columns(
province=pl.col("Region").replace_strict(province_labels, default=None)
)
.sort("Region", nulls_last=True)
)
region_labels.filter(
pl.col("Region").is_in(["Seoul", "Gyeonggi", "Gangwon", "Chungbuk"])
)
(
region_labels.filter(
pl.col("Region").is_not_null() & pl.col("province").is_null()
).height,
region_labels["province"].is_in(codes["Province name"].to_list()).sum(),
)
1
2
3
4
5
6
7
8
9
10
11
12
shape: (4, 3)
┌──────────┬─────┬───────────────────┐
│ Region ┆ n ┆ province │
│ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ str │
╞══════════╪═════╪═══════════════════╡
│ Chungbuk ┆ 15 ┆ Chungcheongbuk-do │
│ Gangwon ┆ 12 ┆ Gangwon State │
│ Gyeonggi ┆ 133 ┆ Gyeonggi-do │
│ Seoul ┆ 90 ┆ Seoul │
└──────────┴─────┴───────────────────┘
(0, 17)
Fifteen submissions list Chungbuk. In the final pair of counts, 0 means every nonblank survey label has a mapping, and 17 is the number of mapped names found in the code table.
Removing -do from Chungcheongbuk-do gives Chungcheongbuk. Matching it to Chungbuk requires the pair listed in province_labels, just as matching Gangwon to Gangwon State does.
13.5 Matching an event to a preceding time
The joins so far have matched equal keys. A response to a scheduled prompt poses a different problem: its time usually differs from the prompt’s opening time. A momentary assessment app records both times, and we need to identify which of the participant’s prompts, if any, was open when the response arrived.
In a constructed example for participant e1 on April 1, 2024, prompt 1 opens at 09:00 and closes at 11:45, and prompt 2 opens at 11:45 and closes at 13:45. Responses arrive at 11:30, 11:45, and 14:00. All times use Asia/Seoul. An exact match on opening time would find only the 11:45 response. It would miss the 11:30 response even though prompt 1 was open.
The candidate is the participant’s most recent prompt opening at or before the response time. The opening time must be unique within that participant to identify one candidate. The response belongs to that prompt only if it arrived before closing.
ymd_hm() reads these clock times in the source zone specified by tz = "Asia/Seoul". The helper clock_view() formats them for display only. If the openings are unique within each participant, the prompt count equals the number of distinct (id, open) pairs.
In join_by(id, closest(at >= open)), id must match and closest() selects the nearest opening no later than at. It compares values, so sorting is unnecessary. The left join returns every event, including events whose candidates have already closed.
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
prompts <- tibble(
id = "e1",
prompt = c(1L, 2L),
open = ymd_hm(c("2024-04-01 09:00", "2024-04-01 11:45"), tz = "Asia/Seoul"),
close = ymd_hm(c("2024-04-01 11:45", "2024-04-01 13:45"), tz = "Asia/Seoul")
)
events <- tibble(
id = "e1",
event = c("a", "b", "c"),
at = ymd_hm(
c("2024-04-01 11:30", "2024-04-01 11:45", "2024-04-01 14:00"),
tz = "Asia/Seoul"
)
)
clock_view <- function(data) {
mutate(
data,
at = format(at, "%H:%M"),
open = format(open, "%H:%M"),
close = format(close, "%H:%M")
)
}
nrow(prompts) == n_distinct(prompts$id, prompts$open)
candidates <- left_join(events, prompts, by = join_by(id, closest(at >= open)))
clock_view(candidates)
1
2
3
4
5
6
7
[1] TRUE
# A tibble: 3 × 6
id event at prompt open close
<chr> <chr> <chr> <int> <chr> <chr>
1 e1 a 11:30 1 09:00 11:45
2 e1 b 11:45 2 11:45 13:45
3 e1 c 14:00 2 11:45 13:45
At 14:00, prompt 2 is the latest to have opened, but it closed at 13:45. The response window is the half-open interval [open, close). A response at the opening time is inside the window, and one at the closing time is outside it. At 11:45, prompt 1 closes just as prompt 2 opens.
difftime() gives the minutes since the candidate opened. The in_window test, at >= open & at < close, determines whether the candidate’s prompt number belongs in matched_prompt. The result includes the event and its candidate fields even when the test fails.
1
2
3
4
5
6
7
8
9
outcomes <- candidates |>
mutate(
minutes = as.numeric(difftime(at, open, units = "mins")),
in_window = at >= open & at < close,
matched_prompt = if_else(in_window, prompt, NA)
)
outcomes |>
clock_view() |>
select(event, at, prompt, open, close, minutes, in_window, matched_prompt)
1
2
3
4
5
6
# A tibble: 3 × 8
event at prompt open close minutes in_window matched_prompt
<chr> <chr> <int> <chr> <chr> <dbl> <lgl> <int>
1 a 11:30 1 09:00 11:45 150 TRUE 1
2 b 11:45 2 11:45 13:45 0 TRUE 2
3 c 14:00 2 11:45 13:45 135 FALSE NA
Event a arrived 150 minutes after prompt 1 opened and before it closed. Event b arrived exactly when prompt 2 opened. For c, prompt is 2 but matched_prompt is NA because 14:00 is after the 13:45 closing time.
In Polars, str.to_datetime() with time_zone="Asia/Seoul" reads the opening, closing, and response times. clock_view() formats them for display. The first check confirms that no participant has two prompts with the same opening time.
For each event, join_asof() with by="id" and strategy="backward" finds that participant’s latest opening at or before at. The result includes every event. Both tables must be in time order within each participant, so the code sorts by id and then by time. For this grouped join, check_sortedness=False suppresses the warning that Polars cannot verify the order.
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
minute_format = "%Y-%m-%d %H:%M"
prompts = pl.DataFrame(
{
"id": ["e1", "e1"],
"prompt": [1, 2],
"open": ["2024-04-01 09:00", "2024-04-01 11:45"],
"close": ["2024-04-01 11:45", "2024-04-01 13:45"],
}
).with_columns(
pl.col("open", "close").str.to_datetime(minute_format, time_zone="Asia/Seoul")
)
events = pl.DataFrame(
{
"id": ["e1", "e1", "e1"],
"event": ["a", "b", "c"],
"at": ["2024-04-01 11:30", "2024-04-01 11:45", "2024-04-01 14:00"],
}
).with_columns(pl.col("at").str.to_datetime(minute_format, time_zone="Asia/Seoul"))
def clock_view(data):
return data.with_columns(pl.col("at", "open", "close").dt.strftime("%H:%M"))
prompts.select("id", "open").n_unique() == prompts.height
candidates = events.sort("id", "at").join_asof(
prompts.sort("id", "open"),
left_on="at",
right_on="open",
by="id",
strategy="backward",
check_sortedness=False,
)
clock_view(candidates)
1
2
3
4
5
6
7
8
9
10
11
True
shape: (3, 6)
┌─────┬───────┬───────┬────────┬───────┬───────┐
│ id ┆ event ┆ at ┆ prompt ┆ open ┆ close │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ i64 ┆ str ┆ str │
╞═════╪═══════╪═══════╪════════╪═══════╪═══════╡
│ e1 ┆ a ┆ 11:30 ┆ 1 ┆ 09:00 ┆ 11:45 │
│ e1 ┆ b ┆ 11:45 ┆ 2 ┆ 11:45 ┆ 13:45 │
│ e1 ┆ c ┆ 14:00 ┆ 2 ┆ 11:45 ┆ 13:45 │
└─────┴───────┴───────┴────────┴───────┴───────┘
In Polars, applying dt.total_minutes() to at - open gives the number of whole minutes since the candidate opened. The & between at >= open and at < close requires both bounds, including the opening and excluding the closing. A pl.when() expression copies the candidate into matched_prompt inside the interval and returns null outside it.
1
2
3
4
5
6
7
8
9
10
11
outcomes = candidates.with_columns(
minutes=(pl.col("at") - pl.col("open")).dt.total_minutes(),
in_window=(pl.col("at") >= pl.col("open")) & (pl.col("at") < pl.col("close")),
).with_columns(
matched_prompt=pl.when(pl.col("in_window"))
.then(pl.col("prompt"))
.otherwise(None)
)
clock_view(outcomes).select(
"event", "at", "prompt", "open", "close", "minutes", "in_window", "matched_prompt"
)
1
2
3
4
5
6
7
8
9
10
shape: (3, 8)
┌───────┬───────┬────────┬───────┬───────┬─────────┬───────────┬────────────────┐
│ event ┆ at ┆ prompt ┆ open ┆ close ┆ minutes ┆ in_window ┆ matched_prompt │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ str ┆ str ┆ i64 ┆ bool ┆ i64 │
╞═══════╪═══════╪════════╪═══════╪═══════╪═════════╪═══════════╪════════════════╡
│ a ┆ 11:30 ┆ 1 ┆ 09:00 ┆ 11:45 ┆ 150 ┆ true ┆ 1 │
│ b ┆ 11:45 ┆ 2 ┆ 11:45 ┆ 13:45 ┆ 0 ┆ true ┆ 2 │
│ c ┆ 14:00 ┆ 2 ┆ 11:45 ┆ 13:45 ┆ 135 ┆ false ┆ null │
└───────┴───────┴────────┴───────┴───────┴─────────┴───────────┴────────────────┘
The 11:30 response arrived 150 minutes after prompt 1 opened, while it was still open. The 11:45 response belongs to prompt 2. At 14:00, only 135 minutes have passed since prompt 2 opened, but it closed at 13:45. The response has a candidate and a null matched_prompt.
A closer prompt from another participant
The participant key is necessary even when the time match appears plausible. Suppose a prompt opens for e2 at 11:20. If time alone decides the match, whose prompt will e1’s 11:30 response receive?
The constructed prompts follow the study’s closing rule: each closes at the next opening for the same participant that day, and the last closes after 120 minutes. bind_rows() in R and pl.concat() in Polars add the new prompt. The Polars pipe() call passes the joined table to clock_view() for display.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
prompts_two <- bind_rows(
prompts,
tibble(
id = "e2",
prompt = 1L,
open = ymd_hm("2024-04-01 11:20", tz = "Asia/Seoul"),
close = ymd_hm("2024-04-01 13:20", tz = "Asia/Seoul")
)
)
left_join(events, prompts_two, by = join_by(closest(at >= open))) |>
filter(event == "a") |>
clock_view() |>
select(event, id.x, id.y, at, prompt, open)
left_join(events, prompts_two, by = join_by(id, closest(at >= open))) |>
filter(event == "a") |>
clock_view() |>
select(event, id, at, prompt, open)
1
2
3
4
5
6
7
8
# A tibble: 1 × 6
event id.x id.y at prompt open
<chr> <chr> <chr> <chr> <int> <chr>
1 a e1 e2 11:30 1 11:20
# A tibble: 1 × 5
event id at prompt open
<chr> <chr> <chr> <int> <chr>
1 a e1 11:30 1 09:00
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
prompt_e2 = pl.DataFrame(
{
"id": ["e2"],
"prompt": [1],
"open": ["2024-04-01 11:20"],
"close": ["2024-04-01 13:20"],
}
).with_columns(
pl.col("open", "close").str.to_datetime(minute_format, time_zone="Asia/Seoul")
)
prompts_two = pl.concat([prompts, prompt_e2])
(
events.sort("at")
.join_asof(
prompts_two.sort("open"), left_on="at", right_on="open", strategy="backward"
)
.filter(pl.col("event") == "a")
.pipe(clock_view)
.select("event", "id", "id_right", "at", "prompt", "open")
)
(
events.sort("id", "at")
.join_asof(
prompts_two.sort("id", "open"),
left_on="at",
right_on="open",
by="id",
strategy="backward",
check_sortedness=False,
)
.filter(pl.col("event") == "a")
.pipe(clock_view)
.select("event", "id", "at", "prompt", "open")
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
shape: (1, 6)
┌───────┬─────┬──────────┬───────┬────────┬───────┐
│ event ┆ id ┆ id_right ┆ at ┆ prompt ┆ open │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str ┆ i64 ┆ str │
╞═══════╪═════╪══════════╪═══════╪════════╪═══════╡
│ a ┆ e1 ┆ e2 ┆ 11:30 ┆ 1 ┆ 11:20 │
└───────┴─────┴──────────┴───────┴────────┴───────┘
shape: (1, 5)
┌───────┬─────┬───────┬────────┬───────┐
│ event ┆ id ┆ at ┆ prompt ┆ open │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ i64 ┆ str │
╞═══════╪═════╪═══════╪════════╪═══════╡
│ a ┆ e1 ┆ 11:30 ┆ 1 ┆ 09:00 │
└───────┴─────┴───────┴────────┴───────┘
Both results show prompt 1. In the time-only match, the 11:30 response came from e1, but the 11:20 prompt went to e2. Matching on participant as well gives e1’s 09:00 prompt, which was still open at 11:30.