Post

Building a Longitudinal Panel

A blank score in a panel study can reflect a missed visit, an unanswered item, or an occasion before the person entered the study. An observed total can present another problem if it disagrees with the answers recorded at that visit. Before comparing scores over time, we need to establish both which observations were expected and which measurements can be used. Here we combine three waves into a common panel, distinguishing enrollment, attendance, and score availability. We then audit supplied totals against their items and calculate changes for people observed at the selected waves, using the recorded dates to describe the intervals between their measurements.

22.1 Harmonizing waves and participant attributes

The first survey file records one participant as 0012. The next two record the same person as 12. A common ID lets us link all three visits to the sex and birth year recorded only when that person entered. Table 22.1 shows how each file records IDs, dates, and survey responses.

Table 22.1. How the three survey files record IDs, dates, item scores, and participant attributes.

FeatureWave 1Wave 2Wave 3
Filepanel_w1.csvpanel_w2.xlsx, sheet Wave 2panel_w3.sav
Fieldwork periodMarch 2024September 2024March 2025
Variable nameslower caselower caseupper case
Identifiertext, 0012numeric cell, 12number, 12
Survey datetext, 2024-03-06serial, 45560, or text, 2024. 9. 25.numeric date with the SPSS display format DATE11
Items and totalstext digitsnumeric cellsnumbers, items with value labels
sex, birth_yearevery rowonly for IDs from 0301 to 0315absent

With col_types = cols(.default = col_character()), readr::read_csv() reads wave-1 IDs such as 0012 as text. In readxl::read_excel(), a list column distinguishes numeric from text date cells in wave 2. In wave 3, haven::read_sav() returns uppercase column names and labeled item codes. Comparing the column names and inspecting the labels identifies the differences to resolve before combining visits.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
library(tidyverse)
library(readxl)
library(haven)
panel_dir <- "data/raw/panel"
w1_raw <- read_csv(
  file.path(panel_dir, "panel_w1.csv"),
  col_types = cols(.default = col_character()),
  na = "",
  trim_ws = FALSE
)
w2_raw <- read_excel(
  file.path(panel_dir, "panel_w2.xlsx"),
  sheet = "Wave 2",
  col_types = c("numeric", "list", rep("numeric", 15))
)
w3_raw <- read_sav(file.path(panel_dir, "panel_w3.sav"))
c(wave_1 = ncol(w1_raw), wave_2 = ncol(w2_raw), wave_3 = ncol(w3_raw))
setdiff(names(w1_raw), names(w2_raw))
setdiff(names(w1_raw), str_to_lower(names(w3_raw)))
setdiff(str_to_lower(names(w3_raw)), names(w1_raw))
attr(w3_raw$DEP_1, "labels")
1
2
3
4
5
6
7
wave_1 wave_2 wave_3 
    17     17     15 
character(0)
[1] "sex"        "birth_year"
character(0)
   Not at all     Sometimes         Often Nearly always 
            0             1             2             3 

The imports confirm that wave 3 lacks sex and birth_year, while its item labels refer to the numeric codes 0 through 3. rename_with() lowercases its column names, and zap_labels() removes the labels before integer conversion. Because mutate() evaluates arguments in order, id_recorded records the original ID before sprintf("%04d", ...) formats it with leading zeros.

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
measure_names <- c(
  paste0("dep_", 1:6), "dep_total", paste0("anx_", 1:5), "anx_total"
)
w1 <- w1_raw |>
  mutate(
    source_file = "panel_w1.csv",
    wave = 1L,
    id_recorded = id,
    across(c(sex, birth_year, all_of(measure_names)), as.integer)
  )
w2 <- w2_raw |>
  mutate(
    source_file = "panel_w2.xlsx",
    wave = 2L,
    id_recorded = as.character(id),
    id = sprintf("%04d", as.integer(id)),
    across(c(sex, birth_year, all_of(measure_names)), as.integer)
  )
w3 <- w3_raw |>
  rename_with(str_to_lower) |>
  mutate(
    source_file = "panel_w3.sav",
    wave = 3L,
    id_recorded = as.character(id),
    id = sprintf("%04d", as.integer(id)),
    across(all_of(measure_names), \(x) as.integer(zap_labels(x)))
  )
bind_rows(
  select(w1, wave, id_recorded, id),
  select(w2, wave, id_recorded, id),
  select(w3, wave, id_recorded, id)
) |>
  filter(id == "0012")
1
2
3
4
5
6
# A tibble: 3 × 3
   wave id_recorded id   
  <int> <chr>       <chr>
1     1 0012        0012 
2     2 12          0012 
3     3 12          0012 

All three visits now have the ID 0012. Their dates also need a common representation. Wave 1 records dates as year-month-day text. In wave 2, a numeric cell counts days from December 30, 1899, while a text cell gives a dotted date. In wave 3, read_sav() has already converted the DATE11 values to R dates.

For the CSV and workbook, date_recorded stores the text or serial number used to obtain date. The SPSS import does not provide that separate representation here, so the code assigns NA to date_recorded and records the declared format in date_source. This NA does not mean that the visit date is missing: date contains the imported date. The earliest and latest dates can then be checked against each wave’s fieldwork month in Table 22.1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
w1 <- w1 |>
  mutate(date_recorded = date, date = ymd(date), date_source = "ISO text")
w2 <- w2 |>
  mutate(
    date_cell = map_chr(date, class),
    date_serial = map_dbl(date, \(x) if (is.numeric(x)) x else NA_real_),
    date_text = map_chr(date, \(x) if (is.character(x)) x else NA_character_),
    date_recorded = coalesce(date_text, as.character(date_serial)),
    date = if_else(
      date_cell == "numeric",
      as.Date(date_serial, origin = "1899-12-30"),
      ymd(date_text)
    ),
    date_source = if_else(date_cell == "numeric", "Excel serial", "dotted text")
  )
w3 <- w3 |>
  mutate(
    date_recorded = NA_character_,
    date_source = paste("SPSS", attr(w3_raw$DATE, "format.spss"))
  )
bind_rows(
  filter(w1, id == "0001"),
  filter(w2, id %in% c("0001", "0003")),
  filter(w3, id == "0001")
) |>
  select(wave, id, date_source, date_recorded, date)
bind_rows(w1, w2, w3) |>
  summarise(rows = n(), first = min(date), last = max(date), .by = c(wave, date_source))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# A tibble: 4 × 5
   wave id    date_source  date_recorded date      
  <int> <chr> <chr>        <chr>         <date>    
1     1 0001  ISO text     2024-03-06    2024-03-06
2     2 0001  dotted text  2024. 9. 25.  2024-09-25
3     2 0003  Excel serial 45560         2024-09-25
4     3 0001  SPSS DATE11  <NA>          2025-03-25
# A tibble: 4 × 5
   wave date_source   rows first      last      
  <int> <chr>        <int> <date>     <date>    
1     1 ISO text       300 2024-03-04 2024-03-29
2     2 dotted text    105 2024-09-02 2024-09-27
3     2 Excel serial   168 2024-09-02 2024-09-27
4     3 SPSS DATE11    254 2025-03-03 2025-03-28

With infer_schema=False, pl.read_csv() reads wave-1 IDs as text, including leading zeros. For wave 2, openpyxl identifies each date cell as numeric or text. The loop assigns its value to date_serial or date_text accordingly. For wave 3, pyreadstat.read_sav() reads the item codes as numbers and returns the labels in w3_meta. Comparing the column names and inspecting the labels identifies the differences to resolve before combining visits.

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
from pathlib import Path

import openpyxl
import polars as pl
import pyreadstat

panel_dir = Path("data/raw/panel")
w1_raw = pl.read_csv(panel_dir / "panel_w1.csv", infer_schema=False)
book = openpyxl.load_workbook(panel_dir / "panel_w2.xlsx")
sheet = book["Wave 2"]
header = [cell.value for cell in sheet[1]]
w2_rows = []
for row in sheet.iter_rows(min_row=2):
    record = {name: cell.value for name, cell in zip(header, row) if name != "date"}
    date_cell = row[header.index("date")]
    record["date_cell"] = date_cell.data_type
    record["date_serial"] = date_cell.value if date_cell.data_type == "n" else None
    record["date_text"] = date_cell.value if date_cell.data_type == "s" else None
    w2_rows.append(record)

w2_raw = pl.DataFrame(w2_rows, infer_schema_length=None)
w3_raw, w3_meta = pyreadstat.read_sav(
    panel_dir / "panel_w3.sav",
    output_format="polars",
    user_missing=True,
    apply_value_formats=False,
)
{"wave_1": w1_raw.width, "wave_2": len(header), "wave_3": w3_raw.width}
[name for name in w1_raw.columns if name not in header]
[name for name in w1_raw.columns if name.upper() not in w3_raw.columns]
[name for name in w3_raw.columns if name.lower() not in w1_raw.columns]
w3_meta.variable_value_labels["DEP_1"]
1
2
3
4
5
{'wave_1': 17, 'wave_2': 17, 'wave_3': 15}
[]
['sex', 'birth_year']
[]
{0.0: 'Not at all', 1.0: 'Sometimes', 2.0: 'Often', 3.0: 'Nearly always'}

The imports confirm that wave 3 lacks sex and birth_year, while its item labels refer to the numeric codes 0 through 3. After the names are converted to lowercase, the three tables can use the same item columns. Expressions in with_columns() read the input columns, so id_recorded records the original ID as text while id receives the four-digit form. Casting a wave-3 ID to an integer first gives 12 in place of 12.0.

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
measure_names = [
    *[f"dep_{n}" for n in range(1, 7)], "dep_total",
    *[f"anx_{n}" for n in range(1, 6)], "anx_total",
]
integer_columns = ["sex", "birth_year", *measure_names]
w1 = w1_raw.with_columns(
    pl.col(integer_columns).cast(pl.Int64),
    source_file=pl.lit("panel_w1.csv"),
    wave=pl.lit(1),
    id_recorded=pl.col("id"),
)
w2 = w2_raw.with_columns(
    pl.col(integer_columns).cast(pl.Int64),
    source_file=pl.lit("panel_w2.xlsx"),
    wave=pl.lit(2),
    id_recorded=pl.col("id").cast(pl.String),
    id=pl.col("id").cast(pl.String).str.zfill(4),
)
w3 = w3_raw.rename(str.lower).with_columns(
    pl.col(measure_names).cast(pl.Int64),
    source_file=pl.lit("panel_w3.sav"),
    wave=pl.lit(3),
    id_recorded=pl.col("id").cast(pl.Int64).cast(pl.String),
    id=pl.col("id").cast(pl.Int64).cast(pl.String).str.zfill(4),
)
key_columns = ["wave", "id_recorded", "id"]
pl.concat(
    [w1.select(key_columns), w2.select(key_columns), w3.select(key_columns)],
    how="vertical",
).filter(pl.col("id") == "0012")
1
2
3
4
5
6
7
8
9
10
shape: (3, 3)
┌──────┬─────────────┬──────┐
│ wave ┆ id_recorded ┆ id   │
│ ---  ┆ ---         ┆ ---  │
│ i32  ┆ str         ┆ str  │
╞══════╪═════════════╪══════╡
│ 1    ┆ 0012        ┆ 0012 │
│ 2    ┆ 12          ┆ 0012 │
│ 3    ┆ 12          ┆ 0012 │
└──────┴─────────────┴──────┘

All three visits now have the ID 0012. Their dates also need a common representation. Wave 1 uses %Y-%m-%d. For numeric wave-2 dates, book.epoch gives the date from which the workbook counts days; for dotted text, str.to_date() uses %Y. %-m. %-d.. pl.coalesce() selects the date text or the serial number converted to text for date_recorded.

In wave 3, pyreadstat has already converted DATE11 to pl.Date. The code records the declared format in date_source but does not store a separate pre-conversion representation in date_recorded, which is null. This null does not mean that the visit date is missing: date contains the imported date. Each wave’s date range should fall within the fieldwork month in Table 22.1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
origin = book.epoch.date()
origin
w1 = w1.with_columns(
    date_recorded=pl.col("date"),
    date=pl.col("date").str.to_date("%Y-%m-%d"),
    date_source=pl.lit("ISO text"),
)
w2 = w2.with_columns(
    date_recorded=pl.coalesce("date_text", pl.col("date_serial").cast(pl.String)),
    date=pl.when(pl.col("date_cell") == "n")
    .then(pl.lit(origin) + pl.duration(days=pl.col("date_serial")))
    .otherwise(pl.col("date_text").str.to_date("%Y. %-m. %-d.")),
    date_source=pl.when(pl.col("date_cell") == "n")
    .then(pl.lit("Excel serial"))
    .otherwise(pl.lit("dotted text")),
)
w3 = w3.with_columns(
    date_recorded=pl.lit(None, dtype=pl.String),
    date_source=pl.lit("SPSS " + w3_meta.original_variable_types["DATE"]),
)
date_columns = ["wave", "id", "date_source", "date_recorded", "date"]
pl.concat(
    [
        w1.filter(pl.col("id") == "0001").select(date_columns),
        w2.filter(pl.col("id").is_in(["0001", "0003"])).select(date_columns),
        w3.filter(pl.col("id") == "0001").select(date_columns),
    ],
    how="vertical",
)
pl.concat(
    [w1.select(date_columns), w2.select(date_columns), w3.select(date_columns)],
    how="vertical",
).group_by("wave", "date_source").agg(
    rows=pl.len(), first=pl.col("date").min(), last=pl.col("date").max()
).sort("wave", "date_source")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
datetime.date(1899, 12, 30)
shape: (4, 5)
┌──────┬──────┬──────────────┬───────────────┬────────────┐
│ wave ┆ id   ┆ date_source  ┆ date_recorded ┆ date       │
│ ---  ┆ ---  ┆ ---          ┆ ---           ┆ ---        │
│ i32  ┆ str  ┆ str          ┆ str           ┆ date       │
╞══════╪══════╪══════════════╪═══════════════╪════════════╡
│ 1    ┆ 0001 ┆ ISO text     ┆ 2024-03-06    ┆ 2024-03-06 │
│ 2    ┆ 0001 ┆ dotted text  ┆ 2024. 9. 25.  ┆ 2024-09-25 │
│ 2    ┆ 0003 ┆ Excel serial ┆ 45560         ┆ 2024-09-25 │
│ 3    ┆ 0001 ┆ SPSS DATE11  ┆ null          ┆ 2025-03-25 │
└──────┴──────┴──────────────┴───────────────┴────────────┘
shape: (4, 5)
┌──────┬──────────────┬──────┬────────────┬────────────┐
│ wave ┆ date_source  ┆ rows ┆ first      ┆ last       │
│ ---  ┆ ---          ┆ ---  ┆ ---        ┆ ---        │
│ i32  ┆ str          ┆ u32  ┆ date       ┆ date       │
╞══════╪══════════════╪══════╪════════════╪════════════╡
│ 1    ┆ ISO text     ┆ 300  ┆ 2024-03-04 ┆ 2024-03-29 │
│ 2    ┆ Excel serial ┆ 168  ┆ 2024-09-02 ┆ 2024-09-27 │
│ 2    ┆ dotted text  ┆ 105  ┆ 2024-09-02 ┆ 2024-09-27 │
│ 3    ┆ SPSS DATE11  ┆ 254  ┆ 2025-03-03 ┆ 2025-03-28 │
└──────┴──────────────┴──────┴────────────┴────────────┘

All recovered dates fall within their fieldwork months. The visits can now be ordered by wave and linked by ID.

Attributes recorded at entry

Sex and birth year describe the participant and were recorded at entry, in wave 1 for IDs from 0001 to 0300 and in wave 2 for IDs from 0301 to 0315. Wave 3 has neither field. Before constructing one participant row per ID, we check whether the files agree with that recording rule. Does any ID have two rows with these attributes, and did wave 2 record either value for a wave-1 entrant?

1
2
3
4
5
6
7
8
9
10
11
12
13
observed_attributes <- bind_rows(w1, w2) |>
  filter(!is.na(sex) | !is.na(birth_year)) |>
  select(id, attribute_wave = wave, sex, birth_year)
count(observed_attributes, attribute_wave, name = "people")
repeated_ids <- observed_attributes |>
  count(id) |>
  filter(n > 1)
c(
  people_with_two_sources = nrow(repeated_ids),
  wave_2_attributes_for_wave_1_people = sum(
    !is.na(w2$sex[w2$id %in% w1$id]) | !is.na(w2$birth_year[w2$id %in% w1$id])
  )
)
1
2
3
4
5
6
7
# A tibble: 2 × 2
  attribute_wave people
           <int>  <int>
1              1    300
2              2     15
            people_with_two_sources wave_2_attributes_for_wave_1_people 
                                  0                                   0 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
attribute_columns = ["id", "wave", "sex", "birth_year"]
observed_attributes = (
    pl.concat(
        [w1.select(attribute_columns), w2.select(attribute_columns)], how="vertical"
    )
    .filter(pl.col("sex").is_not_null() | pl.col("birth_year").is_not_null())
    .rename({"wave": "attribute_wave"})
)
observed_attributes.group_by("attribute_wave").agg(people=pl.len()).sort(
    "attribute_wave"
)
wave_1_ids = w1["id"].to_list()
repeated_ids = observed_attributes.group_by("id").len().filter(pl.col("len") > 1)
{
    "people_with_two_sources": repeated_ids.height,
    "wave_2_attributes_for_wave_1_people": w2.filter(
        pl.col("id").is_in(wave_1_ids)
        & (pl.col("sex").is_not_null() | pl.col("birth_year").is_not_null())
    ).height,
}
1
2
3
4
5
6
7
8
9
10
shape: (2, 2)
┌────────────────┬────────┐
│ attribute_wave ┆ people │
│ ---            ┆ ---    │
│ i32            ┆ u32    │
╞════════════════╪════════╡
│ 1              ┆ 300    │
│ 2              ┆ 15     │
└────────────────┴────────┘
{'people_with_two_sources': 0, 'wave_2_attributes_for_wave_1_people': 0}

No ID appears twice among the rows with sex or birth year, and neither field was recorded again in wave 2 for a wave-1 entrant. Every participant’s entry visit is in these files, so the first recorded wave gives entry_wave for both entry cohorts. The R join matches each ID to the attributes recorded at entry. without_attributes counts people still missing sex or birth year after the join.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
visit_keys <- bind_rows(
  select(w1, id, wave),
  select(w2, id, wave),
  select(w3, id, wave)
)
participants <- visit_keys |>
  summarise(entry_wave = min(wave), .by = id) |>
  left_join(
    observed_attributes,
    by = join_by(id, entry_wave == attribute_wave),
    relationship = "one-to-one"
  ) |>
  mutate(attribute_source = c("panel_w1.csv", "panel_w2.xlsx")[entry_wave]) |>
  arrange(id)
filter(participants, id %in% c("0001", "0301"))
c(
  participants = nrow(participants),
  without_attributes = sum(is.na(participants$sex) | is.na(participants$birth_year)),
  later_entrants = sum(participants$entry_wave == 2),
  cohort_match = sum(participants$id[participants$entry_wave == 2] %in%
    sprintf("%04d", 301:315))
)
visit_keys |>
  filter(id == "0301") |>
  left_join(participants, by = join_by(id), relationship = "many-to-one")
1
2
3
4
5
6
7
8
9
10
11
12
# A tibble: 2 × 5
  id    entry_wave   sex birth_year attribute_source
  <chr>      <int> <int>      <int> <chr>           
1 0001           1     2       1987 panel_w1.csv    
2 0301           2     2       1975 panel_w2.xlsx   
      participants without_attributes     later_entrants       cohort_match 
               315                  0                 15                 15 
# A tibble: 2 × 6
  id     wave entry_wave   sex birth_year attribute_source
  <chr> <int>      <int> <int>      <int> <chr>           
1 0301      2          2     2       1975 panel_w2.xlsx   
2 0301      3          2     2       1975 panel_w2.xlsx   

In Polars, the first recorded wave gives entry_wave because everyone’s entry visit is in the files. The left join matches ID and entry wave to ID and attribute_wave. validate="1:1" checks that the join keys are unique on both sides. without_attributes counts people missing either attribute after the join.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
visit_keys = pl.concat(
    [w1.select("id", "wave"), w2.select("id", "wave"), w3.select("id", "wave")],
    how="vertical",
)
participants = (
    visit_keys.group_by("id")
    .agg(entry_wave=pl.col("wave").min())
    .join(
        observed_attributes,
        left_on=["id", "entry_wave"],
        right_on=["id", "attribute_wave"],
        how="left",
        validate="1:1",
    )
    .with_columns(
        attribute_source=pl.when(pl.col("entry_wave") == 1)
        .then(pl.lit("panel_w1.csv"))
        .otherwise(pl.lit("panel_w2.xlsx"))
    )
    .sort("id")
)
participants.filter(pl.col("id").is_in(["0001", "0301"]))
later_ids = [f"{n:04d}" for n in range(301, 316)]
{
    "participants": participants.height,
    "without_attributes": participants.filter(
        pl.col("sex").is_null() | pl.col("birth_year").is_null()
    ).height,
    "later_entrants": (participants["entry_wave"] == 2).sum(),
    "cohort_match": participants.filter(pl.col("entry_wave") == 2)["id"]
    .is_in(later_ids)
    .sum(),
}
visit_keys.filter(pl.col("id") == "0301").join(
    participants, on="id", how="left", validate="m:1"
).sort("wave")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
shape: (2, 5)
┌──────┬────────────┬─────┬────────────┬──────────────────┐
│ id   ┆ entry_wave ┆ sex ┆ birth_year ┆ attribute_source │
│ ---  ┆ ---        ┆ --- ┆ ---        ┆ ---              │
│ str  ┆ i32        ┆ i64 ┆ i64        ┆ str              │
╞══════╪════════════╪═════╪════════════╪══════════════════╡
│ 0001 ┆ 1          ┆ 2   ┆ 1987       ┆ panel_w1.csv     │
│ 0301 ┆ 2          ┆ 2   ┆ 1975       ┆ panel_w2.xlsx    │
└──────┴────────────┴─────┴────────────┴──────────────────┘
{'participants': 315, 'without_attributes': 0, 'later_entrants': 15, 'cohort_match': 15}
shape: (2, 6)
┌──────┬──────┬────────────┬─────┬────────────┬──────────────────┐
│ id   ┆ wave ┆ entry_wave ┆ sex ┆ birth_year ┆ attribute_source │
│ ---  ┆ ---  ┆ ---        ┆ --- ┆ ---        ┆ ---              │
│ str  ┆ i32  ┆ i32        ┆ i64 ┆ i64        ┆ str              │
╞══════╪══════╪════════════╪═════╪════════════╪══════════════════╡
│ 0301 ┆ 2    ┆ 2          ┆ 2   ┆ 1975       ┆ panel_w2.xlsx    │
│ 0301 ┆ 3    ┆ 2          ┆ 2   ┆ 1975       ┆ panel_w2.xlsx    │
└──────┴──────┴────────────┴─────┴────────────┴──────────────────┘

Across all 315 participants, without_attributes is zero. Only the 15 later entrants have wave-2 attributes. Both visits for 0301 list panel_w2.xlsx as the source of sex and birth year, including the visit in wave 3.

One row per recorded visit

participants records sex and birth year once per person. The scores and dates instead belong to individual visits. bind_rows() and pl.concat() stack these visit fields in visits, where each ID–wave pair should identify one row and each ID should match a participant. The checks below compare row and key counts, test for unmatched IDs, and confirm that participant attributes were not copied into the visit table. The Python expression {"sex", "birth_year"} & set(visits.columns) identifies any such attribute columns.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
visit_columns <- c(
  "source_file", "wave", "id", "id_recorded", "date", "date_source",
  "date_recorded", measure_names
)
visits <- bind_rows(
  select(w1, all_of(visit_columns)),
  select(w2, all_of(visit_columns)),
  select(w3, all_of(visit_columns))
)
count(visits, wave, source_file)
c(
  visits = nrow(visits),
  keys = n_distinct(visits$id, visits$wave),
  people = n_distinct(visits$id),
  participant_rows = nrow(participants),
  unmatched_visits = sum(!visits$id %in% participants$id),
  attribute_columns = sum(c("sex", "birth_year") %in% names(visits))
)
1
2
3
4
5
6
7
8
9
10
# A tibble: 3 × 3
   wave source_file       n
  <int> <chr>         <int>
1     1 panel_w1.csv    300
2     2 panel_w2.xlsx   273
3     3 panel_w3.sav    254
           visits              keys            people  participant_rows 
              827               827               315               315 
 unmatched_visits attribute_columns 
                0                 0 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
visit_columns = [
    "source_file", "wave", "id", "id_recorded", "date", "date_source",
    "date_recorded", *measure_names,
]
visits = pl.concat(
    [w1.select(visit_columns), w2.select(visit_columns), w3.select(visit_columns)],
    how="vertical",
)
visits.group_by("wave", "source_file").agg(n=pl.len()).sort("wave")
{
    "visits": visits.height,
    "keys": visits.select("id", "wave").n_unique(),
    "people": visits["id"].n_unique(),
    "participant_rows": participants.height,
    "unmatched_visits": visits.filter(
        ~pl.col("id").is_in(participants["id"].to_list())
    ).height,
    "attribute_columns": len({"sex", "birth_year"} & set(visits.columns)),
}
1
2
3
4
5
6
7
8
9
10
11
shape: (3, 3)
┌──────┬───────────────┬─────┐
│ wave ┆ source_file   ┆ n   │
│ ---  ┆ ---           ┆ --- │
│ i32  ┆ str           ┆ u32 │
╞══════╪═══════════════╪═════╡
│ 1    ┆ panel_w1.csv  ┆ 300 │
│ 2    ┆ panel_w2.xlsx ┆ 273 │
│ 3    ┆ panel_w3.sav  ┆ 254 │
└──────┴───────────────┴─────┘
{'visits': 827, 'keys': 827, 'people': 315, 'participant_rows': 315, 'unmatched_visits': 0, 'attribute_columns': 0}

The three files contribute 300, 273, and 254 visits, totaling 827 unique person-wave records for 315 people. Who was due for a visit but had no row in that wave’s file?

22.2 Distinguishing enrollment, attendance, and missing measurements

Someone with no row in a wave file may have missed a scheduled visit or joined the study later. Someone who attended can still have a blank total if they left an item unanswered. The eligible field records whether the person was due for a visit. Separate fields record whether a visit took place and which scores were available there.

In R, cross_join() pairs every participant with waves 1 to 3, giving both 0001 and 0301 a wave-1 row. The comparison wave >= entry_wave distinguishes the visit scheduled for 0001 from the occasion before 0301 entered.

1
2
3
4
5
6
7
8
9
10
11
grid <- participants |>
  select(id, entry_wave) |>
  cross_join(tibble(wave = 1:3)) |>
  mutate(eligible = wave >= entry_wave)
c(
  rows = nrow(grid),
  people = n_distinct(grid$id),
  keys = n_distinct(grid$id, grid$wave),
  not_eligible = sum(!grid$eligible)
)
filter(grid, id %in% c("0001", "0301"))
1
2
3
4
5
6
7
8
9
10
11
        rows       people         keys not_eligible 
         945          315          945           15 
# A tibble: 6 × 4
  id    entry_wave  wave eligible
  <chr>      <int> <int> <lgl>   
1 0001           1     1 TRUE    
2 0001           1     2 TRUE    
3 0001           1     3 TRUE    
4 0301           2     1 FALSE   
5 0301           2     2 TRUE    
6 0301           2     3 TRUE    

The grid has 945 rows, three for each of 315 people. Fifteen wave-1 rows fall before entry. Before the one-to-one left join on ID and wave, each recorded visit is marked record_present = TRUE. This identifies an attended visit even if both totals are missing. For grid rows with no matching visit, coalesce() changes the missing flag to FALSE. An unmatched row counts as a missed visit only if the person was eligible.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
panel_grid <- grid |>
  left_join(
    visits |>
      select(id, wave, date, dep_total, anx_total) |>
      mutate(record_present = TRUE),
    by = join_by(id, wave),
    relationship = "one-to-one"
  ) |>
  mutate(
    record_present = coalesce(record_present, FALSE),
    participation = case_when(
      !eligible ~ "before entry",
      record_present ~ "attended",
      .default = "missed"
    ),
    dep_available = !is.na(dep_total),
    anx_available = !is.na(anx_total)
  )
count(panel_grid, eligible, record_present, participation)
panel_grid |>
  filter(!dep_available) |>
  count(participation, name = "blank_dep_totals")
1
2
3
4
5
6
7
8
9
10
11
12
# A tibble: 3 × 4
  eligible record_present participation     n
  <lgl>    <lgl>          <chr>         <int>
1 FALSE    FALSE          before entry     15
2 TRUE     FALSE          missed          103
3 TRUE     TRUE           attended        827
# A tibble: 3 × 2
  participation blank_dep_totals
  <chr>                    <int>
1 attended                    55
2 before entry                15
3 missed                     103

In Polars, the cross join pairs participants and their entry waves with Int32 wave numbers, the type used in the visit key. Both 0001 and 0301 therefore have a wave-1 row. wave >= entry_wave tells us whether each was due for a visit.

1
2
3
4
5
6
7
8
9
10
11
12
13
waves = pl.DataFrame({"wave": [1, 2, 3]}, schema={"wave": pl.Int32})
grid = (
    participants.select("id", "entry_wave")
    .join(waves, how="cross")
    .with_columns(eligible=pl.col("wave") >= pl.col("entry_wave"))
)
{
    "rows": grid.height,
    "people": grid["id"].n_unique(),
    "keys": grid.select("id", "wave").n_unique(),
    "not_eligible": (~grid["eligible"]).sum(),
}
grid.filter(pl.col("id").is_in(["0001", "0301"])).sort("id", "wave")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{'rows': 945, 'people': 315, 'keys': 945, 'not_eligible': 15}
shape: (6, 4)
┌──────┬────────────┬──────┬──────────┐
│ id   ┆ entry_wave ┆ wave ┆ eligible │
│ ---  ┆ ---        ┆ ---  ┆ ---      │
│ str  ┆ i32        ┆ i32  ┆ bool     │
╞══════╪════════════╪══════╪══════════╡
│ 0001 ┆ 1          ┆ 1    ┆ true     │
│ 0001 ┆ 1          ┆ 2    ┆ true     │
│ 0001 ┆ 1          ┆ 3    ┆ true     │
│ 0301 ┆ 2          ┆ 1    ┆ false    │
│ 0301 ┆ 2          ┆ 2    ┆ true     │
│ 0301 ┆ 2          ┆ 3    ┆ true     │
└──────┴────────────┴──────┴──────────┘

Participant 0301 was not due for a wave-1 visit. Before the join on ID and wave, each visit row is marked record_present=True. For a grid row with no matching visit, fill_null(False) changes only the presence flag. If that person was eligible, the visit was missed. At an attended visit, is_not_null() checks each total separately.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
recorded = visits.select("id", "wave", "date", "dep_total", "anx_total").with_columns(
    record_present=pl.lit(True)
)
panel_grid = (
    grid.join(recorded, on=["id", "wave"], how="left", validate="1:1")
    .with_columns(pl.col("record_present").fill_null(False))
    .with_columns(
        participation=pl.when(~pl.col("eligible"))
        .then(pl.lit("before entry"))
        .when(pl.col("record_present"))
        .then(pl.lit("attended"))
        .otherwise(pl.lit("missed")),
        dep_available=pl.col("dep_total").is_not_null(),
        anx_available=pl.col("anx_total").is_not_null(),
    )
    .sort("id", "wave")
)
panel_grid.group_by("eligible", "record_present", "participation").agg(
    n=pl.len()
).sort("eligible", "record_present")
panel_grid.filter(~pl.col("dep_available")).group_by("participation").agg(
    blank_dep_totals=pl.len()
).sort("participation")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
shape: (3, 4)
┌──────────┬────────────────┬───────────────┬─────┐
│ eligible ┆ record_present ┆ participation ┆ n   │
│ ---      ┆ ---            ┆ ---           ┆ --- │
│ bool     ┆ bool           ┆ str           ┆ u32 │
╞══════════╪════════════════╪═══════════════╪═════╡
│ false    ┆ false          ┆ before entry  ┆ 15  │
│ true     ┆ false          ┆ missed        ┆ 103 │
│ true     ┆ true           ┆ attended      ┆ 827 │
└──────────┴────────────────┴───────────────┴─────┘
shape: (3, 2)
┌───────────────┬──────────────────┐
│ participation ┆ blank_dep_totals │
│ ---           ┆ ---              │
│ str           ┆ u32              │
╞═══════════════╪══════════════════╡
│ attended      ┆ 55               │
│ before entry  ┆ 15               │
│ missed        ┆ 103              │
└───────────────┴──────────────────┘

The files record 827 visits. Another 103 visits were due but missed. Among the recorded visits, 55 lack a depression total. The three rows below all have a blank depression total. Which participant missed a scheduled visit?

1
2
3
4
5
panel_grid |>
  filter(
    (id == "0001" & wave == 3) | (id == "0002" & wave == 2) | (id == "0301" & wave == 1)
  ) |>
  select(id, wave, eligible, record_present, participation, dep_total, dep_available)
1
2
3
4
5
6
# A tibble: 3 × 7
  id     wave eligible record_present participation dep_total dep_available
  <chr> <int> <lgl>    <lgl>          <chr>             <int> <lgl>        
1 0001      3 TRUE     TRUE           attended             NA FALSE        
2 0002      2 TRUE     FALSE          missed               NA FALSE        
3 0301      1 FALSE    FALSE          before entry         NA FALSE        
1
2
3
4
5
6
7
8
panel_grid.filter(
    ((pl.col("id") == "0001") & (pl.col("wave") == 3))
    | ((pl.col("id") == "0002") & (pl.col("wave") == 2))
    | ((pl.col("id") == "0301") & (pl.col("wave") == 1))
).select(
    "id", "wave", "eligible", "record_present", "participation", "dep_total",
    "dep_available",
)
1
2
3
4
5
6
7
8
9
10
shape: (3, 7)
┌──────┬──────┬──────────┬────────────────┬───────────────┬───────────┬───────────────┐
│ id   ┆ wave ┆ eligible ┆ record_present ┆ participation ┆ dep_total ┆ dep_available │
│ ---  ┆ ---  ┆ ---      ┆ ---            ┆ ---           ┆ ---       ┆ ---           │
│ str  ┆ i32  ┆ bool     ┆ bool           ┆ str           ┆ i64       ┆ bool          │
╞══════╪══════╪══════════╪════════════════╪═══════════════╪═══════════╪═══════════════╡
│ 0001 ┆ 3    ┆ true     ┆ true           ┆ attended      ┆ null      ┆ false         │
│ 0002 ┆ 2    ┆ true     ┆ false          ┆ missed        ┆ null      ┆ false         │
│ 0301 ┆ 1    ┆ false    ┆ false          ┆ before entry  ┆ null      ┆ false         │
└──────┴──────┴──────────┴────────────────┴───────────────┴───────────┴───────────────┘

Of the three, only 0002 missed the visit shown. At wave 2, eligible is true and record_present is false. Participant 0001 attended wave 3, and 0301 had yet to enter at wave 1.

A missed visit does not necessarily end participation. Participant 0062 missed wave 2; the wave-3 record shows whether they returned.

1
2
3
panel_grid |>
  filter(id == "0062") |>
  select(id, wave, participation, date, dep_total, anx_total)
1
2
3
4
5
6
# A tibble: 3 × 6
  id     wave participation date       dep_total anx_total
  <chr> <int> <chr>         <date>         <int>     <int>
1 0062      1 attended      2024-03-08         6         4
2 0062      2 missed        NA                NA        NA
3 0062      3 attended      2025-03-04         9        10
1
2
3
panel_grid.filter(pl.col("id") == "0062").select(
    "id", "wave", "participation", "date", "dep_total", "anx_total"
)
1
2
3
4
5
6
7
8
9
10
shape: (3, 6)
┌──────┬──────┬───────────────┬────────────┬───────────┬───────────┐
│ id   ┆ wave ┆ participation ┆ date       ┆ dep_total ┆ anx_total │
│ ---  ┆ ---  ┆ ---           ┆ ---        ┆ ---       ┆ ---       │
│ str  ┆ i32  ┆ str           ┆ date       ┆ i64       ┆ i64       │
╞══════╪══════╪═══════════════╪════════════╪═══════════╪═══════════╡
│ 0062 ┆ 1    ┆ attended      ┆ 2024-03-08 ┆ 6         ┆ 4         │
│ 0062 ┆ 2    ┆ missed        ┆ null       ┆ null      ┆ null      │
│ 0062 ┆ 3    ┆ attended      ┆ 2025-03-04 ┆ 9         ┆ 10        │
└──────┴──────┴───────────────┴────────────┴───────────┴───────────┘

Participant 0062 returned at wave 3, with depression and anxiety totals at both the first and last visits.

Attendance patterns and measurement availability

In the R summary, A, M, and - stand for attended, missed, and before entry. After the rows are sorted by person and wave, paste() with collapse = "" joins each person’s three codes into one string. For 0062, AMA records the missed visit between two attended visits. The wave summaries count attendance and the number of visitors with each total or with both.

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
status_codes <- c(attended = "A", missed = "M", "before entry" = "-")
patterns <- panel_grid |>
  arrange(id, wave) |>
  summarise(
    pattern = paste(status_codes[participation], collapse = ""),
    .by = id
  )
count(patterns, pattern, sort = TRUE, name = "people")
panel_grid |>
  summarise(
    eligible = sum(eligible),
    attended = sum(participation == "attended"),
    missed = sum(participation == "missed"),
    before_entry = sum(participation == "before entry"),
    .by = wave
  )
panel_grid |>
  filter(participation == "attended") |>
  summarise(
    attended = n(),
    with_dep = sum(dep_available),
    with_anx = sum(anx_available),
    with_both = sum(dep_available & anx_available),
    .by = wave
  )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# A tibble: 6 × 2
  pattern people
  <chr>    <int>
1 AAA        234
2 AMM         33
3 AAM         24
4 -AA         11
5 AMA          9
6 -AM          4
# A tibble: 3 × 5
   wave eligible attended missed before_entry
  <int>    <int>    <int>  <int>        <int>
1     1      300      300      0           15
2     2      315      273     42            0
3     3      315      254     61            0
# A tibble: 3 × 5
   wave attended with_dep with_anx with_both
  <int>    <int>    <int>    <int>     <int>
1     1      300      276      283       262
2     2      273      259      258       246
3     3      254      237      241       225

In Polars, the rows within each group follow the grid’s wave order. maintain_order=True orders the groups by their first appearance. replace_strict() assigns A to an attended visit, M to a missed visit, and - to a wave before entry. str.join("") combines the three symbols for each person. The wave summaries count visitors with each total and with both.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
status_codes = {"attended": "A", "missed": "M", "before entry": "-"}
patterns = panel_grid.group_by("id", maintain_order=True).agg(
    pattern=pl.col("participation").replace_strict(status_codes).str.join("")
)
patterns.group_by("pattern").agg(people=pl.len()).sort("people", descending=True)
panel_grid.group_by("wave").agg(
    eligible=pl.col("eligible").sum(),
    attended=(pl.col("participation") == "attended").sum(),
    missed=(pl.col("participation") == "missed").sum(),
    before_entry=(pl.col("participation") == "before entry").sum(),
).sort("wave")
panel_grid.filter(pl.col("participation") == "attended").group_by("wave").agg(
    attended=pl.len(),
    with_dep=pl.col("dep_available").sum(),
    with_anx=pl.col("anx_available").sum(),
    with_both=(pl.col("dep_available") & pl.col("anx_available")).sum(),
).sort("wave")
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
shape: (6, 2)
┌─────────┬────────┐
│ pattern ┆ people │
│ ---     ┆ ---    │
│ str     ┆ u32    │
╞═════════╪════════╡
│ AAA     ┆ 234    │
│ AMM     ┆ 33     │
│ AAM     ┆ 24     │
│ -AA     ┆ 11     │
│ AMA     ┆ 9      │
│ -AM     ┆ 4      │
└─────────┴────────┘
shape: (3, 5)
┌──────┬──────────┬──────────┬────────┬──────────────┐
│ wave ┆ eligible ┆ attended ┆ missed ┆ before_entry │
│ ---  ┆ ---      ┆ ---      ┆ ---    ┆ ---          │
│ i32  ┆ u32      ┆ u32      ┆ u32    ┆ u32          │
╞══════╪══════════╪══════════╪════════╪══════════════╡
│ 1    ┆ 300      ┆ 300      ┆ 0      ┆ 15           │
│ 2    ┆ 315      ┆ 273      ┆ 42     ┆ 0            │
│ 3    ┆ 315      ┆ 254      ┆ 61     ┆ 0            │
└──────┴──────────┴──────────┴────────┴──────────────┘
shape: (3, 5)
┌──────┬──────────┬──────────┬──────────┬───────────┐
│ wave ┆ attended ┆ with_dep ┆ with_anx ┆ with_both │
│ ---  ┆ ---      ┆ ---      ┆ ---      ┆ ---       │
│ i32  ┆ u32      ┆ u32      ┆ u32      ┆ u32       │
╞══════╪══════════╪══════════╪══════════╪═══════════╡
│ 1    ┆ 300      ┆ 276      ┆ 283      ┆ 262       │
│ 2    ┆ 273      ┆ 259      ┆ 258      ┆ 246       │
│ 3    ┆ 254      ┆ 237      ┆ 241      ┆ 225       │
└──────┴──────────┴──────────┴──────────┴───────────┘

The nine AMA sequences include 0062, while 234 people attended every wave. At wave 3, 254 people attended but only 237 had a depression total.

22.3 Auditing provided totals against their items

A total can be available without agreeing with its items. One visit has five anxiety items scored 0 and a supplied total of 1. To audit such totals, we first determine whether the items support a complete score and then compare that score with the supplied value.

The depression total sums six items and the anxiety total sums five. Each item is scored from 0 to 3. We calculate a total only for recorded visits where every item on that scale is present and in range. Missed visits and occasions before entry have no items to check.

At wave 3, participant 0001’s recorded depression items add up to 7. To decide whether 7 is a usable score, we need to know how many of the six items contributed.

In R, pivot_longer() turns the item columns into rows, and names_sep = "_" splits each item name, such as dep_3, into a scale part and an item part. between(value, 0, 3) %in% TRUE marks only observed in-range values as valid. For each person, wave, and scale, the valid-item count tells us whether the sum can serve as a total. scale_lengths gives the required counts, six for depression and five for anxiety.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
item_names <- c(paste0("dep_", 1:6), paste0("anx_", 1:5))
scale_lengths <- c(dep = 6L, anx = 5L)
item_values <- visits |>
  select(id, wave, all_of(item_names)) |>
  pivot_longer(
    all_of(item_names),
    names_to = c("scale", "item"),
    names_sep = "_",
    values_to = "value"
  ) |>
  mutate(valid = between(value, 0L, 3L) %in% TRUE)
scale_scores <- item_values |>
  summarise(
    n_valid = sum(valid),
    available_sum = sum(value[valid]),
    .by = c(id, wave, scale)
  ) |>
  mutate(
    n_items = unname(scale_lengths[scale]),
    recomputed = if_else(n_valid == n_items, available_sum, NA_integer_)
  )
c(item_rows = nrow(item_values), scale_rows = nrow(scale_scores))
filter(scale_scores, id == "0001", scale == "dep")
1
2
3
4
5
6
7
8
 item_rows scale_rows 
      9097       1654 
# A tibble: 3 × 7
  id     wave scale n_valid available_sum n_items recomputed
  <chr> <int> <chr>   <int>         <int>   <int>      <int>
1 0001      1 dep         6            13       6         13
2 0001      2 dep         6             5       6          5
3 0001      3 dep         5             7       6         NA

For 0001 at wave 3, five depression items sum to 7. The sixth is missing, so there is no complete depression score for that visit. Joining the supplied and recomputed totals by person, wave, and scale puts them side by side. A discrepancy means that only one total is available or that both are available and differ. If both are missing, same_value is NA and same_value %in% FALSE is false.

1
2
3
4
5
6
7
8
9
10
11
12
13
supplied <- visits |>
  select(id, wave, dep = dep_total, anx = anx_total) |>
  pivot_longer(c(dep, anx), names_to = "scale", values_to = "supplied")
total_audit <- scale_scores |>
  left_join(supplied, by = join_by(id, wave, scale), relationship = "one-to-one") |>
  mutate(
    supplied_available = !is.na(supplied),
    recomputed_available = !is.na(recomputed),
    same_value = supplied == recomputed,
    discrepancy = supplied_available != recomputed_available | same_value %in% FALSE
  )
count(total_audit, scale, supplied_available, recomputed_available, same_value)
count(total_audit, scale, discrepancy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# A tibble: 6 × 5
  scale supplied_available recomputed_available same_value     n
  <chr> <lgl>              <lgl>                <lgl>      <int>
1 anx   FALSE              FALSE                NA            45
2 anx   TRUE               TRUE                 FALSE          1
3 anx   TRUE               TRUE                 TRUE         781
4 dep   FALSE              FALSE                NA            55
5 dep   TRUE               TRUE                 FALSE          1
6 dep   TRUE               TRUE                 TRUE         771
# A tibble: 4 × 3
  scale discrepancy     n
  <chr> <lgl>       <int>
1 anx   FALSE         826
2 anx   TRUE            1
3 dep   FALSE         826
4 dep   TRUE            1

With ID and wave as the index, unpivot() gives each item response its own row for that visit. For each item name, str.split("_") separates the scale and item, and list.get() retrieves each part by position. A missing answer adds zero to the valid-item count because fill_null(False) marks it invalid. Only valid items enter the sum. For 0001, pl.when() returns that sum as a depression score only at visits where the count meets the requirement in scale_lengths.

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
item_names = [*[f"dep_{n}" for n in range(1, 7)], *[f"anx_{n}" for n in range(1, 6)]]
scale_lengths = {"dep": 6, "anx": 5}
item_values = (
    visits.select("id", "wave", *item_names)
    .unpivot(index=["id", "wave"], variable_name="name", value_name="value")
    .with_columns(
        scale=pl.col("name").str.split("_").list.get(0),
        item=pl.col("name").str.split("_").list.get(1),
        valid=pl.col("value").is_between(0, 3).fill_null(False),
    )
)
scale_scores = (
    item_values.group_by("id", "wave", "scale")
    .agg(
        n_valid=pl.col("valid").sum(),
        available_sum=pl.col("value").filter(pl.col("valid")).sum(),
    )
    .with_columns(
        n_items=pl.col("scale").replace_strict(scale_lengths, return_dtype=pl.UInt32)
    )
    .with_columns(
        recomputed=pl.when(pl.col("n_valid") == pl.col("n_items")).then(
            pl.col("available_sum")
        )
    )
)
{"item_rows": item_values.height, "scale_rows": scale_scores.height}
scale_scores.filter((pl.col("id") == "0001") & (pl.col("scale") == "dep")).sort("wave")
1
2
3
4
5
6
7
8
9
10
11
{'item_rows': 9097, 'scale_rows': 1654}
shape: (3, 7)
┌──────┬──────┬───────┬─────────┬───────────────┬─────────┬────────────┐
│ id   ┆ wave ┆ scale ┆ n_valid ┆ available_sum ┆ n_items ┆ recomputed │
│ ---  ┆ ---  ┆ ---   ┆ ---     ┆ ---           ┆ ---     ┆ ---        │
│ str  ┆ i32  ┆ str   ┆ u32     ┆ i64           ┆ u32     ┆ i64        │
╞══════╪══════╪═══════╪═════════╪═══════════════╪═════════╪════════════╡
│ 0001 ┆ 1    ┆ dep   ┆ 6       ┆ 13            ┆ 6       ┆ 13         │
│ 0001 ┆ 2    ┆ dep   ┆ 6       ┆ 5             ┆ 6       ┆ 5          │
│ 0001 ┆ 3    ┆ dep   ┆ 5       ┆ 7             ┆ 6       ┆ null       │
└──────┴──────┴───────┴─────────┴───────────────┴─────────┴────────────┘

At wave 3, 0001 has an available_sum of 7 from five depression items. The required count is six, so recomputed is null. After unpivot(), joining by person, wave, and scale puts the supplied total beside the recomputed one. A second with_columns() flags cases where only one total exists or the two observed totals differ. When both are null, eq(False).fill_null(False) gives false.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
supplied = visits.select("id", "wave", dep="dep_total", anx="anx_total").unpivot(
    index=["id", "wave"], variable_name="scale", value_name="supplied"
)
total_audit = (
    scale_scores.join(supplied, on=["id", "wave", "scale"], how="left", validate="1:1")
    .with_columns(
        supplied_available=pl.col("supplied").is_not_null(),
        recomputed_available=pl.col("recomputed").is_not_null(),
        same_value=pl.col("supplied") == pl.col("recomputed"),
    )
    .with_columns(
        discrepancy=(pl.col("supplied_available") != pl.col("recomputed_available"))
        | pl.col("same_value").eq(False).fill_null(False)
    )
)
total_audit.group_by(
    "scale", "supplied_available", "recomputed_available", "same_value"
).agg(n=pl.len()).sort("scale", "supplied_available", "same_value")
total_audit.filter(pl.col("discrepancy")).select(
    "id", "wave", "scale", "n_valid", "available_sum", "recomputed", "supplied",
    "discrepancy",
).sort("id")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
shape: (6, 5)
┌───────┬────────────────────┬──────────────────────┬────────────┬─────┐
│ scale ┆ supplied_available ┆ recomputed_available ┆ same_value ┆ n   │
│ ---   ┆ ---                ┆ ---                  ┆ ---        ┆ --- │
│ str   ┆ bool               ┆ bool                 ┆ bool       ┆ u32 │
╞═══════╪════════════════════╪══════════════════════╪════════════╪═════╡
│ anx   ┆ false              ┆ false                ┆ null       ┆ 45  │
│ anx   ┆ true               ┆ true                 ┆ false      ┆ 1   │
│ anx   ┆ true               ┆ true                 ┆ true       ┆ 781 │
│ dep   ┆ false              ┆ false                ┆ null       ┆ 55  │
│ dep   ┆ true               ┆ true                 ┆ false      ┆ 1   │
│ dep   ┆ true               ┆ true                 ┆ true       ┆ 771 │
└───────┴────────────────────┴──────────────────────┴────────────┴─────┘
shape: (2, 8)
┌──────┬──────┬───────┬─────────┬───────────────┬────────────┬──────────┬─────────────┐
│ id   ┆ wave ┆ scale ┆ n_valid ┆ available_sum ┆ recomputed ┆ supplied ┆ discrepancy │
│ ---  ┆ ---  ┆ ---   ┆ ---     ┆ ---           ┆ ---        ┆ ---      ┆ ---         │
│ str  ┆ i32  ┆ str   ┆ u32     ┆ i64           ┆ i64        ┆ i64      ┆ bool        │
╞══════╪══════╪═══════╪═════════╪═══════════════╪════════════╪══════════╪═════════════╡
│ 0059 ┆ 1    ┆ dep   ┆ 6       ┆ 3             ┆ 3          ┆ 5        ┆ true        │
│ 0169 ┆ 2    ┆ anx   ┆ 5       ┆ 0             ┆ 0          ┆ 1        ┆ true        │
└──────┴──────┴───────┴─────────┴───────────────┴────────────┴──────────┴─────────────┘

In these visits, a supplied total is present exactly when all items on that scale are valid. Two supplied totals differ from the item sums. The individual items for 0059 at wave 1 and 0169 at wave 2 show which total the recorded responses support.

1
2
3
4
5
item_values |>
  semi_join(filter(total_audit, discrepancy), by = join_by(id, wave, scale)) |>
  summarise(items = paste(value, collapse = " "), .by = c(id, wave, scale)) |>
  left_join(total_audit, by = join_by(id, wave, scale), relationship = "one-to-one") |>
  select(id, wave, scale, items, n_valid, recomputed, supplied)
1
2
3
4
5
# A tibble: 2 × 7
  id     wave scale items       n_valid recomputed supplied
  <chr> <int> <chr> <chr>         <int>      <int>    <int>
1 0059      1 dep   0 0 3 0 0 0       6          3        5
2 0169      2 anx   0 0 0 0 0         5          0        1
1
2
3
4
5
6
7
8
9
10
audit_keys = ["id", "wave", "scale"]
item_values.join(
    total_audit.filter(pl.col("discrepancy")).select(audit_keys),
    on=audit_keys,
    how="semi",
).sort("id", "item").group_by(audit_keys, maintain_order=True).agg(
    items=pl.col("value").cast(pl.String).str.join(" ")
).join(total_audit, on=audit_keys, how="left", validate="1:1").select(
    *audit_keys, "items", "n_valid", "recomputed", "supplied"
)
1
2
3
4
5
6
7
8
9
shape: (2, 7)
┌──────┬──────┬───────┬─────────────┬─────────┬────────────┬──────────┐
│ id   ┆ wave ┆ scale ┆ items       ┆ n_valid ┆ recomputed ┆ supplied │
│ ---  ┆ ---  ┆ ---   ┆ ---         ┆ ---     ┆ ---        ┆ ---      │
│ str  ┆ i32  ┆ str   ┆ str         ┆ u32     ┆ i64        ┆ i64      │
╞══════╪══════╪═══════╪═════════════╪═════════╪════════════╪══════════╡
│ 0059 ┆ 1    ┆ dep   ┆ 0 0 3 0 0 0 ┆ 6       ┆ 3          ┆ 5        │
│ 0169 ┆ 2    ┆ anx   ┆ 0 0 0 0 0   ┆ 5       ┆ 0          ┆ 1        │
└──────┴──────┴───────┴─────────────┴─────────┴────────────┴──────────┘

The six depression items for 0059 sum to 3, and the five anxiety items for 0169 sum to 0. These item sums are the scores used for analysis. The audit also records the supplied totals of 5 and 1 beside the discrepancy flags, allowing each correction to be traced to its recorded values.

Widening the audit places both scales on one visit row for the join to panel_grid. The summary checks the range of each scale and whether any depression score appears outside a recorded visit. The original dep_total and anx_total columns are not replaced by the recomputed scores.

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
working_totals <- total_audit |>
  select(id, wave, scale, n_valid, supplied, recomputed, discrepancy) |>
  pivot_wider(
    names_from = scale,
    values_from = c(n_valid, supplied, recomputed, discrepancy)
  )
panel_grid <- panel_grid |>
  left_join(
    select(
      working_totals, id, wave, recomputed_dep, recomputed_anx, discrepancy_dep,
      discrepancy_anx, n_valid_dep, n_valid_anx
    ),
    by = join_by(id, wave),
    relationship = "one-to-one"
  )
panel_grid |>
  filter(participation == "attended") |>
  summarise(
    rows = n(),
    dep_complete = sum(!is.na(recomputed_dep)),
    dep_min = min(recomputed_dep, na.rm = TRUE),
    dep_max = max(recomputed_dep, na.rm = TRUE),
    anx_complete = sum(!is.na(recomputed_anx)),
    anx_min = min(recomputed_anx, na.rm = TRUE),
    anx_max = max(recomputed_anx, na.rm = TRUE)
  )
c(
  grid_rows = nrow(panel_grid),
  recomputed_outside_visits = sum(
    !is.na(panel_grid$recomputed_dep) & panel_grid$participation != "attended"
  ),
  supplied_kept = sum(!is.na(panel_grid$dep_total))
)
1
2
3
4
5
6
# A tibble: 1 × 7
   rows dep_complete dep_min dep_max anx_complete anx_min anx_max
  <int>        <int>   <int>   <int>        <int>   <int>   <int>
1   827          772       0      18          782       0      15
                grid_rows recomputed_outside_visits             supplied_kept 
                      945                         0                       772 
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
working_totals = total_audit.sort("id", "wave", "scale").select(
    "id", "wave", "scale", "n_valid", "supplied", "recomputed", "discrepancy"
).pivot(
    on="scale",
    index=["id", "wave"],
    values=["n_valid", "supplied", "recomputed", "discrepancy"],
)
panel_grid = panel_grid.join(
    working_totals.select(
        "id", "wave", "recomputed_dep", "recomputed_anx", "discrepancy_dep",
        "discrepancy_anx", "n_valid_dep", "n_valid_anx",
    ),
    on=["id", "wave"],
    how="left",
    validate="1:1",
).sort("id", "wave")
panel_grid.filter(pl.col("participation") == "attended").select(
    rows=pl.len(),
    dep_complete=pl.col("recomputed_dep").count(),
    dep_min=pl.col("recomputed_dep").min(),
    dep_max=pl.col("recomputed_dep").max(),
    anx_complete=pl.col("recomputed_anx").count(),
    anx_min=pl.col("recomputed_anx").min(),
    anx_max=pl.col("recomputed_anx").max(),
)
{
    "grid_rows": panel_grid.height,
    "recomputed_outside_visits": panel_grid.filter(
        pl.col("recomputed_dep").is_not_null()
        & (pl.col("participation") != "attended")
    ).height,
    "supplied_kept": panel_grid["dep_total"].count(),
}
1
2
3
4
5
6
7
8
9
shape: (1, 7)
┌──────┬──────────────┬─────────┬─────────┬──────────────┬─────────┬─────────┐
│ rows ┆ dep_complete ┆ dep_min ┆ dep_max ┆ anx_complete ┆ anx_min ┆ anx_max │
│ ---  ┆ ---          ┆ ---     ┆ ---     ┆ ---          ┆ ---     ┆ ---     │
│ u32  ┆ u32          ┆ i64     ┆ i64     ┆ u32          ┆ i64     ┆ i64     │
╞══════╪══════════════╪═════════╪═════════╪══════════════╪═════════╪═════════╡
│ 827  ┆ 772          ┆ 0       ┆ 18      ┆ 782          ┆ 0       ┆ 15      │
└──────┴──────────────┴─────────┴─────────┴──────────────┴─────────┴─────────┘
{'grid_rows': 945, 'recomputed_outside_visits': 0, 'supplied_kept': 772}

The grid still has 945 rows. Among the 827 attended visits, 772 have complete depression scores and 782 have complete anxiety scores. Both scales span their full possible ranges, from 0 to 18 for depression and from 0 to 15 for anxiety. The two corrections change scores for visits that already had a total.

22.4 Describing change with an explicit comparison set

The mean depression score is higher at wave 2 than at wave 1. How large is the change if we compare only people with scores at both visits? For each person, we subtract the earlier score from the later one. The first two waves were planned six months apart. The recorded dates tell us how much time passed for each person.

In R, n() counts all 315 people on the grid at each wave. The eligibility and attendance counts refer to people due for a visit and people who attended. mean(recomputed_dep, na.rm = TRUE) averages only the observed depression scores, whose count is with_dep.

1
2
3
4
5
6
7
8
9
10
wave_summary <- panel_grid |>
  summarise(
    people = n(),
    eligible = sum(eligible),
    attended = sum(participation == "attended"),
    with_dep = sum(!is.na(recomputed_dep)),
    mean_dep = mean(recomputed_dep, na.rm = TRUE),
    .by = wave
  )
wave_summary
1
2
3
4
5
6
# A tibble: 3 × 6
   wave people eligible attended with_dep mean_dep
  <int>  <int>    <int>    <int>    <int>    <dbl>
1     1    315      300      300      276     6.63
2     2    315      315      273      259     6.76
3     3    315      315      254      237     7.01

The wave-1 depression mean uses 276 people and the wave-2 mean uses 259. To compare scores for the same people, pivot_wider() puts each person’s visits on one row. Its names_glue argument produces names such as dep_w1 and date_w1. The both group has the two scores needed to subtract the wave-1 score from the wave-2 score.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
dep_pairs <- panel_grid |>
  select(id, wave, date, dep = recomputed_dep) |>
  pivot_wider(
    names_from = wave,
    values_from = c(date, dep),
    names_glue = "{.value}_w{wave}"
  ) |>
  mutate(
    status_12 = case_when(
      !is.na(dep_w1) & !is.na(dep_w2) ~ "both",
      !is.na(dep_w1) ~ "wave 1 only",
      !is.na(dep_w2) ~ "wave 2 only",
      .default = "neither"
    ),
    change_12 = if_else(status_12 == "both", dep_w2 - dep_w1, NA_integer_)
  )
c(people = nrow(dep_pairs), distinct = n_distinct(dep_pairs$id))
count(dep_pairs, status_12)
1
2
3
4
5
6
7
8
9
  people distinct 
     315      315 
# A tibble: 4 × 2
  status_12       n
  <chr>       <int>
1 both          225
2 neither         5
3 wave 1 only    51
4 wave 2 only    34

For the 225 pairs, elapsed time depends on the actual visits. Subtracting the dates and applying as.integer() gives whole days. Each difference should be observed and positive if the second visit followed the first.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
dep_pairs <- dep_pairs |>
  mutate(
    days_12 = if_else(
      status_12 == "both",
      as.integer(date_w2 - date_w1),
      NA_integer_
    )
  )
dep_pairs |>
  filter(status_12 == "both") |>
  summarise(
    pairs = n(),
    missing_days = sum(is.na(days_12)),
    nonpositive = sum(days_12 <= 0),
    min_days = min(days_12),
    max_days = max(days_12)
  )
1
2
3
4
# A tibble: 1 × 5
  pairs missing_days nonpositive min_days max_days
  <int>        <int>       <int>    <int>    <int>
1   225            0           0      157      206

In Polars, pl.len() counts grid rows, count() counts nonnull working totals, and mean() averages those totals. Reporting those counts by wave beside eligibility and attendance shows how many visitors contributed to each mean.

1
2
3
4
5
6
7
8
9
10
11
12
wave_summary = (
    panel_grid.group_by("wave")
    .agg(
        people=pl.len(),
        eligible=pl.col("eligible").sum(),
        attended=(pl.col("participation") == "attended").sum(),
        with_dep=pl.col("recomputed_dep").count(),
        mean_dep=pl.col("recomputed_dep").mean(),
    )
    .sort("wave")
)
wave_summary
1
2
3
4
5
6
7
8
9
10
shape: (3, 6)
┌──────┬────────┬──────────┬──────────┬──────────┬──────────┐
│ wave ┆ people ┆ eligible ┆ attended ┆ with_dep ┆ mean_dep │
│ ---  ┆ ---    ┆ ---      ┆ ---      ┆ ---      ┆ ---      │
│ i32  ┆ u32    ┆ u32      ┆ u32      ┆ u32      ┆ f64      │
╞══════╪════════╪══════════╪══════════╪══════════╪══════════╡
│ 1    ┆ 315    ┆ 300      ┆ 300      ┆ 276      ┆ 6.634058 │
│ 2    ┆ 315    ┆ 315      ┆ 273      ┆ 259      ┆ 6.764479 │
│ 3    ┆ 315    ┆ 315      ┆ 254      ┆ 237      ┆ 7.012658 │
└──────┴────────┴──────────┴──────────┴──────────┴──────────┘

The wave-1 mean includes 276 scores and the wave-2 mean includes 259. Formatting the wave numbers as w1, w2, and w3 before pivot() gives each person columns such as dep_w1. When both_12 is true, change_12 is the wave-2 score minus the wave-1 score. Otherwise, change_12 is null.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
dep_pairs = (
    panel_grid.select(
        "id", "date", dep="recomputed_dep", wave=pl.format("w{}", pl.col("wave"))
    )
    .pivot(on="wave", index="id", values=["date", "dep"])
    .sort("id")
)
both_12 = pl.col("dep_w1").is_not_null() & pl.col("dep_w2").is_not_null()
dep_pairs = dep_pairs.with_columns(
    status_12=pl.when(both_12)
    .then(pl.lit("both"))
    .when(pl.col("dep_w1").is_not_null())
    .then(pl.lit("wave 1 only"))
    .when(pl.col("dep_w2").is_not_null())
    .then(pl.lit("wave 2 only"))
    .otherwise(pl.lit("neither")),
    change_12=pl.when(both_12).then(pl.col("dep_w2") - pl.col("dep_w1")),
)
{"people": dep_pairs.height, "distinct": dep_pairs["id"].n_unique()}
dep_pairs.group_by("status_12").agg(n=pl.len()).sort("status_12")
1
2
3
4
5
6
7
8
9
10
11
12
{'people': 315, 'distinct': 315}
shape: (4, 2)
┌─────────────┬─────┐
│ status_12   ┆ n   │
│ ---         ┆ --- │
│ str         ┆ u32 │
╞═════════════╪═════╡
│ both        ┆ 225 │
│ neither     ┆ 5   │
│ wave 1 only ┆ 51  │
│ wave 2 only ┆ 34  │
└─────────────┴─────┘

For the 225 people with both scores, dt.total_days() gives the time between visits in whole days. missing_days counts pairs with an unknown interval, and nonpositive counts pairs in which the second date is the same as or earlier than the first.

1
2
3
4
5
6
7
8
9
10
11
12
dep_pairs = dep_pairs.with_columns(
    days_12=pl.when(both_12).then(
        (pl.col("date_w2") - pl.col("date_w1")).dt.total_days()
    )
)
dep_pairs.filter(pl.col("status_12") == "both").select(
    pairs=pl.len(),
    missing_days=pl.col("days_12").null_count(),
    nonpositive=(pl.col("days_12") <= 0).sum(),
    min_days=pl.col("days_12").min(),
    max_days=pl.col("days_12").max(),
)
1
2
3
4
5
6
7
8
shape: (1, 5)
┌───────┬──────────────┬─────────────┬──────────┬──────────┐
│ pairs ┆ missing_days ┆ nonpositive ┆ min_days ┆ max_days │
│ ---   ┆ ---          ┆ ---         ┆ ---      ┆ ---      │
│ u32   ┆ u32          ┆ u32         ┆ i64      ┆ i64      │
╞═══════╪══════════════╪═════════════╪══════════╪══════════╡
│ 225   ┆ 0            ┆ 0           ┆ 157      ┆ 206      │
└───────┴──────────────┴─────────────┴──────────┴──────────┘

The intervals for the 225 people with both scores range from 157 to 206 days. The first result gives the two scores and the interval for 0001. The second averages the individual changes for all 225 people.

1
2
3
4
5
6
7
8
9
10
11
12
dep_pairs |>
  filter(id == "0001") |>
  select(id, date_w1, dep_w1, date_w2, dep_w2, days_12, change_12)
dep_pairs |>
  filter(status_12 == "both") |>
  summarise(
    pairs = n(),
    mean_w1 = mean(dep_w1),
    mean_w2 = mean(dep_w2),
    mean_change = mean(change_12),
    mean_days = mean(days_12)
  )
1
2
3
4
5
6
7
8
# A tibble: 1 × 7
  id    date_w1    dep_w1 date_w2    dep_w2 days_12 change_12
  <chr> <date>      <int> <date>      <int>   <int>     <int>
1 0001  2024-03-06     13 2024-09-25      5     203        -8
# A tibble: 1 × 5
  pairs mean_w1 mean_w2 mean_change mean_days
  <int>   <dbl>   <dbl>       <dbl>     <dbl>
1   225    6.50    6.56      0.0578      183.
1
2
3
4
5
6
7
8
9
10
dep_pairs.filter(pl.col("id") == "0001").select(
    "id", "date_w1", "dep_w1", "date_w2", "dep_w2", "days_12", "change_12"
)
dep_pairs.filter(pl.col("status_12") == "both").select(
    pairs=pl.len(),
    mean_w1=pl.col("dep_w1").mean(),
    mean_w2=pl.col("dep_w2").mean(),
    mean_change=pl.col("change_12").mean(),
    mean_days=pl.col("days_12").mean(),
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
shape: (1, 7)
┌──────┬────────────┬────────┬────────────┬────────┬─────────┬───────────┐
│ id   ┆ date_w1    ┆ dep_w1 ┆ date_w2    ┆ dep_w2 ┆ days_12 ┆ change_12 │
│ ---  ┆ ---        ┆ ---    ┆ ---        ┆ ---    ┆ ---     ┆ ---       │
│ str  ┆ date       ┆ i64    ┆ date       ┆ i64    ┆ i64     ┆ i64       │
╞══════╪════════════╪════════╪════════════╪════════╪═════════╪═══════════╡
│ 0001 ┆ 2024-03-06 ┆ 13     ┆ 2024-09-25 ┆ 5      ┆ 203     ┆ -8        │
└──────┴────────────┴────────┴────────────┴────────┴─────────┴───────────┘
shape: (1, 5)
┌───────┬──────────┬─────────┬─────────────┬────────────┐
│ pairs ┆ mean_w1  ┆ mean_w2 ┆ mean_change ┆ mean_days  │
│ ---   ┆ ---      ┆ ---     ┆ ---         ┆ ---        │
│ u32   ┆ f64      ┆ f64     ┆ f64         ┆ f64        │
╞═══════╪══════════╪═════════╪═════════════╪════════════╡
│ 225   ┆ 6.502222 ┆ 6.56    ┆ 0.057778    ┆ 182.622222 │
└───────┴──────────┴─────────┴─────────────┴────────────┘

Participant 0001’s depression score fell from 13 to 5 over 203 days. Across the 225 people with both scores, the mean increase was about 0.058 points.

The separate wave means use larger, different groups: wave 1 includes another 51 people without a wave-2 score, and wave 2 includes another 34 without a wave-1 score. Subtracting those wave means gives an increase of about 0.130 points. That difference describes the two groups’ observed scores, whereas 0.058 describes change among the same 225 people.

Waves 1 and 3

Does missing wave 2 exclude someone like 0062 from a comparison of waves 1 and 3? Only the scores at those two endpoints are needed to calculate change. Every recorded wave-2 visit in these files has a date, so we can also tell whether someone with no middle score missed the visit or attended without a complete depression score.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
dep_pairs <- dep_pairs |>
  mutate(
    pair_13 = !is.na(dep_w1) & !is.na(dep_w3),
    change_13 = if_else(pair_13, dep_w3 - dep_w1, NA_integer_),
    days_13 = if_else(pair_13, as.integer(date_w3 - date_w1), NA_integer_)
  )
dep_pairs |>
  filter(id == "0062") |>
  select(id, dep_w1, date_w2, dep_w2, dep_w3, days_13, change_13)
dep_pairs |>
  filter(pair_13) |>
  summarise(
    pairs = n(),
    without_wave_2 = sum(is.na(dep_w2)),
    absent_at_wave_2 = sum(is.na(date_w2)),
    min_days = min(days_13),
    max_days = max(days_13),
    mean_change = mean(change_13)
  )
1
2
3
4
5
6
7
8
# A tibble: 1 × 7
  id    dep_w1 date_w2 dep_w2 dep_w3 days_13 change_13
  <chr>  <int> <date>   <int>  <int>   <int>     <int>
1 0062       6 NA          NA      9     361         3
# A tibble: 1 × 6
  pairs without_wave_2 absent_at_wave_2 min_days max_days mean_change
  <int>          <int>            <int>    <int>    <int>       <dbl>
1   207             18                9      341      388       0.256

In Polars, both_13 selects the people whose wave-3 and wave-1 scores can be subtracted. For these people, null_count() on dep_w2 counts missing middle scores, and null_count() on date_w2 counts missed middle visits.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
both_13 = pl.col("dep_w1").is_not_null() & pl.col("dep_w3").is_not_null()
dep_pairs = dep_pairs.with_columns(
    pair_13=both_13,
    change_13=pl.when(both_13).then(pl.col("dep_w3") - pl.col("dep_w1")),
    days_13=pl.when(both_13).then(
        (pl.col("date_w3") - pl.col("date_w1")).dt.total_days()
    ),
)
dep_pairs.filter(pl.col("id") == "0062").select(
    "id", "dep_w1", "date_w2", "dep_w2", "dep_w3", "days_13", "change_13"
)
dep_pairs.filter(pl.col("pair_13")).select(
    pairs=pl.len(),
    without_wave_2=pl.col("dep_w2").null_count(),
    absent_at_wave_2=pl.col("date_w2").null_count(),
    min_days=pl.col("days_13").min(),
    max_days=pl.col("days_13").max(),
    mean_change=pl.col("change_13").mean(),
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
shape: (1, 7)
┌──────┬────────┬─────────┬────────┬────────┬─────────┬───────────┐
│ id   ┆ dep_w1 ┆ date_w2 ┆ dep_w2 ┆ dep_w3 ┆ days_13 ┆ change_13 │
│ ---  ┆ ---    ┆ ---     ┆ ---    ┆ ---    ┆ ---     ┆ ---       │
│ str  ┆ i64    ┆ date    ┆ i64    ┆ i64    ┆ i64     ┆ i64       │
╞══════╪════════╪═════════╪════════╪════════╪═════════╪═══════════╡
│ 0062 ┆ 6      ┆ null    ┆ null   ┆ 9      ┆ 361     ┆ 3         │
└──────┴────────┴─────────┴────────┴────────┴─────────┴───────────┘
shape: (1, 6)
┌───────┬────────────────┬──────────────────┬──────────┬──────────┬─────────────┐
│ pairs ┆ without_wave_2 ┆ absent_at_wave_2 ┆ min_days ┆ max_days ┆ mean_change │
│ ---   ┆ ---            ┆ ---              ┆ ---      ┆ ---      ┆ ---         │
│ u32   ┆ u32            ┆ u32              ┆ i64      ┆ i64      ┆ f64         │
╞═══════╪════════════════╪══════════════════╪══════════╪══════════╪═════════════╡
│ 207   ┆ 18             ┆ 9                ┆ 341      ┆ 388      ┆ 0.256039    │
└───────┴────────────────┴──────────────────┴──────────┴──────────┴─────────────┘

The depression score for 0062 rises from 6 to 9 over 361 days. Among the 207 people with scores at waves 1 and 3, the mean change is about 0.256 points over intervals of 341 to 388 days. Eighteen of those people had no wave-2 depression total. Nine missed the visit, as 0062 did, and nine attended without a complete score. For those 18, we know the net change but cannot tell how much occurred before or after wave 2.

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