Post

Matching Scheduled Prompts and Responses

An app scheduled 4,200 prompts and received 3,323 submissions. How many prompts went unanswered? Because some prompts received two submissions, the answer requires matching each submission to the prompt that was open for that participant. This chapter builds that match by interpreting the exported answers and clock readings, checking response windows, and selecting among repeated submissions. We then connect the selected responses to the full schedule, making unanswered prompts visible and separating response coverage from the availability of a mood rating. That ordered schedule also lets us define changes between consecutive prompts rather than between whichever responses happen to be observed.

23.1 Establishing scheduled and submitted observation units

Ecological momentary assessment (EMA) collects short reports repeatedly during daily life. Here an app prompted 60 participants five times a day for 14 days to rate mood, stress, and energy. The schedule records each prompt, one opportunity to answer. A separate export records the submissions. An unanswered prompt has a schedule row but no submission of its own. Two submissions can also answer the same prompt.

Each scheduled prompt has a three-part key. id identifies the participant, day is the study day from 1 to 14, and prompt is the position within the day from 1 to 5. That gives 70 opportunities per person and 4,200 in total. The schedule should have that many rows and as many distinct keys. prompt_time gives each opening in Korean local time.

In data/raw/ema/ema_responses.json, the responses array contains submissions, while the other top-level fields describe the export. The export gives submissions no IDs. Here event 1 is the first submission in the original array. Assigning IDs from those positions before flattening or sorting lets us trace each event back to the export.

In readr::read_csv(), the column types specify text for IDs and clock readings and integers for days and prompt numbers. The row and key counts check that the schedule has one row per opportunity. Counting days and opportunities within each person checks the planned 14-day, 70-prompt schedule.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
library(tidyverse)

schedule <- read_csv(
  "data/raw/ema/ema_schedule.csv",
  col_types = cols(
    id = col_character(),
    day = col_integer(),
    prompt = col_integer(),
    prompt_time = col_character()
  ),
  na = "",
  trim_ws = FALSE
)
c(
  rows = nrow(schedule),
  keys = n_distinct(schedule$id, schedule$day, schedule$prompt),
  people = n_distinct(schedule$id)
)
per_person <- schedule |>
  summarise(days = n_distinct(day), opportunities = n(), .by = id)
count(per_person, days, opportunities, name = "people")
slice(schedule, 1)
1
2
3
4
5
6
7
8
9
10
  rows   keys people 
  4200   4200     60 
# A tibble: 1 × 3
   days opportunities people
  <int>         <int>  <int>
1    14            70     60
# A tibble: 1 × 4
  id      day prompt prompt_time        
  <chr> <int>  <int> <chr>              
1 E001      1      1 2024-04-01 09:47:00

The schedule contains 4,200 distinct opportunities, with 70 over 14 days for every participant. The submission export has a different unit: one record per event. With simplifyVector = FALSE, jsonlite::read_json() reads each submission as a list. seq_along() assigns its source position as the event ID, and str() reveals the participant, recorded time, and nested answers.

1
2
3
4
5
6
7
8
9
10
11
12
export <- jsonlite::read_json(
  "data/raw/ema/ema_responses.json",
  simplifyVector = FALSE
)
names(export)
event_records <- tibble(
  event_id = seq_along(export$responses),
  record = export$responses
)
print(event_records, n = 2)
str(event_records$record[[1]])
event_records$record[[3323]]$user_id
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[1] "export_version" "exported_at"    "note"           "responses"     
# A tibble: 3,323 × 2
  event_id record          
     <int> <list>          
1        1 <named list [3]>
2        2 <named list [3]>
# ℹ 3,321 more rows
# ℹ Use `print(n = ...)` to see more rows
List of 3
 $ user_id     : chr "E009"
 $ submitted_at: chr "2024-04-01T00:31:32"
 $ answers     :List of 3
  ..$ mood  : int 3
  ..$ stress: int 3
  ..$ energy: int 6
[1] "E058"

pl.read_csv() uses infer_schema=False for text fields and integer overrides for day and prompt. The row and key counts check that the schedule has one row per opportunity. Counting days and opportunities within each person checks the planned 14-day, 70-prompt schedule.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import json
from pathlib import Path

import polars as pl

schedule = pl.read_csv(
    "data/raw/ema/ema_schedule.csv",
    infer_schema=False,
    schema_overrides={"day": pl.Int64, "prompt": pl.Int64},
)
{
    "rows": schedule.height,
    "keys": schedule.select("id", "day", "prompt").n_unique(),
    "people": schedule["id"].n_unique(),
}
per_person = schedule.group_by("id").agg(
    days=pl.col("day").n_unique(), opportunities=pl.len()
)
per_person.group_by("days", "opportunities").agg(people=pl.len())
schedule.head(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{'rows': 4200, 'keys': 4200, 'people': 60}
shape: (1, 3)
┌──────┬───────────────┬────────┐
│ days ┆ opportunities ┆ people │
│ ---  ┆ ---           ┆ ---    │
│ u32  ┆ u32           ┆ u32    │
╞══════╪═══════════════╪════════╡
│ 14   ┆ 70            ┆ 60     │
└──────┴───────────────┴────────┘
shape: (1, 4)
┌──────┬─────┬────────┬─────────────────────┐
│ id   ┆ day ┆ prompt ┆ prompt_time         │
│ ---  ┆ --- ┆ ---    ┆ ---                 │
│ str  ┆ i64 ┆ i64    ┆ str                 │
╞══════╪═════╪════════╪═════════════════════╡
│ E001 ┆ 1   ┆ 1      ┆ 2024-04-01 09:47:00 │
└──────┴─────┴────────┴─────────────────────┘

The schedule contains 4,200 distinct opportunities, with 70 over 14 days for every participant. The submission export instead contains events without assigned IDs. json.loads() reads that structure, and enumerate(..., start=1) numbers the submissions by source position. The resulting dictionary uses 1 for its first key, so event_records[1] refers to responses[0].

1
2
3
4
5
6
7
8
9
export_path = Path("data/raw/ema/ema_responses.json")
export = json.loads(export_path.read_text(encoding="utf-8"))
list(export)
responses = export["responses"]
event_records = dict(enumerate(responses, start=1))
(len(event_records), min(event_records), max(event_records))
event_records[1]
event_records[1] is responses[0]
event_records[3323]["user_id"]
1
2
3
4
5
['export_version', 'exported_at', 'note', 'responses']
(3323, 1, 3323)
{'user_id': 'E009', 'submitted_at': '2024-04-01T00:31:32', 'answers': {'mood': 3, 'stress': 3, 'energy': 6}}
True
'E058'

The schedule identifies each of a participant’s 70 prompts by day and prompt number. An event ID tells us where to find a submission in the export. It does not tell us which of those 70 prompts the participant answered.

1
2
3
4
5
6
7
8
9
10
11
source_counts <- tibble(
  source = c("schedule", "schedule", "export"),
  unit = c("opportunity", "opportunities per person", "submitted event"),
  identity = c("id, day, prompt", "rows per id", "array position"),
  count = c(
    n_distinct(schedule$id, schedule$day, schedule$prompt),
    unique(per_person$opportunities),
    n_distinct(event_records$event_id)
  )
)
source_counts
1
2
3
4
5
6
# A tibble: 3 × 4
  source   unit                     identity        count
  <chr>    <chr>                    <chr>           <int>
1 schedule opportunity              id, day, prompt  4200
2 schedule opportunities per person rows per id        70
3 export   submitted event          array position   3323
1
2
3
4
5
6
7
8
9
10
11
12
13
source_counts = pl.DataFrame(
    {
        "source": ["schedule", "schedule", "export"],
        "unit": ["opportunity", "opportunities per person", "submitted event"],
        "identity": ["id, day, prompt", "rows per id", "array position"],
        "count": [
            schedule.select("id", "day", "prompt").n_unique(),
            per_person["opportunities"].unique().item(),
            len(event_records),
        ],
    }
)
source_counts
1
2
3
4
5
6
7
8
9
10
shape: (3, 4)
┌──────────┬──────────────────────────┬─────────────────┬───────┐
│ source   ┆ unit                     ┆ identity        ┆ count │
│ ---      ┆ ---                      ┆ ---             ┆ ---   │
│ str      ┆ str                      ┆ str             ┆ i64   │
╞══════════╪══════════════════════════╪═════════════════╪═══════╡
│ schedule ┆ opportunity              ┆ id, day, prompt ┆ 4200  │
│ schedule ┆ opportunities per person ┆ rows per id     ┆ 70    │
│ export   ┆ submitted event          ┆ array position  ┆ 3323  │
└──────────┴──────────────────────────┴─────────────────┴───────┘

Study day and calendar date

Submissions give the participant and time but no study day or prompt number. Can the calendar date tell us which study day to use? The schedule shows when day 1 began for E001 and E011, who entered a week apart.

1
2
3
4
5
schedule |>
  filter(day == 1, prompt == 1) |>
  count(start = substr(prompt_time, 1, 10), name = "people")
schedule |>
  filter(id %in% c("E001", "E011"), day %in% c(1, 8), prompt == 1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# A tibble: 6 × 2
  start      people
  <chr>       <int>
1 2024-04-01     10
2 2024-04-08     10
3 2024-04-15     10
4 2024-04-22     10
5 2024-04-29     10
6 2024-05-06     10
# A tibble: 4 × 4
  id      day prompt prompt_time        
  <chr> <int>  <int> <chr>              
1 E001      1      1 2024-04-01 09:47:00
2 E001      8      1 2024-04-08 10:02:00
3 E011      1      1 2024-04-08 10:06:00
4 E011      8      1 2024-04-15 09:30:00
1
2
3
4
5
6
7
8
9
10
11
(
    schedule.filter((pl.col("day") == 1) & (pl.col("prompt") == 1))
    .group_by(start=pl.col("prompt_time").str.slice(0, 10))
    .agg(people=pl.len())
    .sort("start")
)
schedule.filter(
    pl.col("id").is_in(["E001", "E011"])
    & pl.col("day").is_in([1, 8])
    & (pl.col("prompt") == 1)
).sort("id", "day")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
shape: (6, 2)
┌────────────┬────────┐
│ start      ┆ people │
│ ---        ┆ ---    │
│ str        ┆ u32    │
╞════════════╪════════╡
│ 2024-04-01 ┆ 10     │
│ 2024-04-08 ┆ 10     │
│ 2024-04-15 ┆ 10     │
│ 2024-04-22 ┆ 10     │
│ 2024-04-29 ┆ 10     │
│ 2024-05-06 ┆ 10     │
└────────────┴────────┘
shape: (4, 4)
┌──────┬─────┬────────┬─────────────────────┐
│ id   ┆ day ┆ prompt ┆ prompt_time         │
│ ---  ┆ --- ┆ ---    ┆ ---                 │
│ str  ┆ i64 ┆ i64    ┆ str                 │
╞══════╪═════╪════════╪═════════════════════╡
│ E001 ┆ 1   ┆ 1      ┆ 2024-04-01 09:47:00 │
│ E001 ┆ 8   ┆ 1      ┆ 2024-04-08 10:02:00 │
│ E011 ┆ 1   ┆ 1      ┆ 2024-04-08 10:06:00 │
│ E011 ┆ 8   ┆ 1      ┆ 2024-04-15 09:30:00 │
└──────┴─────┴────────┴─────────────────────┘

April 8 is day 8 for E001 and day 1 for E011. The six groups started a week apart. To find a submission’s study day and prompt number, we need that participant’s opening times.

23.2 Interpreting nested answers and clock readings

A participant can report mood without answering the energy item. Such a submission still needs to be matched to a prompt. Event 10 illustrates the export’s structure: answers contains only the items answered, each a whole number from 1 to 7. We first extract these answers without discarding the event, then interpret its recorded time so that it can be compared with the schedule.

1
str(event_records$record[[10]])
1
2
3
4
5
6
List of 3
 $ user_id     : chr "E009"
 $ submitted_at: chr "2024-04-01T02:57:45"
 $ answers     :List of 2
  ..$ mood  : int 4
  ..$ stress: int 2
1
event_records[10]
1
{'user_id': 'E009', 'submitted_at': '2024-04-01T02:57:45', 'answers': {'mood': 4, 'stress': 2}}

Event 10 has mood and stress but no energy key. Its participant and submission time are present, so the unanswered item does not prevent matching.

In R, two unnest_wider() calls flatten the event and its answers, and the absent energy cell becomes NA. For each answer column, answer_status() classifies the recorded code as absent, valid, or invalid. The counts show which fields are missing. Even a partly answered submission should still appear under its original event ID.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
events <- event_records |>
  unnest_wider(record) |>
  unnest_wider(answers)
answer_status <- function(code) {
  case_when(
    is.na(code) ~ "absent",
    code %in% 1:7 ~ "valid",
    .default = "invalid"
  )
}
events <- events |>
  mutate(across(c(mood, stress, energy), answer_status, .names = "{.col}_status"))
events |>
  filter(event_id == 10) |>
  select(event_id, user_id, submitted_at, energy, energy_status)
events |>
  pivot_longer(ends_with("_status"), names_to = "field", values_to = "status") |>
  count(field, status)
nrow(events)
identical(events$event_id, event_records$event_id)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# A tibble: 1 × 5
  event_id user_id submitted_at        energy energy_status
     <int> <chr>   <chr>                <int> <chr>        
1       10 E009    2024-04-01T02:57:45     NA absent       
# A tibble: 6 × 3
  field         status     n
  <chr>         <chr>  <int>
1 energy_status absent    77
2 energy_status valid   3246
3 mood_status   absent    68
4 mood_status   valid   3255
5 stress_status absent    60
6 stress_status valid   3263
[1] 3323
[1] TRUE

Each response dictionary becomes one Polars row. **record copies its fields beside the original event ID. The export stores ratings as integers, so the answers struct declares an integer field for each item. unnest() expands the three item fields into columns, with null for an omitted key.

answer_status() distinguishes a missing value, a code from 1 to 7, and an out-of-range code. The status counts describe the answers; comparing the event IDs with the original sequence separately checks that every submission has a row.

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
answer_fields = pl.Struct({"mood": pl.Int64, "stress": pl.Int64, "energy": pl.Int64})
event_schema = {
    "event_id": pl.Int64,
    "user_id": pl.String,
    "submitted_at": pl.String,
    "answers": answer_fields,
}
events = pl.DataFrame(
    [{"event_id": event_id, **record} for event_id, record in event_records.items()],
    schema=event_schema,
).unnest("answers")
answer_names = ["mood", "stress", "energy"]


def answer_status(name):
    code = pl.col(name)
    return (
        pl.when(code.is_null())
        .then(pl.lit("absent"))
        .when(code.is_between(1, 7))
        .then(pl.lit("valid"))
        .otherwise(pl.lit("invalid"))
        .alias(f"{name}_status")
    )


events = events.with_columns([answer_status(name) for name in answer_names])
events.filter(pl.col("event_id") == 10).select(
    "event_id", "user_id", "submitted_at", "energy", "energy_status"
)
(
    events.unpivot(
        on=[f"{name}_status" for name in answer_names],
        index="event_id",
        variable_name="field",
        value_name="status",
    )
    .group_by("field", "status")
    .agg(n=pl.len())
    .sort("field", "status")
)
(events.height, events["event_id"].to_list() == list(event_records))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
shape: (1, 5)
┌──────────┬─────────┬─────────────────────┬────────┬───────────────┐
│ event_id ┆ user_id ┆ submitted_at        ┆ energy ┆ energy_status │
│ ---      ┆ ---     ┆ ---                 ┆ ---    ┆ ---           │
│ i64      ┆ str     ┆ str                 ┆ i64    ┆ str           │
╞══════════╪═════════╪═════════════════════╪════════╪═══════════════╡
│ 10       ┆ E009    ┆ 2024-04-01T02:57:45 ┆ null   ┆ absent        │
└──────────┴─────────┴─────────────────────┴────────┴───────────────┘
shape: (6, 3)
┌───────────────┬────────┬──────┐
│ field         ┆ status ┆ n    │
│ ---           ┆ ---    ┆ ---  │
│ str           ┆ str    ┆ u32  │
╞═══════════════╪════════╪══════╡
│ energy_status ┆ absent ┆ 77   │
│ energy_status ┆ valid  ┆ 3246 │
│ mood_status   ┆ absent ┆ 68   │
│ mood_status   ┆ valid  ┆ 3255 │
│ stress_status ┆ absent ┆ 60   │
│ stress_status ┆ valid  ┆ 3263 │
└───────────────┴────────┴──────┘
(3323, True)

All 3,323 submissions have their original IDs. Some items are unanswered, and every recorded rating is in range.

Two clock rules

The extracted submission times have no time-zone labels. The schedule uses Korean time. In the response export, E017’s clock readings are also in Korean time, while all other participants’ readings are in Coordinated Universal Time (UTC). These source conventions determine the instants represented by the text. A short delay between a prompt and a submission cannot establish its time zone.

lubridate::force_tzs() interprets each clock reading in its submitted_zone and returns the instant in UTC. For the schedule, ymd_hms() reads each opening in Asia/Seoul, and with_tz() expresses that instant in UTC. Event 1 was recorded in UTC, so its clock reading is unchanged. For E017’s event 313 and the scheduled opening, the UTC readings are nine hours earlier than the Korean readings.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
events <- events |>
  mutate(
    submitted_zone = if_else(user_id == "E017", "Asia/Seoul", "UTC"),
    submitted_utc = force_tzs(
      ymd_hms(submitted_at),
      tzones = submitted_zone,
      tzone_out = "UTC"
    )
  )
schedule <- schedule |>
  mutate(
    prompt_zone = "Asia/Seoul",
    open_utc = with_tz(ymd_hms(prompt_time, tz = "Asia/Seoul"), "UTC")
  )
events |>
  filter(event_id %in% c(1, 313)) |>
  select(event_id, user_id, submitted_at, submitted_zone, submitted_utc)
schedule |>
  filter(id == "E017", day == 1, prompt == 1) |>
  select(id, prompt_time, prompt_zone, open_utc)
1
2
3
4
5
6
7
8
9
# A tibble: 2 × 5
  event_id user_id submitted_at        submitted_zone submitted_utc      
     <int> <chr>   <chr>               <chr>          <dttm>             
1        1 E009    2024-04-01T00:31:32 UTC            2024-04-01 00:31:32
2      313 E017    2024-04-08T10:13:32 Asia/Seoul     2024-04-08 01:13:32
# A tibble: 1 × 4
  id    prompt_time         prompt_zone open_utc           
  <chr> <chr>               <chr>       <dttm>             
1 E017  2024-04-08 10:04:00 Asia/Seoul  2024-04-08 01:04:00

In Polars, the parsed clock reading initially has no zone. A pl.when() branch uses dt.replace_time_zone("Asia/Seoul") for E017’s readings, then dt.convert_time_zone("UTC") expresses the same instants in UTC. For the other events, dt.replace_time_zone("UTC") assigns the source zone directly. Schedule openings use Seoul time throughout. The event table records the original clock text and its source zone alongside the converted instant.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
clock = pl.col("submitted_at").str.to_datetime("%Y-%m-%dT%H:%M:%S")
events = events.with_columns(
    submitted_zone=pl.when(pl.col("user_id") == "E017")
    .then(pl.lit("Asia/Seoul"))
    .otherwise(pl.lit("UTC"))
).with_columns(
    submitted_utc=pl.when(pl.col("submitted_zone") == "Asia/Seoul")
    .then(clock.dt.replace_time_zone("Asia/Seoul").dt.convert_time_zone("UTC"))
    .otherwise(clock.dt.replace_time_zone("UTC"))
)
schedule = schedule.with_columns(
    prompt_zone=pl.lit("Asia/Seoul"),
    open_utc=pl.col("prompt_time")
    .str.to_datetime("%Y-%m-%d %H:%M:%S")
    .dt.replace_time_zone("Asia/Seoul")
    .dt.convert_time_zone("UTC"),
)
events.filter(pl.col("event_id").is_in([1, 313])).select(
    "event_id", "user_id", "submitted_at", "submitted_zone", "submitted_utc"
)
schedule.filter(
    (pl.col("id") == "E017") & (pl.col("day") == 1) & (pl.col("prompt") == 1)
).select("id", "prompt_time", "prompt_zone", "open_utc")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
shape: (2, 5)
┌──────────┬─────────┬─────────────────────┬────────────────┬─────────────────────────┐
│ event_id ┆ user_id ┆ submitted_at        ┆ submitted_zone ┆ submitted_utc           │
│ ---      ┆ ---     ┆ ---                 ┆ ---            ┆ ---                     │
│ i64      ┆ str     ┆ str                 ┆ str            ┆ datetime[μs, UTC]       │
╞══════════╪═════════╪═════════════════════╪════════════════╪═════════════════════════╡
│ 1        ┆ E009    ┆ 2024-04-01T00:31:32 ┆ UTC            ┆ 2024-04-01 00:31:32 UTC │
│ 313      ┆ E017    ┆ 2024-04-08T10:13:32 ┆ Asia/Seoul     ┆ 2024-04-08 01:13:32 UTC │
└──────────┴─────────┴─────────────────────┴────────────────┴─────────────────────────┘
shape: (1, 4)
┌──────┬─────────────────────┬─────────────┬─────────────────────────┐
│ id   ┆ prompt_time         ┆ prompt_zone ┆ open_utc                │
│ ---  ┆ ---                 ┆ ---         ┆ ---                     │
│ str  ┆ str                 ┆ str         ┆ datetime[μs, UTC]       │
╞══════╪═════════════════════╪═════════════╪═════════════════════════╡
│ E017 ┆ 2024-04-08 10:04:00 ┆ Asia/Seoul  ┆ 2024-04-08 01:04:00 UTC │
└──────┴─────────────────────┴─────────────┴─────────────────────────┘

Event 313 was submitted at 10:13:32 Korean time, 9 minutes 32 seconds after the 10:04 opening. Its UTC time is 01:13:32. What happens if we mistakenly read the original 10:13:32 as UTC?

1
2
3
4
5
e017_event <- filter(events, event_id == 313)
format(e017_event$submitted_utc, tz = "Asia/Seoul", usetz = TRUE)
shifted <- with_tz(ymd_hms(e017_event$submitted_at), "Asia/Seoul")
shifted
difftime(shifted, e017_event$submitted_utc, units = "hours")
1
2
3
[1] "2024-04-08 10:13:32 KST"
[1] "2024-04-08 19:13:32 KST"
Time difference of 9 hours
1
2
3
4
5
6
e017_event = events.filter(pl.col("event_id") == 313)
e017_event.select(
    "submitted_at",
    as_seoul=pl.col("submitted_utc").dt.convert_time_zone("Asia/Seoul"),
    shifted=clock.dt.replace_time_zone("UTC").dt.convert_time_zone("Asia/Seoul"),
).with_columns(difference=pl.col("shifted") - pl.col("as_seoul"))
1
2
3
4
5
6
7
8
shape: (1, 4)
┌─────────────────────┬──────────────────────────┬──────────────────────────┬──────────────┐
│ submitted_at        ┆ as_seoul                 ┆ shifted                  ┆ difference   │
│ ---                 ┆ ---                      ┆ ---                      ┆ ---          │
│ str                 ┆ datetime[μs, Asia/Seoul] ┆ datetime[μs, Asia/Seoul] ┆ duration[μs] │
╞═════════════════════╪══════════════════════════╪══════════════════════════╪══════════════╡
│ 2024-04-08T10:13:32 ┆ 2024-04-08 10:13:32 KST  ┆ 2024-04-08 19:13:32 KST  ┆ 9h           │
└─────────────────────┴──────────────────────────┴──────────────────────────┴──────────────┘

Reading 10:13:32 as UTC places the submission at 19:13:32 in Korea, nine hours after it actually arrived.

Time order of the events

Once all clock readings represent UTC instants, the events can be ordered by submission time. In export order, a backward step occurs when an event’s UTC time precedes the one above it. Events 312 and 313 illustrate that difference. Sorting by submitted_utc establishes time order, with event_id providing a reproducible order for ties.

1
2
3
4
5
6
7
8
9
10
11
12
13
events |>
  filter(event_id %in% 312:314) |>
  select(event_id, user_id, submitted_at, submitted_utc)
sum(diff(events$submitted_utc) < 0)
events <- arrange(events, submitted_utc, event_id)
c(
  rows = nrow(events),
  distinct_ids = n_distinct(events$event_id),
  backward_steps = sum(diff(events$submitted_utc) < 0),
  missing_mood = sum(is.na(events$mood)),
  position_313 = which(events$event_id == 313)
)
identical(sort(events$event_id), event_records$event_id)
1
2
3
4
5
6
7
8
9
10
# A tibble: 3 × 4
  event_id user_id submitted_at        submitted_utc      
     <int> <chr>   <chr>               <dttm>             
1      312 E009    2024-04-08T09:00:57 2024-04-08 09:00:57
2      313 E017    2024-04-08T10:13:32 2024-04-08 01:13:32
3      314 E010    2024-04-08T10:16:45 2024-04-08 10:16:45
[1] 27
          rows   distinct_ids backward_steps   missing_mood   position_313 
          3323           3323              0             68            270 
[1] TRUE
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
events.filter(pl.col("event_id").is_between(312, 314)).select(
    "event_id", "user_id", "submitted_at", "submitted_utc"
)
(events["submitted_utc"].diff().dt.total_seconds() < 0).sum()
events = events.sort("submitted_utc", "event_id")
{
    "rows": events.height,
    "distinct_ids": events["event_id"].n_unique(),
    "backward_steps": (events["submitted_utc"].diff().dt.total_seconds() < 0).sum(),
    "missing_mood": events["mood"].null_count(),
}
events.with_row_index("position", offset=1).filter(pl.col("event_id") == 313).select(
    "position", "event_id", "submitted_utc"
)
events["event_id"].sort().to_list() == list(event_records)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
shape: (3, 4)
┌──────────┬─────────┬─────────────────────┬─────────────────────────┐
│ event_id ┆ user_id ┆ submitted_at        ┆ submitted_utc           │
│ ---      ┆ ---     ┆ ---                 ┆ ---                     │
│ i64      ┆ str     ┆ str                 ┆ datetime[μs, UTC]       │
╞══════════╪═════════╪═════════════════════╪═════════════════════════╡
│ 312      ┆ E009    ┆ 2024-04-08T09:00:57 ┆ 2024-04-08 09:00:57 UTC │
│ 313      ┆ E017    ┆ 2024-04-08T10:13:32 ┆ 2024-04-08 01:13:32 UTC │
│ 314      ┆ E010    ┆ 2024-04-08T10:16:45 ┆ 2024-04-08 10:16:45 UTC │
└──────────┴─────────┴─────────────────────┴─────────────────────────┘
27
{'rows': 3323, 'distinct_ids': 3323, 'backward_steps': 0, 'missing_mood': 68}
shape: (1, 3)
┌──────────┬──────────┬─────────────────────────┐
│ position ┆ event_id ┆ submitted_utc           │
│ ---      ┆ ---      ┆ ---                     │
│ u32      ┆ i64      ┆ datetime[μs, UTC]       │
╞══════════╪══════════╪═════════════════════════╡
│ 270      ┆ 313      ┆ 2024-04-08 01:13:32 UTC │
└──────────┴──────────┴─────────────────────────┘
True

Event 313 was submitted before event 312. It moves to row 270 after sorting and still has ID 313. The 27 backward steps disappear. All 68 submissions without mood ratings still have a participant and a submission time for matching.

23.3 Finding a candidate prompt and validating its window

A submission can answer a prompt only while that prompt is open. The app closes each prompt at the next opening for the same participant on the same study day. The last prompt closes 120 minutes after opening. Each window includes its opening instant and excludes its close, the half-open interval [open, close).

Matching therefore has two steps. The most recent opening for that person at or before submission identifies a candidate. Comparing the submission with that candidate’s closing time determines whether it arrived while the prompt was still open.

In each participant’s day, lead(open_utc) gives the next opening once the prompts are in order. Only the final prompt lacks one, so coalesce() gives it a close 120 minutes after it opens. korean_clock() displays R date-time values in Korean time and changes the column suffix from _utc to _kst. Calculations use UTC instants. In the example, the two prompts open at 09:00 and 11:45. The second table gives the shortest and longest windows at each position in the study.

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
add_closes <- function(prompts) {
  prompts |>
    arrange(id, day, prompt) |>
    mutate(
      close_utc = coalesce(lead(open_utc), open_utc + minutes(120)),
      .by = c(id, day)
    ) |>
    mutate(window_min = as.numeric(difftime(close_utc, open_utc, units = "mins")))
}
korean_clock <- function(data) {
  data |>
    mutate(across(where(is.POSIXct), \(x) format(x, "%H:%M", tz = "Asia/Seoul"))) |>
    rename_with(\(name) str_replace(name, "_utc$", "_kst"))
}
mini_prompts <- tibble(
  id = "e1",
  day = 1L,
  prompt = 1:2,
  open_utc = with_tz(
    ymd_hm(c("2024-04-01 09:00", "2024-04-01 11:45"), tz = "Asia/Seoul"),
    "UTC"
  )
)
mini_intervals <- add_closes(mini_prompts)
korean_clock(mini_intervals)
schedule <- add_closes(schedule)
schedule |>
  summarise(shortest = min(window_min), longest = max(window_min), .by = prompt)
1
2
3
4
5
6
7
8
9
10
11
12
13
# A tibble: 2 × 6
  id      day prompt open_kst close_kst window_min
  <chr> <int>  <int> <chr>    <chr>          <dbl>
1 e1        1      1 09:00    11:45            165
2 e1        1      2 11:45    13:45            120
# A tibble: 5 × 3
  prompt shortest longest
   <int>    <dbl>   <dbl>
1      1       63     237
2      2       63     237
3      3       64     237
4      4       68     232
5      5      120     120

In the example, the first prompt is open for 165 minutes. The 120-minute rule applies to the last prompt of the day. find_candidates() checks that each participant’s opening times are distinct, so the latest opening is unambiguous. In left_join(), closest(submitted_utc >= open_utc) finds the latest opening at or before submission for the same participant. This rolling join needs no prior sorting. With keep = TRUE, the result includes the IDs from both tables.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
find_candidates <- function(events, prompts) {
  stopifnot(n_distinct(prompts$id, prompts$open_utc) == nrow(prompts))
  left_join(
    events,
    select(prompts, candidate_id = id, day, prompt, open_utc, close_utc),
    by = join_by(user_id == candidate_id, closest(submitted_utc >= open_utc)),
    keep = TRUE
  )
}
mini_events <- tibble(
  event_id = 1:3,
  user_id = "e1",
  submitted_utc = with_tz(
    ymd_hm(paste("2024-04-01", c("11:30", "11:45", "14:00")), tz = "Asia/Seoul"),
    "UTC"
  )
)
mini_candidates <- find_candidates(mini_events, mini_intervals)
korean_clock(mini_candidates)
candidates <- find_candidates(events, schedule)
c(rows = nrow(candidates), with_candidate = sum(!is.na(candidates$prompt)))
1
2
3
4
5
6
7
8
# A tibble: 3 × 8
  event_id user_id submitted_kst candidate_id   day prompt open_kst close_kst
     <int> <chr>   <chr>         <chr>        <int>  <int> <chr>    <chr>    
1        1 e1      11:30         e1               1      1 09:00    11:45    
2        2 e1      11:45         e1               1      2 11:45    13:45    
3        3 e1      14:00         e1               1      2 11:45    13:45    
          rows with_candidate 
          3323           3323 

The latest-opening search assigns the same candidate to the 14:00 and 11:45 events, although that prompt closed at 13:45. validate_windows() calculates the minutes since the candidate opened and assigns matched_day and matched_prompt only to submissions inside the window. For a rejected submission, the candidate fields identify the prompt that was checked.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
validate_windows <- function(candidates) {
  candidates |>
    mutate(
      delay_min = as.numeric(difftime(submitted_utc, open_utc, units = "mins")),
      window_status = case_when(
        is.na(open_utc) ~ "no candidate",
        submitted_utc >= open_utc & submitted_utc < close_utc ~ "accepted",
        .default = "after close"
      ),
      matched_day = if_else(window_status == "accepted", day, NA),
      matched_prompt = if_else(window_status == "accepted", prompt, NA)
    )
}
mini_audit <- validate_windows(mini_candidates)
mini_audit |>
  korean_clock() |>
  select(event_id, submitted_kst, prompt, close_kst, delay_min, window_status)
event_audit <- validate_windows(candidates)
count(event_audit, window_status)
1
2
3
4
5
6
7
8
9
10
# A tibble: 3 × 6
  event_id submitted_kst prompt close_kst delay_min window_status
     <int> <chr>          <int> <chr>         <dbl> <chr>        
1        1 11:30              1 11:45           150 accepted     
2        2 11:45              2 13:45             0 accepted     
3        3 14:00              2 13:45           135 after close  
# A tibble: 1 × 2
  window_status     n
  <chr>         <int>
1 accepted       3323

On prompts sorted by participant, day, and position, shift(-1).over("id", "day") gives the next opening within the day. The last opening has no successor, so fill_null() gives it a close 120 minutes later. The elapsed seconds divided by 60 give window_min. The display helper shows Seoul clock times for the two-prompt example. In the supplied schedule, the shortest and longest windows at each position show where the duration varies.

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
def add_closes(prompts):
    return (
        prompts.sort("id", "day", "prompt")
        .with_columns(
            close_utc=pl.col("open_utc")
            .shift(-1)
            .over("id", "day")
            .fill_null(pl.col("open_utc") + pl.duration(minutes=120))
        )
        .with_columns(
            window_min=(pl.col("close_utc") - pl.col("open_utc")).dt.total_seconds()
            / 60
        )
    )


def korean_clock(data):
    return data.with_columns(
        pl.col(pl.Datetime).dt.convert_time_zone("Asia/Seoul").dt.strftime("%H:%M")
    ).rename(lambda name: name.replace("_utc", "_kst"))


minute_format = "%Y-%m-%d %H:%M"
mini_prompts = pl.DataFrame(
    {
        "id": ["e1", "e1"],
        "day": [1, 1],
        "prompt": [1, 2],
        "open_utc": ["2024-04-01 09:00", "2024-04-01 11:45"],
    }
).with_columns(
    pl.col("open_utc")
    .str.to_datetime(minute_format, time_zone="Asia/Seoul")
    .dt.convert_time_zone("UTC")
)
mini_intervals = add_closes(mini_prompts)
korean_clock(mini_intervals)
schedule = add_closes(schedule)
schedule.group_by("prompt").agg(
    shortest=pl.col("window_min").min(), longest=pl.col("window_min").max()
).sort("prompt")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
shape: (2, 6)
┌─────┬─────┬────────┬──────────┬───────────┬────────────┐
│ id  ┆ day ┆ prompt ┆ open_kst ┆ close_kst ┆ window_min │
│ --- ┆ --- ┆ ---    ┆ ---      ┆ ---       ┆ ---        │
│ str ┆ i64 ┆ i64    ┆ str      ┆ str       ┆ f64        │
╞═════╪═════╪════════╪══════════╪═══════════╪════════════╡
│ e1  ┆ 1   ┆ 1      ┆ 09:00    ┆ 11:45     ┆ 165.0      │
│ e1  ┆ 1   ┆ 2      ┆ 11:45    ┆ 13:45     ┆ 120.0      │
└─────┴─────┴────────┴──────────┴───────────┴────────────┘
shape: (5, 3)
┌────────┬──────────┬─────────┐
│ prompt ┆ shortest ┆ longest │
│ ---    ┆ ---      ┆ ---     │
│ i64    ┆ f64      ┆ f64     │
╞════════╪══════════╪═════════╡
│ 1      ┆ 63.0     ┆ 237.0   │
│ 2      ┆ 63.0     ┆ 237.0   │
│ 3      ┆ 64.0     ┆ 237.0   │
│ 4      ┆ 68.0     ┆ 232.0   │
│ 5      ┆ 120.0    ┆ 120.0   │
└────────┴──────────┴─────────┘

find_candidates() requires distinct opening times within each participant because a tie could give a submission two equally recent prompts. It sorts each participant’s submissions and openings by time before join_asof() uses strategy="backward" to find the latest opening at or before submission. by_left and by_right restrict the search to that participant. Polars cannot verify time order within participant groups. The explicit sorts establish that order before the call with check_sortedness=False. candidate_id shows the participant from the schedule.

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
def find_candidates(events, prompts):
    assert prompts.select("id", "open_utc").n_unique() == prompts.height
    return events.sort("user_id", "submitted_utc").join_asof(
        prompts.select("id", "day", "prompt", "open_utc", "close_utc")
        .with_columns(candidate_id=pl.col("id"))
        .sort("id", "open_utc"),
        left_on="submitted_utc",
        right_on="open_utc",
        by_left="user_id",
        by_right="id",
        strategy="backward",
        check_sortedness=False,
    )


mini_events = pl.DataFrame(
    {
        "event_id": [1, 2, 3],
        "user_id": ["e1", "e1", "e1"],
        "submitted_utc": ["2024-04-01 11:30", "2024-04-01 11:45", "2024-04-01 14:00"],
    }
).with_columns(
    pl.col("submitted_utc")
    .str.to_datetime(minute_format, time_zone="Asia/Seoul")
    .dt.convert_time_zone("UTC")
)
mini_candidates = find_candidates(mini_events, mini_intervals)
korean_clock(mini_candidates).select(
    "event_id", "user_id", "submitted_kst", "candidate_id", "prompt", "open_kst",
    "close_kst",
)
candidates = find_candidates(events, schedule)
{"rows": candidates.height, "with_candidate": candidates["prompt"].is_not_null().sum()}
1
2
3
4
5
6
7
8
9
10
11
shape: (3, 7)
┌──────────┬─────────┬───────────────┬──────────────┬────────┬──────────┬───────────┐
│ event_id ┆ user_id ┆ submitted_kst ┆ candidate_id ┆ prompt ┆ open_kst ┆ close_kst │
│ ---      ┆ ---     ┆ ---           ┆ ---          ┆ ---    ┆ ---      ┆ ---       │
│ i64      ┆ str     ┆ str           ┆ str          ┆ i64    ┆ str      ┆ str       │
╞══════════╪═════════╪═══════════════╪══════════════╪════════╪══════════╪═══════════╡
│ 1        ┆ e1      ┆ 11:30         ┆ e1           ┆ 1      ┆ 09:00    ┆ 11:45     │
│ 2        ┆ e1      ┆ 11:45         ┆ e1           ┆ 2      ┆ 11:45    ┆ 13:45     │
│ 3        ┆ e1      ┆ 14:00         ┆ e1           ┆ 2      ┆ 11:45    ┆ 13:45     │
└──────────┴─────────┴───────────────┴──────────────┴────────┴──────────┴───────────┘
{'rows': 3323, 'with_candidate': 3323}

The 14:00 submission has a candidate, but that prompt closed at 13:45. inside requires the submission to be at or after open_utc and before close_utc. Once the status is known, the next with_columns() assigns matched keys only to accepted events. The candidate fields still show which prompt was considered for a rejected event. Dividing elapsed seconds by 60 gives delay_min without losing fractions of a minute.

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
def validate_windows(candidates):
    inside = (pl.col("submitted_utc") >= pl.col("open_utc")) & (
        pl.col("submitted_utc") < pl.col("close_utc")
    )
    accepted = pl.col("window_status") == "accepted"
    return candidates.with_columns(
        delay_min=(pl.col("submitted_utc") - pl.col("open_utc")).dt.total_seconds()
        / 60,
        window_status=pl.when(pl.col("open_utc").is_null())
        .then(pl.lit("no candidate"))
        .when(inside)
        .then(pl.lit("accepted"))
        .otherwise(pl.lit("after close")),
    ).with_columns(
        matched_day=pl.when(accepted).then(pl.col("day")),
        matched_prompt=pl.when(accepted).then(pl.col("prompt")),
    )


mini_audit = validate_windows(mini_candidates)
korean_clock(mini_audit).select(
    "event_id", "submitted_kst", "prompt", "close_kst", "delay_min", "window_status"
)
event_audit = validate_windows(candidates)
event_audit.group_by("window_status").agg(n=pl.len())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
shape: (3, 6)
┌──────────┬───────────────┬────────┬───────────┬───────────┬───────────────┐
│ event_id ┆ submitted_kst ┆ prompt ┆ close_kst ┆ delay_min ┆ window_status │
│ ---      ┆ ---           ┆ ---    ┆ ---       ┆ ---       ┆ ---           │
│ i64      ┆ str           ┆ i64    ┆ str       ┆ f64       ┆ str           │
╞══════════╪═══════════════╪════════╪═══════════╪═══════════╪═══════════════╡
│ 1        ┆ 11:30         ┆ 1      ┆ 11:45     ┆ 150.0     ┆ accepted      │
│ 2        ┆ 11:45         ┆ 2      ┆ 13:45     ┆ 0.0       ┆ accepted      │
│ 3        ┆ 14:00         ┆ 2      ┆ 13:45     ┆ 135.0     ┆ after close   │
└──────────┴───────────────┴────────┴───────────┴───────────┴───────────────┘
shape: (1, 2)
┌───────────────┬──────┐
│ window_status ┆ n    │
│ ---           ┆ ---  │
│ str           ┆ u32  │
╞═══════════════╪══════╡
│ accepted      ┆ 3323 │
└───────────────┴──────┘

The 11:30 submission arrives 150 minutes after prompt 1 opened, while that prompt is still open. At exactly 11:45, a submission answers prompt 2. That prompt is closed from 13:45 onward, so a submission at 13:45 or 14:00 has the status after close. Would a fixed 120-minute cutoff give the same decision for the 11:30 submission?

1
2
3
mini_audit |>
  mutate(within_120 = delay_min < 120) |>
  select(event_id, prompt, delay_min, window_status, matched_prompt, within_120)
1
2
3
4
5
6
# A tibble: 3 × 6
  event_id prompt delay_min window_status matched_prompt within_120
     <int>  <int>     <dbl> <chr>                  <int> <lgl>     
1        1      1       150 accepted                   1 FALSE     
2        2      2         0 accepted                   2 TRUE      
3        3      2       135 after close               NA FALSE     
1
2
3
mini_audit.with_columns(within_120=pl.col("delay_min") < 120).select(
    "event_id", "prompt", "delay_min", "window_status", "matched_prompt", "within_120"
)
1
2
3
4
5
6
7
8
9
10
shape: (3, 6)
┌──────────┬────────┬───────────┬───────────────┬────────────────┬────────────┐
│ event_id ┆ prompt ┆ delay_min ┆ window_status ┆ matched_prompt ┆ within_120 │
│ ---      ┆ ---    ┆ ---       ┆ ---           ┆ ---            ┆ ---        │
│ i64      ┆ i64    ┆ f64       ┆ str           ┆ i64            ┆ bool       │
╞══════════╪════════╪═══════════╪═══════════════╪════════════════╪════════════╡
│ 1        ┆ 1      ┆ 150.0     ┆ accepted      ┆ 1              ┆ false      │
│ 2        ┆ 2      ┆ 0.0       ┆ accepted      ┆ 2              ┆ true       │
│ 3        ┆ 2      ┆ 135.0     ┆ after close   ┆ null           ┆ false      │
└──────────┴────────┴───────────┴───────────────┴────────────────┴────────────┘

A fixed cutoff would reject the 11:30 submission even though the 09:00 prompt was still open.

Matching submissions in the study

In the supplied data, each accepted submission should come from the same participant, at or after the prompt opens and before it closes. Counting events by matched key reveals prompts with more than one submission inside the window.

1
2
3
4
5
6
7
8
9
10
11
12
accepted <- filter(event_audit, window_status == "accepted")
c(
  events = nrow(event_audit),
  distinct_ids = n_distinct(event_audit$event_id),
  accepted = nrow(accepted),
  same_participant = sum(accepted$user_id == accepted$candidate_id),
  at_or_after_open = sum(accepted$submitted_utc >= accepted$open_utc),
  before_close = sum(accepted$submitted_utc < accepted$close_utc)
)
accepted |>
  count(user_id, matched_day, matched_prompt, name = "events") |>
  filter(events > 1)
1
2
3
4
5
6
7
8
9
          events     distinct_ids         accepted same_participant 
            3323             3323             3323             3323 
at_or_after_open     before_close 
            3323             3323 
# A tibble: 2 × 4
  user_id matched_day matched_prompt events
  <chr>         <int>          <int>  <int>
1 E004              2              3      2
2 E027              8              4      2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
accepted = event_audit.filter(pl.col("window_status") == "accepted")
{
    "events": event_audit.height,
    "distinct_ids": event_audit["event_id"].n_unique(),
    "accepted": accepted.height,
    "same_participant": (accepted["user_id"] == accepted["candidate_id"]).sum(),
    "at_or_after_open": (accepted["submitted_utc"] >= accepted["open_utc"]).sum(),
    "before_close": (accepted["submitted_utc"] < accepted["close_utc"]).sum(),
}
(
    accepted.group_by("user_id", "matched_day", "matched_prompt")
    .agg(events=pl.len())
    .filter(pl.col("events") > 1)
    .sort("user_id")
)
1
2
3
4
5
6
7
8
9
10
{'events': 3323, 'distinct_ids': 3323, 'accepted': 3323, 'same_participant': 3323, 'at_or_after_open': 3323, 'before_close': 3323}
shape: (2, 4)
┌─────────┬─────────────┬────────────────┬────────┐
│ user_id ┆ matched_day ┆ matched_prompt ┆ events │
│ ---     ┆ ---         ┆ ---            ┆ ---    │
│ str     ┆ i64         ┆ i64            ┆ u32    │
╞═════════╪═════════════╪════════════════╪════════╡
│ E004    ┆ 2           ┆ 3              ┆ 2      │
│ E027    ┆ 8           ┆ 4              ┆ 2      │
└─────────┴─────────────┴────────────────┴────────┘

All 3,323 submissions fall inside a prompt window for the right participant. Two prompts received two submissions each. They were E004’s third prompt on day 2 and E027’s fourth prompt on day 8.

23.4 Resolving repeated submissions without losing events

When someone submits twice for one prompt, which set of ratings should represent that opportunity? Selecting one submission prevents that prompt from contributing two sets of ratings, while the original events allow us to inspect whether the answers changed.

We first distinguish repeated submissions from duplicate schedule rows. The event count groups accepted submissions by their matched prompt key; the separate schedule check tests whether that key occurs more than once. In R, across(all_of(opportunity)) passes the key columns to count(). In Polars, group_by(opportunity) takes the key list directly.

1
2
3
4
5
opportunity <- c("user_id", "matched_day", "matched_prompt")
accepted |>
  count(across(all_of(opportunity)), name = "events") |>
  count(events, name = "opportunities")
nrow(schedule) - n_distinct(schedule$id, schedule$day, schedule$prompt)
1
2
3
4
5
6
# A tibble: 2 × 2
  events opportunities
   <int>         <int>
1      1          3319
2      2             2
[1] 0
1
2
3
4
5
6
7
8
9
opportunity = ["user_id", "matched_day", "matched_prompt"]
(
    accepted.group_by(opportunity)
    .agg(events=pl.len())
    .group_by("events")
    .agg(opportunities=pl.len())
    .sort("events")
)
schedule.height - schedule.select("id", "day", "prompt").n_unique()
1
2
3
4
5
6
7
8
9
10
shape: (2, 2)
┌────────┬───────────────┐
│ events ┆ opportunities │
│ ---    ┆ ---           │
│ u32    ┆ u32           │
╞════════╪═══════════════╡
│ 1      ┆ 3319          │
│ 2      ┆ 2             │
└────────┴───────────────┘
0

The schedule has no duplicate key, but two prompts each have two accepted events. Their timestamps, delays, and ratings show how closely the submissions followed each other and whether the answers changed. In R, filter(n() > 1, .by = all_of(opportunity)) selects all submissions for those prompts. In Polars, filter(pl.len().over(opportunity) > 1) selects the same four rows.

1
2
3
4
repeated <- accepted |>
  filter(n() > 1, .by = all_of(opportunity)) |>
  arrange(user_id, submitted_utc)
select(repeated, event_id, user_id, submitted_utc, delay_min, mood, stress, energy)
1
2
3
4
5
6
7
# A tibble: 4 × 7
  event_id user_id submitted_utc       delay_min  mood stress energy
     <int> <chr>   <dttm>                  <dbl> <int>  <int>  <int>
1       51 E004    2024-04-02 05:33:54      4.9      5      4      6
2       52 E004    2024-04-02 05:34:35      5.58     5      4      6
3     1400 E027    2024-04-22 08:39:42      4.7      4      3      3
4     1401 E027    2024-04-22 08:40:57      5.95     4      3      3
1
2
3
4
5
6
repeated = accepted.filter(pl.len().over(opportunity) > 1).sort(
    "user_id", "submitted_utc"
)
repeated.select(
    "event_id", "user_id", "submitted_utc", "delay_min", "mood", "stress", "energy"
)
1
2
3
4
5
6
7
8
9
10
11
shape: (4, 7)
┌──────────┬─────────┬─────────────────────────┬───────────┬──────┬────────┬────────┐
│ event_id ┆ user_id ┆ submitted_utc           ┆ delay_min ┆ mood ┆ stress ┆ energy │
│ ---      ┆ ---     ┆ ---                     ┆ ---       ┆ ---  ┆ ---    ┆ ---    │
│ i64      ┆ str     ┆ datetime[μs, UTC]       ┆ f64       ┆ i64  ┆ i64    ┆ i64    │
╞══════════╪═════════╪═════════════════════════╪═══════════╪══════╪════════╪════════╡
│ 51       ┆ E004    ┆ 2024-04-02 05:33:54 UTC ┆ 4.9       ┆ 5    ┆ 4      ┆ 6      │
│ 52       ┆ E004    ┆ 2024-04-02 05:34:35 UTC ┆ 5.583333  ┆ 5    ┆ 4      ┆ 6      │
│ 1400     ┆ E027    ┆ 2024-04-22 08:39:42 UTC ┆ 4.7       ┆ 4    ┆ 3      ┆ 3      │
│ 1401     ┆ E027    ┆ 2024-04-22 08:40:57 UTC ┆ 5.95      ┆ 4    ┆ 3      ┆ 3      │
└──────────┴─────────┴─────────────────────────┴───────────┴──────┴────────┴────────┘

E004 submitted identical ratings 41 seconds apart, and E027 did so 75 seconds apart. We use the first submission inside each prompt’s window, even if a later one answers more items. If the times are equal, we use the submission with the smaller original event ID.

In R, arrange() orders submissions within each opportunity by instant, then event ID. Among accepted events, the first has rank 1 and event_status is selected. Later ones are additional valid. An event outside the window is unmatched regardless of its position. For each repeated prompt, the two statuses show which event will represent the answer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
event_audit <- event_audit |>
  arrange(user_id, matched_day, matched_prompt, submitted_utc, event_id) |>
  mutate(
    submission_order = if_else(window_status == "accepted", row_number(), NA),
    .by = all_of(opportunity)
  ) |>
  mutate(
    event_status = case_when(
      window_status != "accepted" ~ "unmatched",
      submission_order == 1 ~ "selected",
      .default = "additional valid"
    )
  )
event_audit |>
  filter(event_id %in% repeated$event_id) |>
  select(event_id, user_id, matched_day, matched_prompt, submission_order,
         event_status)
1
2
3
4
5
6
7
# A tibble: 4 × 6
  event_id user_id matched_day matched_prompt submission_order event_status    
     <int> <chr>         <int>          <int>            <int> <chr>           
1       51 E004              2              3                1 selected        
2       52 E004              2              3                2 additional valid
3     1400 E027              8              4                1 selected        
4     1401 E027              8              4                2 additional valid

In Polars, sort(*opportunity, "submitted_utc", "event_id") unpacks the key fields with * and orders each prompt’s submissions by instant, then ID. cum_count().over(opportunity) gives accepted events their ranks. A second with_columns() marks unmatched events first, selects rank 1, and labels later accepted events additional valid. Both IDs for a repeated prompt are still visible.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
event_audit = (
    event_audit.sort(*opportunity, "submitted_utc", "event_id")
    .with_columns(
        submission_order=pl.when(pl.col("window_status") == "accepted").then(
            pl.col("event_id").cum_count().over(opportunity)
        )
    )
    .with_columns(
        event_status=pl.when(pl.col("window_status") != "accepted")
        .then(pl.lit("unmatched"))
        .when(pl.col("submission_order") == 1)
        .then(pl.lit("selected"))
        .otherwise(pl.lit("additional valid"))
    )
)
event_audit.filter(pl.col("event_id").is_in(repeated["event_id"].to_list())).select(
    *opportunity, "event_id", "submission_order", "event_status"
)
1
2
3
4
5
6
7
8
9
10
11
shape: (4, 6)
┌─────────┬─────────────┬────────────────┬──────────┬──────────────────┬──────────────────┐
│ user_id ┆ matched_day ┆ matched_prompt ┆ event_id ┆ submission_order ┆ event_status     │
│ ---     ┆ ---         ┆ ---            ┆ ---      ┆ ---              ┆ ---              │
│ str     ┆ i64         ┆ i64            ┆ i64      ┆ u32              ┆ str              │
╞═════════╪═════════════╪════════════════╪══════════╪══════════════════╪══════════════════╡
│ E004    ┆ 2           ┆ 3              ┆ 51       ┆ 1                ┆ selected         │
│ E004    ┆ 2           ┆ 3              ┆ 52       ┆ 2                ┆ additional valid │
│ E027    ┆ 8           ┆ 4              ┆ 1400     ┆ 1                ┆ selected         │
│ E027    ┆ 8           ┆ 4              ┆ 1401     ┆ 2                ┆ additional valid │
└─────────┴─────────────┴────────────────┴──────────┴──────────────────┴──────────────────┘

Events 51 and 1400 are selected. Their later counterparts, 52 and 1401, are classified as additional valid submissions. Each answered prompt now has exactly one selected submission.

1
count(event_audit, window_status, event_status)
1
2
3
4
5
# A tibble: 2 × 3
  window_status event_status         n
  <chr>         <chr>            <int>
1 accepted      additional valid     2
2 accepted      selected          3321
1
2
3
event_audit.group_by("window_status", "event_status").agg(n=pl.len()).sort(
    "event_status"
)
1
2
3
4
5
6
7
8
9
shape: (2, 3)
┌───────────────┬──────────────────┬──────┐
│ window_status ┆ event_status     ┆ n    │
│ ---           ┆ ---              ┆ ---  │
│ str           ┆ str              ┆ u32  │
╞═══════════════╪══════════════════╪══════╡
│ accepted      ┆ additional valid ┆ 2    │
│ accepted      ┆ selected         ┆ 3321 │
└───────────────┴──────────────────┴──────┘

The audit contains 3,321 selected submissions and two additional ones. In selected_events, id, day, and prompt identify one submission per answered prompt. Only ratings marked valid enter this table as scores; the audit records the original codes.

Before calculating coverage, we check that every selected key belongs to the schedule and occurs once. Comparing joins with the selected events and with all accepted events then shows how repeated submissions would affect the denominator.

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
selected_events <- event_audit |>
  filter(event_status == "selected") |>
  mutate(
    mood = if_else(mood_status == "valid", mood, NA_integer_),
    stress = if_else(stress_status == "valid", stress, NA_integer_),
    energy = if_else(energy_status == "valid", energy, NA_integer_)
  ) |>
  select(id = user_id, day = matched_day, prompt = matched_prompt, event_id,
         submitted_utc, delay_min, mood, stress, energy)
c(
  audit_rows = nrow(event_audit),
  audit_ids = n_distinct(event_audit$event_id),
  selected_rows = nrow(selected_events),
  selected_keys = n_distinct(selected_events$id, selected_events$day,
                             selected_events$prompt),
  keys_not_in_schedule = nrow(anti_join(selected_events, schedule,
                                        by = join_by(id, day, prompt)))
)
c(
  with_selected = nrow(left_join(
    schedule,
    selected_events,
    by = join_by(id, day, prompt),
    relationship = "one-to-one"
  )),
  with_all_accepted = nrow(left_join(
    schedule,
    select(accepted, id = user_id, day = matched_day, prompt = matched_prompt),
    by = join_by(id, day, prompt)
  ))
)
1
2
3
4
5
6
          audit_rows            audit_ids        selected_rows 
                3323                 3323                 3321 
       selected_keys keys_not_in_schedule 
                3321                    0 
    with_selected with_all_accepted 
             4200              4202 
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
valid_ratings = [
    pl.when(pl.col(f"{name}_status") == "valid").then(pl.col(name)).alias(name)
    for name in answer_names
]
selected_events = (
    event_audit.filter(pl.col("event_status") == "selected")
    .select(*opportunity, "event_id", "submitted_utc", "delay_min", *valid_ratings)
    .rename({"user_id": "id", "matched_day": "day", "matched_prompt": "prompt"})
)
{
    "audit_rows": event_audit.height,
    "audit_ids": event_audit["event_id"].n_unique(),
    "selected_rows": selected_events.height,
    "selected_keys": selected_events.select("id", "day", "prompt").n_unique(),
    "keys_not_in_schedule": selected_events.join(
        schedule, on=["id", "day", "prompt"], how="anti"
    ).height,
}
accepted_keys = accepted.select(
    id="user_id", day="matched_day", prompt="matched_prompt"
)
{
    "with_selected": schedule.join(
        selected_events, on=["id", "day", "prompt"], how="left", validate="1:1"
    ).height,
    "with_all_accepted": schedule.join(
        accepted_keys, on=["id", "day", "prompt"], how="left"
    ).height,
}
1
2
{'audit_rows': 3323, 'audit_ids': 3323, 'selected_rows': 3321, 'selected_keys': 3321, 'keys_not_in_schedule': 0}
{'with_selected': 4200, 'with_all_accepted': 4202}

Joining selected events gives the same 4,200 schedule rows. Joining all accepted events produces 4,202 rows, counting each of the two repeated opportunities twice. All 3,323 submissions remain in the event audit, including the two later ones.

23.5 Reconstructing response coverage and observed measurements

Of the 4,200 scheduled prompts, how many received an answer, and how many yielded a mood rating? For response coverage, a prompt counts as answered if its participant submitted at least once while it was open. A missing mood rating does not change that count. The denominator includes every scheduled prompt, five per person per day and 70 per person over the study. Using only the selected submissions would give 100 percent coverage because every unanswered prompt is missing from that table.

In R, left_join() matches the selected events to the schedule on id, day, and prompt, with a one-to-one relationship. An event_id marks an answered prompt even when its mood rating is blank. Each item has its own availability flag. The five rows for E001’s second day show which scheduled prompts received a submission.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
coverage <- schedule |>
  select(id, day, prompt, prompt_time, open_utc, close_utc) |>
  left_join(
    selected_events,
    by = join_by(id, day, prompt),
    relationship = "one-to-one"
  ) |>
  mutate(
    responded = !is.na(event_id),
    mood_available = !is.na(mood),
    stress_available = !is.na(stress),
    energy_available = !is.na(energy)
  )
c(rows = nrow(coverage), keys = n_distinct(coverage$id, coverage$day, coverage$prompt))
count(coverage, responded)
coverage |>
  filter(id == "E001", day == 2) |>
  select(id, day, prompt, prompt_time, event_id, delay_min, mood, responded)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
rows keys 
4200 4200 
# A tibble: 2 × 2
  responded     n
  <lgl>     <int>
1 FALSE       879
2 TRUE       3321
# A tibble: 5 × 8
  id      day prompt prompt_time         event_id delay_min  mood responded
  <chr> <int>  <int> <chr>                  <int>     <dbl> <int> <lgl>    
1 E001      2      1 2024-04-02 10:18:00       NA     NA       NA FALSE    
2 E001      2      2 2024-04-02 11:31:00       45     29.0      5 TRUE     
3 E001      2      3 2024-04-02 15:25:00       NA     NA       NA FALSE    
4 E001      2      4 2024-04-02 16:46:00       60      1.55     5 TRUE     
5 E001      2      5 2024-04-02 19:32:00       71      9.38     3 TRUE     

In Polars, the left join includes every scheduled prompt, and validate="1:1" checks that the join keys are unique in both tables. A nonnull event_id marks an answered prompt. The item columns show which ratings the selected submission provided. E001’s second day has a row for each of the five scheduled prompts.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
coverage = (
    schedule.select("id", "day", "prompt", "prompt_time", "open_utc", "close_utc")
    .join(selected_events, on=["id", "day", "prompt"], how="left", validate="1:1")
    .with_columns(
        responded=pl.col("event_id").is_not_null(),
        mood_available=pl.col("mood").is_not_null(),
        stress_available=pl.col("stress").is_not_null(),
        energy_available=pl.col("energy").is_not_null(),
    )
)
{"rows": coverage.height, "keys": coverage.select("id", "day", "prompt").n_unique()}
coverage.group_by("responded").agg(n=pl.len()).sort("responded")
coverage.filter((pl.col("id") == "E001") & (pl.col("day") == 2)).select(
    "id", "day", "prompt", "prompt_time", "event_id", "delay_min", "mood", "responded"
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{'rows': 4200, 'keys': 4200}
shape: (2, 2)
┌───────────┬──────┐
│ responded ┆ n    │
│ ---       ┆ ---  │
│ bool      ┆ u32  │
╞═══════════╪══════╡
│ false     ┆ 879  │
│ true      ┆ 3321 │
└───────────┴──────┘
shape: (5, 8)
┌──────┬─────┬────────┬─────────────────────┬──────────┬───────────┬──────┬───────────┐
│ id   ┆ day ┆ prompt ┆ prompt_time         ┆ event_id ┆ delay_min ┆ mood ┆ responded │
│ ---  ┆ --- ┆ ---    ┆ ---                 ┆ ---      ┆ ---       ┆ ---  ┆ ---       │
│ str  ┆ i64 ┆ i64    ┆ str                 ┆ i64      ┆ f64       ┆ i64  ┆ bool      │
╞══════╪═════╪════════╪═════════════════════╪══════════╪═══════════╪══════╪═══════════╡
│ E001 ┆ 2   ┆ 1      ┆ 2024-04-02 10:18:00 ┆ null     ┆ null      ┆ null ┆ false     │
│ E001 ┆ 2   ┆ 2      ┆ 2024-04-02 11:31:00 ┆ 45       ┆ 29.05     ┆ 5    ┆ true      │
│ E001 ┆ 2   ┆ 3      ┆ 2024-04-02 15:25:00 ┆ null     ┆ null      ┆ null ┆ false     │
│ E001 ┆ 2   ┆ 4      ┆ 2024-04-02 16:46:00 ┆ 60       ┆ 1.55      ┆ 5    ┆ true      │
│ E001 ┆ 2   ┆ 5      ┆ 2024-04-02 19:32:00 ┆ 71       ┆ 9.383333  ┆ 3    ┆ true      │
└──────┴─────┴────────┴─────────────────────┴──────────┴───────────┴──────┴───────────┘

Of the 4,200 scheduled prompts, 879 went unanswered. On E001’s second day, prompts 1 and 3 received no submission. The mood cell for day 12, prompt 3 is also blank. Did that prompt go unanswered too?

1
2
3
coverage |>
  filter(id == "E001", (day == 2 & prompt == 1) | (day == 12 & prompt == 3)) |>
  select(id, day, prompt, event_id, mood, stress, responded, mood_available)
1
2
3
4
5
# A tibble: 2 × 8
  id      day prompt event_id  mood stress responded mood_available
  <chr> <int>  <int>    <int> <int>  <int> <lgl>     <lgl>         
1 E001      2      1       NA    NA     NA FALSE     FALSE         
2 E001     12      3      609    NA      4 TRUE      FALSE         
1
2
3
4
5
6
7
8
9
coverage.filter(
    (pl.col("id") == "E001")
    & (
        ((pl.col("day") == 2) & (pl.col("prompt") == 1))
        | ((pl.col("day") == 12) & (pl.col("prompt") == 3))
    )
).select(
    "id", "day", "prompt", "event_id", "mood", "stress", "responded", "mood_available"
)
1
2
3
4
5
6
7
8
9
shape: (2, 8)
┌──────┬─────┬────────┬──────────┬──────┬────────┬───────────┬────────────────┐
│ id   ┆ day ┆ prompt ┆ event_id ┆ mood ┆ stress ┆ responded ┆ mood_available │
│ ---  ┆ --- ┆ ---    ┆ ---      ┆ ---  ┆ ---    ┆ ---       ┆ ---            │
│ str  ┆ i64 ┆ i64    ┆ i64      ┆ i64  ┆ i64    ┆ bool      ┆ bool           │
╞══════╪═════╪════════╪══════════╪══════╪════════╪═══════════╪════════════════╡
│ E001 ┆ 2   ┆ 1      ┆ null     ┆ null ┆ null   ┆ false     ┆ false          │
│ E001 ┆ 12  ┆ 3      ┆ 609      ┆ null ┆ 4      ┆ true      ┆ false          │
└──────┴─────┴────────┴──────────┴──────┴────────┴───────────┴────────────────┘

The first prompt on day 2 has no event ID. On day 12, event 609 identifies the submission for prompt 3, so that prompt counts as answered. It includes a stress rating of 4. Neither row contributes a mood rating.

Coverage and mood availability

How much of each day’s schedule and each person’s schedule was answered, and how many ratings does each item mean use?

Within a person-day or a person, sum(responded) counts answered prompts and dplyr::n() counts scheduled prompts. Coverage is answered divided by scheduled. For E004 on day 2, a repeat submission can increase the event count without increasing coverage.

1
2
3
4
5
6
7
8
9
10
11
12
daily <- coverage |>
  summarise(scheduled = n(), answered = sum(responded), .by = c(id, day)) |>
  mutate(coverage = answered / scheduled)
participants <- coverage |>
  summarise(scheduled = n(), answered = sum(responded), .by = id) |>
  mutate(coverage = answered / scheduled)
count(daily, scheduled, answered, name = "person_days")
filter(daily, id == "E004", day == 2)
sum(event_audit$user_id == "E004" & event_audit$matched_day %in% 2)
participants |>
  filter(answered %in% range(answered)) |>
  arrange(answered)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# A tibble: 6 × 3
  scheduled answered person_days
      <int>    <int>       <int>
1         5        0           2
2         5        1          20
3         5        2          65
4         5        3         154
5         5        4         286
6         5        5         313
# A tibble: 1 × 5
  id      day scheduled answered coverage
  <chr> <int>     <int>    <int>    <dbl>
1 E004      2         5        4      0.8
[1] 5
# A tibble: 2 × 4
  id    scheduled answered coverage
  <chr>     <int>    <int>    <dbl>
1 E059         70       31    0.443
2 E033         70       69    0.986

E004 submitted five times on day 2 and answered four of the five prompts. The first submission for each answered prompt determines its delay and ratings. After pivot_longer(), each field has a mean over its observed values. On a day with no mood ratings, mean(mood, na.rm = TRUE) gives NaN, so the daily summary uses NA_real_ for the missing mean.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
measures <- coverage |>
  pivot_longer(
    c(mood, stress, energy, delay_min),
    names_to = "field",
    values_to = "value"
  ) |>
  summarise(
    scheduled = n(),
    answered = sum(responded),
    observed = sum(!is.na(value)),
    mean = mean(value, na.rm = TRUE),
    .by = field
  )
measures
daily_mood <- coverage |>
  summarise(
    answered = sum(responded),
    mood_n = sum(mood_available),
    mood_mean = if_else(mood_n > 0, mean(mood, na.rm = TRUE), NA_real_),
    .by = c(id, day)
  )
filter(daily_mood, (id == "E001" & day == 12) | answered == 0)
1
2
3
4
5
6
7
8
9
10
11
12
13
# A tibble: 4 × 5
  field     scheduled answered observed  mean
  <chr>         <int>    <int>    <int> <dbl>
1 mood           4200     3321     3253  4.43
2 stress         4200     3321     3261  3.56
3 energy         4200     3321     3244  3.97
4 delay_min      4200     3321     3321  8.92
# A tibble: 3 × 5
  id      day answered mood_n mood_mean
  <chr> <int>    <int>  <int>     <dbl>
1 E001     12        5      4         4
2 E005     13        0      0        NA
3 E025      9        0      0        NA

In Polars, grouping by person and day gives five opportunities per group, and grouping by person gives 70. pl.col("responded").sum() counts answered prompts and pl.len() counts scheduled ones. A later with_columns() divides answered by scheduled. For E004 on day 2, are there as many answered prompts as accepted submissions?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
daily = (
    coverage.group_by("id", "day")
    .agg(scheduled=pl.len(), answered=pl.col("responded").sum())
    .with_columns(coverage=pl.col("answered") / pl.col("scheduled"))
)
participants = (
    coverage.group_by("id")
    .agg(scheduled=pl.len(), answered=pl.col("responded").sum())
    .with_columns(coverage=pl.col("answered") / pl.col("scheduled"))
)
daily.group_by("scheduled", "answered").agg(person_days=pl.len()).sort("answered")
daily.filter((pl.col("id") == "E004") & (pl.col("day") == 2))
event_audit.filter(
    (pl.col("user_id") == "E004") & (pl.col("matched_day") == 2)
).height
lowest, highest = participants["answered"].min(), participants["answered"].max()
participants.filter(pl.col("answered").is_in([lowest, highest])).sort("answered")
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
shape: (6, 3)
┌───────────┬──────────┬─────────────┐
│ scheduled ┆ answered ┆ person_days │
│ ---       ┆ ---      ┆ ---         │
│ u32       ┆ u32      ┆ u32         │
╞═══════════╪══════════╪═════════════╡
│ 5         ┆ 0        ┆ 2           │
│ 5         ┆ 1        ┆ 20          │
│ 5         ┆ 2        ┆ 65          │
│ 5         ┆ 3        ┆ 154         │
│ 5         ┆ 4        ┆ 286         │
│ 5         ┆ 5        ┆ 313         │
└───────────┴──────────┴─────────────┘
shape: (1, 5)
┌──────┬─────┬───────────┬──────────┬──────────┐
│ id   ┆ day ┆ scheduled ┆ answered ┆ coverage │
│ ---  ┆ --- ┆ ---       ┆ ---      ┆ ---      │
│ str  ┆ i64 ┆ u32       ┆ u32      ┆ f64      │
╞══════╪═════╪═══════════╪══════════╪══════════╡
│ E004 ┆ 2   ┆ 5         ┆ 4        ┆ 0.8      │
└──────┴─────┴───────────┴──────────┴──────────┘
5
shape: (2, 4)
┌──────┬───────────┬──────────┬──────────┐
│ id   ┆ scheduled ┆ answered ┆ coverage │
│ ---  ┆ ---       ┆ ---      ┆ ---      │
│ str  ┆ u32       ┆ u32      ┆ f64      │
╞══════╪═══════════╪══════════╪══════════╡
│ E059 ┆ 70        ┆ 31       ┆ 0.442857 │
│ E033 ┆ 70        ┆ 69       ┆ 0.985714 │
└──────┴───────────┴──────────┴──────────┘

E004 submitted five times on day 2 and answered four of the five prompts. Using responded as the index in Polars’ unpivot() repeats the response flag beside each measurement. Each field then has a count and a mean over its observed values. For a day with no mood observations, mean() returns null directly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
measures = (
    coverage.unpivot(
        on=[*answer_names, "delay_min"],
        index="responded",
        variable_name="field",
        value_name="value",
    )
    .group_by("field", maintain_order=True)
    .agg(
        scheduled=pl.len(),
        answered=pl.col("responded").sum(),
        observed=pl.col("value").count(),
        mean=pl.col("value").mean(),
    )
)
measures
daily_mood = coverage.group_by("id", "day").agg(
    answered=pl.col("responded").sum(),
    mood_n=pl.col("mood_available").sum(),
    mood_mean=pl.col("mood").mean(),
)
daily_mood.filter(
    ((pl.col("id") == "E001") & (pl.col("day") == 12)) | (pl.col("answered") == 0)
).sort("id", "day")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
shape: (4, 5)
┌───────────┬───────────┬──────────┬──────────┬──────────┐
│ field     ┆ scheduled ┆ answered ┆ observed ┆ mean     │
│ ---       ┆ ---       ┆ ---      ┆ ---      ┆ ---      │
│ str       ┆ u32       ┆ u32      ┆ u32      ┆ f64      │
╞═══════════╪═══════════╪══════════╪══════════╪══════════╡
│ mood      ┆ 4200      ┆ 3321     ┆ 3253     ┆ 4.426068 │
│ stress    ┆ 4200      ┆ 3321     ┆ 3261     ┆ 3.562711 │
│ energy    ┆ 4200      ┆ 3321     ┆ 3244     ┆ 3.967941 │
│ delay_min ┆ 4200      ┆ 3321     ┆ 3321     ┆ 8.92445  │
└───────────┴───────────┴──────────┴──────────┴──────────┘
shape: (3, 5)
┌──────┬─────┬──────────┬────────┬───────────┐
│ id   ┆ day ┆ answered ┆ mood_n ┆ mood_mean │
│ ---  ┆ --- ┆ ---      ┆ ---    ┆ ---       │
│ str  ┆ i64 ┆ u32      ┆ u32    ┆ f64       │
╞══════╪═════╪══════════╪════════╪═══════════╡
│ E001 ┆ 12  ┆ 5        ┆ 4      ┆ 4.0       │
│ E005 ┆ 13  ┆ 0        ┆ 0      ┆ null      │
│ E025 ┆ 9   ┆ 0        ┆ 0      ┆ null      │
└──────┴─────┴──────────┴────────┴───────────┘

The mean mood score of about 4.43 uses 3,253 ratings. All 3,321 selected submissions have a delay, averaging 8.92 minutes from opening to submission. E001 answered five prompts on day 12 and gave four mood ratings. On the two days with no submissions, the daily mood mean is missing.

To describe mood availability, we can compare the 3,253 ratings with either answered prompts or all scheduled prompts. The cross-classification below separates unanswered prompts from answered prompts without mood. The accompanying counts verify five opportunities per person-day and 70 per person before calculating the percentages.

1
2
3
4
5
6
7
8
9
count(coverage, responded, mood_available)
c(
  person_days = nrow(daily),
  with_five = sum(daily$scheduled == 5),
  people = nrow(participants),
  with_seventy = sum(participants$scheduled == 70),
  answered = sum(daily$answered),
  unanswered = sum(daily$scheduled - daily$answered)
)
1
2
3
4
5
6
7
8
# A tibble: 3 × 3
  responded mood_available     n
  <lgl>     <lgl>          <int>
1 FALSE     FALSE            879
2 TRUE      FALSE             68
3 TRUE      TRUE            3253
 person_days    with_five       people with_seventy     answered   unanswered 
         840          840           60           60         3321          879 
1
2
3
4
5
6
7
8
9
10
11
coverage.group_by("responded", "mood_available").agg(n=pl.len()).sort(
    "responded", "mood_available"
)
{
    "person_days": daily.height,
    "with_five": (daily["scheduled"] == 5).sum(),
    "people": participants.height,
    "with_seventy": (participants["scheduled"] == 70).sum(),
    "answered": daily["answered"].sum(),
    "unanswered": (daily["scheduled"] - daily["answered"]).sum(),
}
1
2
3
4
5
6
7
8
9
10
11
shape: (3, 3)
┌───────────┬────────────────┬──────┐
│ responded ┆ mood_available ┆ n    │
│ ---       ┆ ---            ┆ ---  │
│ bool      ┆ bool           ┆ u32  │
╞═══════════╪════════════════╪══════╡
│ false     ┆ false          ┆ 879  │
│ true      ┆ false          ┆ 68   │
│ true      ┆ true           ┆ 3253 │
└───────────┴────────────────┴──────┘
{'person_days': 840, 'with_five': 840, 'people': 60, 'with_seventy': 60, 'answered': 3321, 'unanswered': 879}

Participants answered 3,321 of the 4,200 scheduled prompts, giving 79.1 percent response coverage. Among the 3,321 answered prompts, 3,253 had a mood rating, or 98.0 percent. The same 3,253 ratings represent 77.5 percent of all scheduled prompts. Event 609 accounts for one of the 68 prompts that were answered without a mood rating.

23.6 Defining previous occasions and within-person changes

Suppose a participant reports a mood of 2, misses the next prompt, then reports a 5. Has mood risen by 3 points since the previous prompt? To describe change between consecutive scheduled prompts, we need ratings at both adjacent opportunities for the same person on the same day.

The first calculation determines the previous mood from all three scheduled prompts. The second excludes the unanswered prompt before determining the previous mood.

1
2
3
4
5
6
miniature <- tibble(prompt = 1:3, mood = c(2L, NA, 5L))
miniature |>
  mutate(previous_mood = lag(mood), change = mood - previous_mood)
miniature |>
  filter(!is.na(mood)) |>
  mutate(previous_prompt = lag(prompt), change = mood - lag(mood))
1
2
3
4
5
6
7
8
9
10
11
# A tibble: 3 × 4
  prompt  mood previous_mood change
   <int> <int>         <int>  <int>
1      1     2            NA     NA
2      2    NA             2     NA
3      3     5            NA     NA
# A tibble: 2 × 4
  prompt  mood previous_prompt change
   <int> <int>           <int>  <int>
1      1     2              NA     NA
2      3     5               1      3
1
2
3
4
5
6
7
8
miniature = pl.DataFrame({"prompt": [1, 2, 3], "mood": [2, None, 5]})
miniature.with_columns(previous_mood=pl.col("mood").shift(1)).with_columns(
    change=pl.col("mood") - pl.col("previous_mood")
)
miniature.filter(pl.col("mood").is_not_null()).with_columns(
    previous_prompt=pl.col("prompt").shift(1),
    change=pl.col("mood") - pl.col("mood").shift(1),
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
shape: (3, 4)
┌────────┬──────┬───────────────┬────────┐
│ prompt ┆ mood ┆ previous_mood ┆ change │
│ ---    ┆ ---  ┆ ---           ┆ ---    │
│ i64    ┆ i64  ┆ i64           ┆ i64    │
╞════════╪══════╪═══════════════╪════════╡
│ 1      ┆ 2    ┆ null          ┆ null   │
│ 2      ┆ null ┆ 2             ┆ null   │
│ 3      ┆ 5    ┆ null          ┆ null   │
└────────┴──────┴───────────────┴────────┘
shape: (2, 4)
┌────────┬──────┬─────────────────┬────────┐
│ prompt ┆ mood ┆ previous_prompt ┆ change │
│ ---    ┆ ---  ┆ ---             ┆ ---    │
│ i64    ┆ i64  ┆ i64             ┆ i64    │
╞════════╪══════╪═════════════════╪════════╡
│ 1      ┆ 2    ┆ null            ┆ null   │
│ 3      ┆ 5    ┆ 1               ┆ 3      │
└────────┴──────┴─────────────────┴────────┘

The 3-point rise is from prompt 1 to prompt 3. We cannot calculate the change from prompt 2 to prompt 3 because prompt 2 has no rating.

With .by = c(id, day) in mutate(), lag() finds the previous prompt separately for each participant and day, following the sorted prompt order. On E001’s second day, the preceding prompt number and opening time identify the previous scheduled prompt even when it has no rating.

1
2
3
4
5
6
7
8
9
10
11
12
changes <- coverage |>
  arrange(id, day, prompt) |>
  mutate(
    previous_prompt = lag(prompt),
    previous_open_utc = lag(open_utc),
    previous_mood = lag(mood),
    .by = c(id, day)
  )
changes |>
  filter(id == "E001", day == 2) |>
  korean_clock() |>
  select(prompt, open_kst, mood, previous_prompt, previous_open_kst, previous_mood)
1
2
3
4
5
6
7
8
# A tibble: 5 × 6
  prompt open_kst  mood previous_prompt previous_open_kst previous_mood
   <int> <chr>    <int>           <int> <chr>                     <int>
1      1 10:18       NA              NA <NA>                         NA
2      2 11:31        5               1 10:18                        NA
3      3 15:25       NA               2 11:31                         5
4      4 16:46        5               3 15:25                        NA
5      5 19:32        3               4 16:46                         5

On E001’s second day, prompt 4 follows unanswered prompt 3. The openings are 81 minutes apart, but the change in mood is unknown. A second mutate() subtracts consecutive opening times for interval_min and consecutive ratings for mood_change. The first prompt of each day has no previous opening or rating.

1
2
3
4
5
6
7
8
9
changes <- changes |>
  mutate(
    interval_min = as.numeric(difftime(open_utc, previous_open_utc, units = "mins")),
    mood_change = mood - previous_mood
  )
changes |>
  filter(id == "E001", day %in% c(2, 12)) |>
  select(day, prompt, mood, previous_mood, interval_min, mood_change)
c(rows = nrow(changes), with_change = sum(!is.na(changes$mood_change)))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# A tibble: 10 × 6
     day prompt  mood previous_mood interval_min mood_change
   <int>  <int> <int>         <int>        <dbl>       <int>
 1     2      1    NA            NA           NA          NA
 2     2      2     5            NA           73          NA
 3     2      3    NA             5          234          NA
 4     2      4     5            NA           81          NA
 5     2      5     3             5          166          -2
 6    12      1     4            NA           NA          NA
 7    12      2     5             4          138           1
 8    12      3    NA             5          155          NA
 9    12      4     4            NA           98          NA
10    12      5     3             4          143          -1
       rows with_change 
       4200        2074 

On the full schedule sorted by person, day, and prompt, shift(1).over(["id", "day"]) finds the previous prompt number, opening time, and mood. Its groups prevent a predecessor from crossing participants or reaching back to the previous evening. On E001’s second day, even an unanswered prompt can be the predecessor.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
day_groups = ["id", "day"]
changes = coverage.sort("id", "day", "prompt").with_columns(
    previous_prompt=pl.col("prompt").shift(1).over(day_groups),
    previous_open_utc=pl.col("open_utc").shift(1).over(day_groups),
    previous_mood=pl.col("mood").shift(1).over(day_groups),
)
e001_day_2 = changes.filter((pl.col("id") == "E001") & (pl.col("day") == 2))
korean_clock(e001_day_2).select(
    "prompt",
    "open_kst",
    "mood",
    "previous_prompt",
    "previous_open_kst",
    "previous_mood",
)
1
2
3
4
5
6
7
8
9
10
11
12
shape: (5, 6)
┌────────┬──────────┬──────┬─────────────────┬───────────────────┬───────────────┐
│ prompt ┆ open_kst ┆ mood ┆ previous_prompt ┆ previous_open_kst ┆ previous_mood │
│ ---    ┆ ---      ┆ ---  ┆ ---             ┆ ---               ┆ ---           │
│ i64    ┆ str      ┆ i64  ┆ i64             ┆ str               ┆ i64           │
╞════════╪══════════╪══════╪═════════════════╪═══════════════════╪═══════════════╡
│ 1      ┆ 10:18    ┆ null ┆ null            ┆ null              ┆ null          │
│ 2      ┆ 11:31    ┆ 5    ┆ 1               ┆ 10:18             ┆ null          │
│ 3      ┆ 15:25    ┆ null ┆ 2               ┆ 11:31             ┆ 5             │
│ 4      ┆ 16:46    ┆ 5    ┆ 3               ┆ 15:25             ┆ null          │
│ 5      ┆ 19:32    ┆ 3    ┆ 4               ┆ 16:46             ┆ 5             │
└────────┴──────────┴──────┴─────────────────┴───────────────────┴───────────────┘

On E001’s second day, prompt 4 follows the unanswered third prompt. A second with_columns() calculates minutes between openings and subtracts the earlier mood rating from the later one. For prompt 4, the interval is 81 minutes and the change is null. For the first prompt of each day, both are null.

1
2
3
4
5
6
7
8
9
changes = changes.with_columns(
    interval_min=(pl.col("open_utc") - pl.col("previous_open_utc")).dt.total_seconds()
    / 60,
    mood_change=pl.col("mood") - pl.col("previous_mood"),
)
changes.filter((pl.col("id") == "E001") & pl.col("day").is_in([2, 12])).select(
    "day", "prompt", "mood", "previous_mood", "interval_min", "mood_change"
)
{"rows": changes.height, "with_change": changes["mood_change"].is_not_null().sum()}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
shape: (10, 6)
┌─────┬────────┬──────┬───────────────┬──────────────┬─────────────┐
│ day ┆ prompt ┆ mood ┆ previous_mood ┆ interval_min ┆ mood_change │
│ --- ┆ ---    ┆ ---  ┆ ---           ┆ ---          ┆ ---         │
│ i64 ┆ i64    ┆ i64  ┆ i64           ┆ f64          ┆ i64         │
╞═════╪════════╪══════╪═══════════════╪══════════════╪═════════════╡
│ 2   ┆ 1      ┆ null ┆ null          ┆ null         ┆ null        │
│ 2   ┆ 2      ┆ 5    ┆ null          ┆ 73.0         ┆ null        │
│ 2   ┆ 3      ┆ null ┆ 5             ┆ 234.0        ┆ null        │
│ 2   ┆ 4      ┆ 5    ┆ null          ┆ 81.0         ┆ null        │
│ 2   ┆ 5      ┆ 3    ┆ 5             ┆ 166.0        ┆ -2          │
│ 12  ┆ 1      ┆ 4    ┆ null          ┆ null         ┆ null        │
│ 12  ┆ 2      ┆ 5    ┆ 4             ┆ 138.0        ┆ 1           │
│ 12  ┆ 3      ┆ null ┆ 5             ┆ 155.0        ┆ null        │
│ 12  ┆ 4      ┆ 4    ┆ null          ┆ 98.0         ┆ null        │
│ 12  ┆ 5      ┆ 3    ┆ 4             ┆ 143.0        ┆ -1          │
└─────┴────────┴──────┴───────────────┴──────────────┴─────────────┘
{'rows': 4200, 'with_change': 2074}

On day 2, mood fell from 5 to 3 at the last two prompts, which opened 166 minutes apart. On day 12, prompt 3 received a response without mood. Neither the change from prompt 2 to 3 nor the change from 3 to 4 can be calculated. There are 2,074 observed changes across the study. Which extra pairs would we count if we dropped missing ratings first or allowed comparisons across days?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
mood_only <- coverage |>
  filter(mood_available) |>
  arrange(id, day, prompt) |>
  mutate(previous_prompt = lag(prompt), .by = c(id, day))
within_person_only <- coverage |>
  arrange(id, day, prompt) |>
  mutate(change = mood - lag(mood), .by = id)
c(
  first_prompts = sum(is.na(changes$previous_prompt) & changes$prompt == 1),
  adjacent_pairs = sum(changes$prompt - changes$previous_prompt == 1, na.rm = TRUE),
  observed_pairs = sum(!is.na(changes$mood_change)),
  mood_only_pairs = sum(!is.na(mood_only$previous_prompt)),
  bridging_pairs = sum(mood_only$prompt - mood_only$previous_prompt > 1,
                       na.rm = TRUE),
  evening_to_morning = sum(!is.na(within_person_only$change)) -
    sum(!is.na(changes$mood_change))
)
1
2
     first_prompts     adjacent_pairs     observed_pairs    mood_only_pairs     bridging_pairs evening_to_morning 
               840               3360               2074               2415                341                465 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
mood_only = (
    coverage.filter(pl.col("mood_available"))
    .sort("id", "day", "prompt")
    .with_columns(previous_prompt=pl.col("prompt").shift(1).over(day_groups))
)
within_person_only = coverage.sort("id", "day", "prompt").with_columns(
    change=pl.col("mood") - pl.col("mood").shift(1).over("id")
)
step = pl.col("prompt") - pl.col("previous_prompt")
{
    "first_prompts": changes.filter(
        pl.col("previous_prompt").is_null() & (pl.col("prompt") == 1)
    ).height,
    "adjacent_pairs": changes.filter(step == 1).height,
    "observed_pairs": changes["mood_change"].is_not_null().sum(),
    "mood_only_pairs": mood_only["previous_prompt"].is_not_null().sum(),
    "bridging_pairs": mood_only.filter(step > 1).height,
    "evening_to_morning": within_person_only["change"].is_not_null().sum()
    - changes["mood_change"].is_not_null().sum(),
}
1
{'first_prompts': 840, 'adjacent_pairs': 3360, 'observed_pairs': 2074, 'mood_only_pairs': 2415, 'bridging_pairs': 341, 'evening_to_morning': 465}

Excluding missing mood ratings first adds 341 comparisons that skip at least one prompt. With all scheduled prompts included, grouping by person without separating days adds 465 evening-to-morning comparisons. Neither set represents changes between consecutive prompts within the same day.

Mood changes between consecutive prompts

The 2,074 observed changes describe adjacent prompts with both ratings. To interpret that set, we distinguish it from first prompts, which have no predecessor within the day, and adjacent pairs with a missing rating. Plotting three days for E001 shows how those distinctions affect the observed trajectory. The horizontal positions and intervals refer to scheduled openings, not submission times.

The R summary records these three cases before calculating the mean and spread of the observed changes. For three days of E001, clock_hours() expresses openings as hours after midnight in Korea. geom_vline() marks every prompt with a dashed line. Points mark observed moods. A segment joins two points only where mood_change exists.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
changes |>
  mutate(
    pair_status = case_when(
      is.na(previous_prompt) ~ "first prompt of the day",
      !is.na(mood_change) ~ "both moods observed",
      .default = "a mood unavailable"
    )
  ) |>
  count(pair_status)
changes |>
  filter(!is.na(mood_change)) |>
  summarise(
    pairs = n(),
    mean = mean(mood_change),
    sd = sd(mood_change),
    smallest = min(mood_change),
    largest = max(mood_change),
    median_interval = median(interval_min)
  )
clock_hours <- function(x) {
  local <- with_tz(x, "Asia/Seoul")
  hour(local) + minute(local) / 60
}
plot_prompts <- changes |>
  filter(id == "E001", day %in% c(1, 2, 12)) |>
  mutate(
    panel = factor(paste("Day", day), levels = c("Day 1", "Day 2", "Day 12")),
    hour_kst = clock_hours(open_utc),
    previous_hour_kst = clock_hours(previous_open_utc)
  )
trajectory_plot <- ggplot(plot_prompts) +
  geom_vline(aes(xintercept = hour_kst), colour = "grey60", linetype = "dashed") +
  geom_segment(
    data = filter(plot_prompts, !is.na(mood_change)),
    aes(x = previous_hour_kst, y = previous_mood, xend = hour_kst, yend = mood),
    colour = "#0072B2"
  ) +
  geom_point(
    data = filter(plot_prompts, !is.na(mood)),
    aes(x = hour_kst, y = mood),
    colour = "#0072B2",
    size = 2
  ) +
  facet_wrap(vars(panel), nrow = 1) +
  scale_x_continuous(limits = c(9, 21), breaks = seq(9, 21, by = 3)) +
  scale_y_continuous(limits = c(1, 7), breaks = 1:7) +
  labs(x = "Scheduled prompt time, hour in Korean time", y = "Mood (1 to 7)") +
  theme_minimal(base_size = 11) +
  theme(panel.grid.major.x = element_blank(), panel.grid.minor = element_blank())
dir.create("figures/ch23", showWarnings = FALSE, recursive = TRUE)
ggsave("figures/ch23/fig-23-01.png", trajectory_plot, width = 6.5, height = 4.2,
       units = "in", dpi = 300)
ggsave("figures/ch23/fig-23-01.pdf", trajectory_plot, width = 6.5, height = 4.2,
       units = "in")
c(
  prompt_lines = nrow(layer_data(trajectory_plot, 1)),
  segments = nrow(layer_data(trajectory_plot, 2)),
  points = nrow(layer_data(trajectory_plot, 3))
)
1
2
3
4
5
6
7
8
9
10
11
12
# A tibble: 3 × 2
  pair_status                 n
  <chr>                   <int>
1 a mood unavailable       1286
2 both moods observed      2074
3 first prompt of the day   840
# A tibble: 1 × 6
  pairs    mean    sd smallest largest median_interval
  <int>   <dbl> <dbl>    <int>   <int>           <dbl>
1  2074 0.00145  1.47       -5       4             149
prompt_lines     segments       points 
          15            7           12 

Three panels in one row for days 1, 2, and 12, with hours from 9 to 21 across and mood from 1 to 7 up. Each panel has five dashed vertical lines. Day 1 has five points at 3, 3, 5, 4, and 2 joined by four segments. Day 2 has points at 5, 5, and 3, with a segment only between the last two. Day 12 has points at 4, 5, 4, and 3, with segments between the first two and the last two and a gap at the third dashed line.

Figure 23.1. E001’s mood ratings on three study days, drawn with ggplot2. Each dashed line marks a prompt’s opening time in Korea. A point at that time shows the mood reported in response. A segment connects consecutive prompts when both have ratings.

In Python, pair_status assigns these categories, and the numerical summary uses only nonnull mood_change values. The common horizontal axis shows each opening in Korean local hours. draw_trajectories() draws schedule lines with ax.vlines(), mood points, and a separate segment for each observed adjacent pair on one panel per day. Where a prompt has no mood rating, no segment connects across it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
changes.with_columns(
    pair_status=pl.when(pl.col("previous_prompt").is_null())
    .then(pl.lit("first prompt of the day"))
    .when(pl.col("mood_change").is_not_null())
    .then(pl.lit("both moods observed"))
    .otherwise(pl.lit("a mood unavailable"))
).group_by("pair_status").agg(n=pl.len()).sort("pair_status")
changes.filter(pl.col("mood_change").is_not_null()).select(
    pairs=pl.len(),
    mean=pl.col("mood_change").mean(),
    sd=pl.col("mood_change").std(),
    smallest=pl.col("mood_change").min(),
    largest=pl.col("mood_change").max(),
    median_interval=pl.col("interval_min").median(),
)

import matplotlib.pyplot as plt


def clock_hours(column):
    local = pl.col(column).dt.convert_time_zone("Asia/Seoul")
    return local.dt.hour() + local.dt.minute() / 60


plot_prompts = changes.filter(
    (pl.col("id") == "E001") & pl.col("day").is_in([1, 2, 12])
).with_columns(
    hour_kst=clock_hours("open_utc"),
    previous_hour_kst=clock_hours("previous_open_utc"),
)


def draw_trajectories(prompts, days):
    fig, axes = plt.subplots(
        1, len(days), figsize=(6.5, 4.2), sharey=True, layout="constrained"
    )
    fig.get_layout_engine().set(wspace=0.15)
    for ax, day in zip(axes, days):
        rows = prompts.filter(pl.col("day") == day)
        ax.vlines(rows["hour_kst"], 0.5, 7.5, colors="0.6", linestyles="dashed")
        pairs = rows.filter(pl.col("mood_change").is_not_null())
        for x0, y0, x1, y1 in pairs.select(
            "previous_hour_kst", "previous_mood", "hour_kst", "mood"
        ).iter_rows():
            ax.plot([x0, x1], [y0, y1], color="#0072B2")
        observed = rows.filter(pl.col("mood").is_not_null())
        ax.scatter(observed["hour_kst"], observed["mood"], color="#0072B2", zorder=3)
        ax.set_title(f"Day {day}", fontsize=11)
        ax.set_xlim(9, 21)
        ax.set_xticks([9, 12, 15, 18, 21])
        ax.set_ylim(0.5, 7.5)
        ax.set_yticks(range(1, 8))
        ax.grid(axis="y", color="0.9")
        ax.set_axisbelow(True)
    axes[0].set_ylabel("Mood (1 to 7)", fontsize=11)
    fig.supxlabel("Scheduled prompt time, hour in Korean time", fontsize=11)
    return fig, axes


fig, axes = draw_trajectories(plot_prompts, [1, 2, 12])
Path("figures/ch23").mkdir(parents=True, exist_ok=True)
fig.savefig("figures/ch23/fig-23-02.png", dpi=300)
fig.savefig("figures/ch23/fig-23-02.pdf")
plt.close(fig)
{
    "prompt_lines": [len(ax.collections[0].get_segments()) for ax in axes],
    "segments": [len(ax.lines) for ax in axes],
    "points": [len(ax.collections[1].get_offsets()) for ax in axes],
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
shape: (3, 2)
┌─────────────────────────┬──────┐
│ pair_status             ┆ n    │
│ ---                     ┆ ---  │
│ str                     ┆ u32  │
╞═════════════════════════╪══════╡
│ a mood unavailable      ┆ 1286 │
│ both moods observed     ┆ 2074 │
│ first prompt of the day ┆ 840  │
└─────────────────────────┴──────┘
shape: (1, 6)
┌───────┬──────────┬──────────┬──────────┬─────────┬─────────────────┐
│ pairs ┆ mean     ┆ sd       ┆ smallest ┆ largest ┆ median_interval │
│ ---   ┆ ---      ┆ ---      ┆ ---      ┆ ---     ┆ ---             │
│ u32   ┆ f64      ┆ f64      ┆ i64      ┆ i64     ┆ f64             │
╞═══════╪══════════╪══════════╪══════════╪═════════╪═════════════════╡
│ 2074  ┆ 0.001446 ┆ 1.467939 ┆ -5       ┆ 4       ┆ 149.0           │
└───────┴──────────┴──────────┴──────────┴─────────┴─────────────────┘
{'prompt_lines': [5, 5, 5], 'segments': [4, 1, 2], 'points': [5, 3, 4]}

Three framed panels in one row for days 1, 2, and 12, with hours from 9 to 21 across and mood from 1 to 7 up. Each panel has five dashed vertical lines. Day 1 has five points joined by four segments, day 2 has three points with a segment only between the last two, and day 12 has four points with a gap at the third dashed line.

Figure 23.2. E001’s mood ratings on three study days, drawn with Matplotlib. Each dashed line marks a prompt’s opening time in Korea. A point at that time shows the mood reported in response. A segment connects consecutive prompts when both have ratings.

On day 1, E001 reported mood at all five prompts. On day 2, only the last two ratings are joined. On day 12, E001 answered prompt 3 and reported stress but no mood, so the mood line breaks.

Across the 2,074 consecutive pairs with both ratings, the mean change was close to zero; individual changes ranged from a 5-point fall to a 4-point rise. Each pair contributes once to this mean, so people with more observed pairs contribute more changes. The intervals between openings vary, with a median of 149 minutes for these pairs. The score differences therefore describe change between scheduled occasions, not change over a fixed duration.

This post is licensed under CC BY-NC 4.0 by the author.