Comparing a person’s first and last scores is convenient when the scores appear side by side, whereas examining one round of data collection requires a field that identifies the round. The same measurements therefore need different layouts for different questions. This chapter shows how to move measurements between rows and columns while preserving their association with people and occasions. We begin with information embedded in column names, then reshape the table in both directions and check that the values survive the transformation. Duplicate records and blank cells require further interpretation, so we also examine when a proposed output cell has several source records or no observed score.
12.1 When a column name contains data
A panel study follows people over several rounds of data collection, called waves. In a constructed example, p1 and p2 each have one row, with depression totals in dep_w1, dep_w2 and dep_w3. How can we filter rows by wave when w2 appears only in the column name dep_w2?
In the wide layout, each wave has its own score column. In dep_w3, dep means depression and w3 means wave 3. In the long layout, each row represents one person at one wave. The 7 in p1’s dep_w3 cell becomes the dep value on the row for p1 at w3.
tidyr::pivot_longer() moves the columns selected by cols = starts_with("dep_") into rows and repeats each participant’s id. After names_prefix = "dep_" removes the prefix, names_to = "wave" puts the remaining label in wave. With values_to = "dep", the score from that cell goes into dep.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| library(tidyverse)
depression_wide <- tibble(
id = c("p1", "p2"),
dep_w1 = c(2, 5),
dep_w2 = c(4, NA),
dep_w3 = c(7, 8)
)
depression_wide
depression_long <- pivot_longer(
depression_wide,
cols = starts_with("dep_"),
names_to = "wave",
names_prefix = "dep_",
values_to = "dep"
)
filter(depression_long, id == "p1")
|
1
2
3
4
5
6
7
8
9
10
11
| # A tibble: 2 × 4
id dep_w1 dep_w2 dep_w3
<chr> <dbl> <dbl> <dbl>
1 p1 2 4 7
2 p2 5 NA 8
# A tibble: 3 × 3
id wave dep
<chr> <chr> <dbl>
1 p1 w1 2
2 p1 w2 4
3 p1 w3 7
|
The three rows for p1 show scores of 2, 4 and 7 in wave order. Does the result also include a row for p2’s empty wave-2 cell?
1
| filter(depression_long, id == "p2")
|
1
2
3
4
5
6
| # A tibble: 3 × 3
id wave dep
<chr> <chr> <dbl>
1 p2 w1 5
2 p2 w2 NA
3 p2 w3 8
|
By default, pivot_longer() produces a row for p2 at w2 with NA in dep. Setting values_drop_na = TRUE would drop that row.
Polars unpivot() creates a row for each cell in the columns listed in on. With index="id", the participant ID repeats on each of that person’s rows. variable_name="column" puts the original column name in column, and value_name="dep" puts the score in dep. The parentheses in str.extract(r"^dep_(w\d)$") capture w and its digit, so dep_w3 in column gives w3 in wave.
1
2
3
4
5
6
7
8
9
10
11
12
13
| import polars as pl
depression_wide = pl.DataFrame(
{"id": ["p1", "p2"], "dep_w1": [2, 5], "dep_w2": [4, None], "dep_w3": [7, 8]}
)
depression_wide
depression_long = depression_wide.unpivot(
on=["dep_w1", "dep_w2", "dep_w3"],
index="id",
variable_name="column",
value_name="dep",
).with_columns(wave=pl.col("column").str.extract(r"^dep_(w\d)$"))
depression_long.columns
|
1
2
3
4
5
6
7
8
9
10
| shape: (2, 4)
┌─────┬────────┬────────┬────────┐
│ id ┆ dep_w1 ┆ dep_w2 ┆ dep_w3 │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 ┆ i64 │
╞═════╪════════╪════════╪════════╡
│ p1 ┆ 2 ┆ 4 ┆ 7 │
│ p2 ┆ 5 ┆ null ┆ 8 │
└─────┴────────┴────────┴────────┘
['id', 'column', 'dep', 'wave']
|
unpivot() does not guarantee row order. Sorting by id and wave puts the three rows for each person in wave order in the display.
1
| depression_long.sort("id", "wave")
|
1
2
3
4
5
6
7
8
9
10
11
12
13
| shape: (6, 4)
┌─────┬────────┬──────┬──────┐
│ id ┆ column ┆ dep ┆ wave │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ str │
╞═════╪════════╪══════╪══════╡
│ p1 ┆ dep_w1 ┆ 2 ┆ w1 │
│ p1 ┆ dep_w2 ┆ 4 ┆ w2 │
│ p1 ┆ dep_w3 ┆ 7 ┆ w3 │
│ p2 ┆ dep_w1 ┆ 5 ┆ w1 │
│ p2 ┆ dep_w2 ┆ null ┆ w2 │
│ p2 ┆ dep_w3 ┆ 8 ┆ w3 │
└─────┴────────┴──────┴──────┘
|
The row for p2 at wave 2 has dep_w2 in column and null in dep. For p1 at wave 3, dep_w3 identifies the source of 7.
One row per person and wave means the row count should equal the number of distinct (id, wave) keys. dplyr::n_distinct() counts people from id alone and pairs from id and wave together. In Polars, n_unique() counts people and unique().height on the two columns counts pairs.
1
2
| c(nrow(depression_wide), nrow(depression_long))
c(n_distinct(depression_long$id), n_distinct(depression_long$id, depression_long$wave))
|
1
2
| (depression_wide.height, depression_long.height)
(depression_long["id"].n_unique(), depression_long.select("id", "wave").unique().height)
|
The six rows still describe two people. Each (id, wave) pair occurs once, and only five of the rows contain a score. Filtering for w2 selects one row for each person, including the row with p2’s missing score. The wide layout puts each person’s first and last scores side by side.
12.2 Moving repeated measurements into rows
Extend the two-person example to include anxiety totals. Across the three waves, p1’s totals are 1, 2 and 3, and p2’s are 3, missing and 4. To compare depression with anxiety at each visit, the two scores must describe the same person and wave. At p1’s wave 2, that means pairing depression 4 with anxiety 2.
The practice file panel_wide.csv also records visit dates. For participant 0001 at wave 2, date_w2, dep_w2 and anx_w2 belong on one row alongside sex and birth_year. The file gives a depression total only when all six items were answered and an anxiety total only when all five were answered. A visit can therefore have a date even when a total is missing. The totals in the new table come directly from the file.
In tidyr::pivot_longer(), names_sep = "_" splits each repeated column name. With names_to = c(".value", "wave"), .value makes the first part the name of a score column. The second part gives the wave value. For dep_w2, the score goes in dep on the w2 row. cols = -id selects every column except the participant identifier.
1
2
3
4
5
6
7
8
9
10
11
12
| both_wide <- tibble(
id = c("p1", "p2"),
dep_w1 = c(2, 5), dep_w2 = c(4, NA), dep_w3 = c(7, 8),
anx_w1 = c(1, 3), anx_w2 = c(2, NA), anx_w3 = c(3, 4)
)
both_long <- pivot_longer(
both_wide,
cols = -id,
names_to = c(".value", "wave"),
names_sep = "_"
)
both_long
|
1
2
3
4
5
6
7
8
9
| # A tibble: 6 × 4
id wave dep anx
<chr> <chr> <dbl> <dbl>
1 p1 w1 2 1
2 p1 w2 4 2
3 p1 w3 7 3
4 p2 w1 5 3
5 p2 w2 NA NA
6 p2 w3 8 4
|
For p1 at w2, the row pairs the depression total of 4 with the anxiety total of 2. Both totals are missing for p2 at w2. Counting nonmissing values gives the number of scores for each measure.
1
| c(sum(!is.na(both_long$dep)), sum(!is.na(both_long$anx)))
|
Both columns have five observed scores. Swapping p1’s wave-1 and wave-2 anxiety scores would still give five in each column, but the wave-2 depression score of 4 would then be paired with 1 instead of 2.
In panel_wide.csv, nine columns begin with date_, dep_ or anx_. With col_character() as the default, readr::read_csv() reads 0001 as a four-character ID. pivot_longer() repeats each person’s sex and birth_year on the three wave rows. ymd() then parses the visit dates. The totals are still text.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| panel <- read_csv(
"data/practice/panel_wide.csv",
col_types = cols(.default = col_character()),
na = "", trim_ws = FALSE
)
panel_long <- pivot_longer(
panel,
cols = starts_with(c("date_", "dep_", "anx_")),
names_to = c(".value", "wave"),
names_sep = "_"
) |>
mutate(date = ymd(date))
filter(panel_long, id == "0001")
c(
nrow(panel_long),
n_distinct(panel_long$id, panel_long$wave),
n_distinct(panel_long$id)
)
|
1
2
3
4
5
6
7
| # A tibble: 3 × 7
id sex birth_year wave date dep anx
<chr> <chr> <chr> <chr> <date> <chr> <chr>
1 0001 2 1987 w1 2024-03-06 13 10
2 0001 2 1987 w2 2024-09-25 5 13
3 0001 2 1987 w3 2025-03-25 <NA> <NA>
[1] 945 945 315
|
At the wave-2 visit on September 25, 0001 has a depression total of 5 and an anxiety total of 13. The wave-3 row has a date but neither total. Across the panel, the checks find 945 rows, 945 distinct person-wave pairs and 315 people.
In Polars, select() builds a table for each wave. For wave_1, it selects id, labels each row w1 and names the two score columns dep and anx. The other two tables use the scores and label for their own wave.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| both_wide = pl.DataFrame(
{
"id": ["p1", "p2"],
"dep_w1": [2, 5], "dep_w2": [4, None], "dep_w3": [7, 8],
"anx_w1": [1, 3], "anx_w2": [2, None], "anx_w3": [3, 4],
}
)
wave_1 = both_wide.select(
"id", wave=pl.lit("w1"), dep=pl.col("dep_w1"), anx=pl.col("anx_w1")
)
wave_2 = both_wide.select(
"id", wave=pl.lit("w2"), dep=pl.col("dep_w2"), anx=pl.col("anx_w2")
)
wave_3 = both_wide.select(
"id", wave=pl.lit("w3"), dep=pl.col("dep_w3"), anx=pl.col("anx_w3")
)
wave_1.schema
(wave_1.schema == wave_2.schema, wave_2.schema == wave_3.schema)
|
1
2
| Schema({'id': String, 'wave': String, 'dep': Int64, 'anx': Int64})
(True, True)
|
pl.concat(..., how="vertical") can stack these rows because the column names, order and types match. Sorting by id and wave groups each person’s rows together for display.
1
2
| both_long = pl.concat([wave_1, wave_2, wave_3], how="vertical")
both_long.sort("id", "wave")
|
1
2
3
4
5
6
7
8
9
10
11
12
13
| shape: (6, 4)
┌─────┬──────┬──────┬──────┐
│ id ┆ wave ┆ dep ┆ anx │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ i64 │
╞═════╪══════╪══════╪══════╡
│ p1 ┆ w1 ┆ 2 ┆ 1 │
│ p1 ┆ w2 ┆ 4 ┆ 2 │
│ p1 ┆ w3 ┆ 7 ┆ 3 │
│ p2 ┆ w1 ┆ 5 ┆ 3 │
│ p2 ┆ w2 ┆ null ┆ null │
│ p2 ┆ w3 ┆ 8 ┆ 4 │
└─────┴──────┴──────┴──────┘
|
For p1 at w2, the table pairs depression 4 with anxiety 2. For p2 at w2, both totals are null.
In the practice panel, infer_schema=False tells pl.read_csv() to read all fields as text. panel_wave("w2"), for example, selects date_w2, dep_w2 and anx_w2 alongside each person’s ID, sex and birth_year. Only the visit date is parsed, with str.to_date().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| panel = pl.read_csv("data/practice/panel_wide.csv", infer_schema=False)
def panel_wave(wave):
return panel.select(
"id",
"sex",
"birth_year",
wave=pl.lit(wave),
date=pl.col("date_" + wave).str.to_date("%Y-%m-%d"),
dep=pl.col("dep_" + wave),
anx=pl.col("anx_" + wave),
)
panel_long = pl.concat(
[panel_wave("w1"), panel_wave("w2"), panel_wave("w3")], how="vertical"
)
panel_long.filter(pl.col("id") == "0001")
(
panel_long.height,
panel_long.select("id", "wave").unique().height,
panel_long["id"].n_unique(),
)
|
1
2
3
4
5
6
7
8
9
10
11
| shape: (3, 7)
┌──────┬─────┬────────────┬──────┬────────────┬──────┬──────┐
│ id ┆ sex ┆ birth_year ┆ wave ┆ date ┆ dep ┆ anx │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str ┆ date ┆ str ┆ str │
╞══════╪═════╪════════════╪══════╪════════════╪══════╪══════╡
│ 0001 ┆ 2 ┆ 1987 ┆ w1 ┆ 2024-03-06 ┆ 13 ┆ 10 │
│ 0001 ┆ 2 ┆ 1987 ┆ w2 ┆ 2024-09-25 ┆ 5 ┆ 13 │
│ 0001 ┆ 2 ┆ 1987 ┆ w3 ┆ 2025-03-25 ┆ null ┆ null │
└──────┴─────┴────────────┴──────┴────────────┴──────┴──────┘
(945, 945, 315)
|
For 0001, the wave-2 row gives the visit date as 2024-09-25 and the two totals as 5 for depression and 13 for anxiety. The wave-3 row has a date and no totals. Across the full panel, 945 rows represent 945 distinct person-wave pairs for 315 people.
The row and key counts cannot establish that every value reached the correct wave. Swapping the wave-2 and wave-3 scores would still give 945 distinct pairs. We therefore compare each wave’s values with its source columns.
The first comparison checks whether the IDs for each wave are in source order. With the IDs aligned, we can compare the dates and totals row by row. R’s paste0() builds names such as dep_w2, and identical() compares the columns. In Polars, equals() treats nulls in the same position as equal.
1
2
3
4
5
6
7
8
9
| for (w in c("w1", "w2", "w3")) {
rows <- filter(panel_long, wave == w)
print(c(
id = identical(rows$id, panel$id),
date = identical(rows$date, ymd(panel[[paste0("date_", w)]])),
dep = identical(rows$dep, panel[[paste0("dep_", w)]]),
anx = identical(rows$anx, panel[[paste0("anx_", w)]])
))
}
|
1
2
3
4
5
6
| id date dep anx
TRUE TRUE TRUE TRUE
id date dep anx
TRUE TRUE TRUE TRUE
id date dep anx
TRUE TRUE TRUE TRUE
|
1
2
3
4
5
6
7
8
| for w in ["w1", "w2", "w3"]:
rows = panel_long.filter(pl.col("wave") == w)
print(
rows["id"].equals(panel["id"]),
rows["date"].equals(panel["date_" + w].str.to_date("%Y-%m-%d")),
rows["dep"].equals(panel["dep_" + w]),
rows["anx"].equals(panel["anx_" + w]),
)
|
1
2
3
| True True True True
True True True True
True True True True
|
All twelve comparisons are true in each language. IDs are in source order, and every date and total matches its own wave’s source column, including missing positions.
In this practice panel, a recorded visit has a date even when both totals are missing. A wave without a visit has a blank date and blank totals. Counting dated rows gives the number of recorded visits at each wave.
1
| count(panel_long, wave, dated = !is.na(date))
|
1
2
3
4
5
6
7
8
9
| # A tibble: 6 × 3
wave dated n
<chr> <lgl> <int>
1 w1 FALSE 15
2 w1 TRUE 300
3 w2 FALSE 42
4 w2 TRUE 273
5 w3 FALSE 61
6 w3 TRUE 254
|
1
2
3
4
5
| (
panel_long.group_by("wave", dated=pl.col("date").is_not_null())
.agg(n=pl.len())
.sort("wave", "dated")
)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
| shape: (6, 3)
┌──────┬───────┬─────┐
│ wave ┆ dated ┆ n │
│ --- ┆ --- ┆ --- │
│ str ┆ bool ┆ u32 │
╞══════╪═══════╪═════╡
│ w1 ┆ false ┆ 15 │
│ w1 ┆ true ┆ 300 │
│ w2 ┆ false ┆ 42 │
│ w2 ┆ true ┆ 273 │
│ w3 ┆ false ┆ 61 │
│ w3 ┆ true ┆ 254 │
└──────┴───────┴─────┘
|
The three waves have 300, 273 and 254 dated rows, for a total of 827 recorded visits. The other 118 rows in the 945-row table have no visit date. The row count therefore describes combinations of person and wave; the date count describes recorded visits.
12.3 Moving values into columns without hiding duplicates
Return to depression_long, the two-person example from Section 12.1. Widening it puts each person’s wave-1 and wave-3 depression totals side by side. There is currently one row for each (id, wave) pair, so each output score cell has one source row.
If the table lists both p1’s original wave-2 score and a correction, two records point to the same cell. Which value belongs there?
In tidyr::pivot_wider(), names_from = wave takes the new column names from the wave labels and values_from = dep fills them with depression scores. The only other column, id, identifies the output rows. With names_prefix = "dep_", wave w3 becomes column dep_w3. identical() compares the result with the original wide table.
1
2
3
4
5
6
7
8
9
| depression_paired <- pivot_wider(
depression_long,
names_from = wave,
values_from = dep,
names_prefix = "dep_"
)
depression_paired
filter(depression_long, id == "p1", wave == "w3")
identical(depression_paired, depression_wide)
|
1
2
3
4
5
6
7
8
9
10
| # A tibble: 2 × 4
id dep_w1 dep_w2 dep_w3
<chr> <dbl> <dbl> <dbl>
1 p1 2 4 7
2 p2 5 NA 8
# A tibble: 1 × 3
id wave dep
<chr> <chr> <dbl>
1 p1 w3 7
[1] TRUE
|
p1’s dep_w3 cell contains 7 from its only wave-3 row. TRUE confirms that the complete result matches the original wide table, including the blank dep_w2 cell for p2.
In Polars, pivot() uses index="id" for the rows, on="wave" for the column names and values="dep" for the scores. The wave label w3 becomes the column name directly.
1
2
3
| depression_paired = depression_long.pivot(on="wave", index="id", values="dep")
depression_paired
depression_long.filter((pl.col("id") == "p1") & (pl.col("wave") == "w3"))
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| shape: (2, 4)
┌─────┬─────┬──────┬─────┐
│ id ┆ w1 ┆ w2 ┆ w3 │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪══════╪═════╡
│ p1 ┆ 2 ┆ 4 ┆ 7 │
│ p2 ┆ 5 ┆ null ┆ 8 │
└─────┴─────┴──────┴─────┘
shape: (1, 4)
┌─────┬────────┬─────┬──────┐
│ id ┆ column ┆ dep ┆ wave │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ str │
╞═════╪════════╪═════╪══════╡
│ p1 ┆ dep_w3 ┆ 7 ┆ w3 │
└─────┴────────┴─────┴──────┘
|
The 7 in p1’s w3 cell comes from the displayed row for p1 at w3. The w2 cell for p2 is null because that person’s wave-2 row had no score.
Two revisions of one cell
A constructed revision history lists 4 as p1’s original wave-2 total and 5 as its correction. Both belong to the same person and wave. In tidyr::pivot_wider(), id_cols = id makes id the only row identifier. In Polars, index="id" does the same. Both revisions map to the w2 cell for p1.
1
2
3
4
5
6
7
8
| revisions <- tibble(
id = c("p1", "p1", "p1"),
wave = c("w1", "w2", "w2"),
revision = c(1L, 1L, 2L),
dep = c(2, 4, 5),
note = c("original", "original", "corrects revision 1")
)
pivot_wider(revisions, id_cols = id, names_from = wave, values_from = dep)
|
1
2
3
4
5
6
7
8
9
10
11
12
| # A tibble: 1 × 3
id w1 w2
<chr> <list> <list>
1 p1 <dbl [1]> <dbl [2]>
Warning message:
Values from `dep` are not uniquely identified; output will contain list-cols.
• Use `values_fn = list` to suppress this warning.
• Use `values_fn = {summary_fun}` to summarise duplicates.
• Use the following dplyr code to identify duplicates.
{data} |>
dplyr::summarise(n = dplyr::n(), .by = c(id, wave)) |>
dplyr::filter(n > 1L)
|
1
2
3
4
5
6
7
8
9
| revisions = pl.DataFrame(
{
"id": ["p1", "p1", "p1"],
"wave": ["w1", "w2", "w2"],
"revision": [1, 1, 2],
"dep": [2, 4, 5],
"note": ["original", "original", "corrects revision 1"],
}
)
|
1
2
| # Deliberate error: two values for one cell and no stated resolution
revisions.pivot(on="wave", index="id", values="dep")
|
1
| polars.exceptions.ComputeError: aggregation 'item' expected no or a single value, got 2 values
|
pivot_wider() issues a warning and creates list columns. In w2, <dbl [2]> means the cell contains two numbers. Polars reports an error because it found two values for one cell.
The correction note says that 5 replaces 4. Averaging them would give 4.5, a score neither record reports. Resolving the duplicate therefore requires selecting the correction before widening.
In R, filter(revision == max(revision)) selects the latest revision within each (id, wave) group. The result goes into accepted. A count by id and wave checks whether any cell still has more than one accepted row.
1
2
3
4
5
6
7
| accepted <- revisions |>
group_by(id, wave) |>
filter(revision == max(revision)) |>
ungroup()
filter(revisions, wave == "w2")
max(count(accepted, id, wave)$n)
pivot_wider(accepted, id_cols = id, names_from = wave, values_from = dep)
|
1
2
3
4
5
6
7
8
9
10
| # A tibble: 2 × 5
id wave revision dep note
<chr> <chr> <int> <dbl> <chr>
1 p1 w2 1 4 original
2 p1 w2 2 5 corrects revision 1
[1] 1
# A tibble: 1 × 3
id w1 w2
<chr> <dbl> <dbl>
1 p1 2 5
|
The wave-2 history in revisions shows both 4 and 5. The largest count in accepted is 1, so each accepted row has a cell of its own. The wide table shows 2 at wave 1 and the corrected 5 at wave 2.
In Polars, max().over("id", "wave") finds the highest revision number for each person and wave. The filter selects those rows for accepted. Counting rows per pair checks whether any pair still has two records with the same highest revision number.
1
2
3
4
5
6
| accepted = revisions.filter(
pl.col("revision") == pl.col("revision").max().over("id", "wave")
)
revisions.filter(pl.col("wave") == "w2")
accepted.group_by("id", "wave").agg(n=pl.len())["n"].max()
accepted.pivot(on="wave", index="id", values="dep")
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| shape: (2, 5)
┌─────┬──────┬──────────┬─────┬─────────────────────┐
│ id ┆ wave ┆ revision ┆ dep ┆ note │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ i64 ┆ str │
╞═════╪══════╪══════════╪═════╪═════════════════════╡
│ p1 ┆ w2 ┆ 1 ┆ 4 ┆ original │
│ p1 ┆ w2 ┆ 2 ┆ 5 ┆ corrects revision 1 │
└─────┴──────┴──────────┴─────┴─────────────────────┘
1
shape: (1, 3)
┌─────┬─────┬─────┐
│ id ┆ w1 ┆ w2 │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ p1 ┆ 2 ┆ 5 │
└─────┴─────┴─────┘
|
The maximum count is 1. The wide table shows 2 at wave 1 and 5 at wave 2. The original wave-2 score of 4 is still visible in revisions beside its correction.
Round trips
Resolving the revisions gives one accepted score per person and wave. A separate question is whether reshaping preserves rows whose scores are missing. Can a round trip from long to wide and back recover p2’s wave-2 row even though it had no score?
Both versions below return to depression_paired, the wide table for p1 and p2 from the start of this section. By default, the missing cell produces a row. The lossy version drops that row with values_drop_na = TRUE in tidyr::pivot_longer() or drop_nulls("dep") after the Polars unpivot().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| back <- pivot_longer(
depression_paired,
cols = -id,
names_to = "wave",
names_prefix = "dep_",
values_to = "dep"
)
lossy <- pivot_longer(
depression_paired,
cols = -id,
names_to = "wave",
names_prefix = "dep_",
values_to = "dep",
values_drop_na = TRUE
)
c(identical(back, depression_long), identical(lossy, depression_long))
c(nrow(back), nrow(lossy))
identical(lossy, filter(depression_long, !is.na(dep)))
|
1
2
3
| [1] TRUE FALSE
[1] 6 5
[1] TRUE
|
1
2
3
4
5
6
7
8
9
10
11
| back = depression_paired.unpivot(
on=["w1", "w2", "w3"], index="id", variable_name="wave", value_name="dep"
)
lossy = back.drop_nulls("dep")
original = depression_long.select("id", "wave", "dep")
(
back.sort("id", "wave").equals(original.sort("id", "wave")),
lossy.sort("id", "wave").equals(original.sort("id", "wave")),
)
(back.height, lossy.height)
lossy.sort("id", "wave").equals(original.drop_nulls("dep").sort("id", "wave"))
|
1
2
3
| (True, False)
(6, 5)
True
|
The default round trip restores all six person-wave pairs. R compares the entire result with depression_long. Polars compares id, wave and dep after sorting, omitting column, which contains the original names such as dep_w2. The last comparison is true for lossy because it tests only the five rows with scores. The row for p2 at wave 2 is gone. Equality on observed scores therefore does not establish that the table represents the same person-wave combinations.
12.4 Missing combinations and the meaning of a blank
In the long panel, each of the 315 people has a row for every wave, but only 827 of the 945 rows have a visit date. Moving the waves into rows gives every combination of person and wave a row, whether or not a visit took place. A blank depression cell in such a row can mean that the person had not yet enrolled, that the person missed a visit that was due or that the person attended and no score was recorded.
The constructed panel shows the three cases with two people. In it, p2 enrolled at wave 1 and missed the wave-2 visit. A new participant, p3, enrolled at wave 2 and attended that wave, but no depression score was recorded. Two people and three waves give six rows, so p3 also has a row for wave 1, an occasion before enrollment. Counting each blank as a missed visit would mark p3 absent at wave 1, before enrollment, and at wave 2, which p3 attended.
Telling the cases apart requires three separate questions, each represented by a field. eligible indicates whether the person had enrolled by that wave and follows from the entry wave. record_present indicates whether a visit took place, and the example gives it separately for each person and wave. score_observed indicates whether the dep cell has a value. It is the only one of the three fields that the reshaped table can provide by itself.
In R, wave >= entry_wave identifies eligible waves and !is.na(dep) identifies observed scores. For the three selected rows, case_when() first tests eligibility, then whether a visit record exists. For a recorded visit, a blank dep gives the status record, score missing.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| schedule <- tibble(
id = c("p2", "p2", "p2", "p3", "p3", "p3"),
wave = c(1L, 2L, 3L, 1L, 2L, 3L),
entry_wave = c(1L, 1L, 1L, 2L, 2L, 2L),
record_present = c(TRUE, FALSE, TRUE, FALSE, TRUE, TRUE),
dep = c(5, NA, 8, NA, NA, 8)
) |>
mutate(eligible = wave >= entry_wave, score_observed = !is.na(dep))
schedule
focal <- schedule |>
filter((id == "p2" & wave == 2L) | (id == "p3" & wave %in% c(1L, 2L))) |>
mutate(
status = case_when(
!eligible ~ "not eligible",
!record_present ~ "eligible, no record",
!score_observed ~ "record, score missing",
.default = "record, score observed"
)
)
select(focal, id, wave, eligible, record_present, score_observed, status)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| # A tibble: 6 × 7
id wave entry_wave record_present dep eligible score_observed
<chr> <int> <int> <lgl> <dbl> <lgl> <lgl>
1 p2 1 1 TRUE 5 TRUE TRUE
2 p2 2 1 FALSE NA TRUE FALSE
3 p2 3 1 TRUE 8 TRUE TRUE
4 p3 1 2 FALSE NA FALSE FALSE
5 p3 2 2 TRUE NA TRUE FALSE
6 p3 3 2 TRUE 8 TRUE TRUE
# A tibble: 3 × 6
id wave eligible record_present score_observed status
<chr> <int> <lgl> <lgl> <lgl> <chr>
1 p2 2 TRUE FALSE FALSE eligible, no record
2 p3 1 FALSE FALSE FALSE not eligible
3 p3 2 TRUE TRUE FALSE record, score missing
|
In Polars, wave >= entry_wave identifies eligible waves and is_not_null() identifies observed depression scores. For the three example rows, pl.when() checks eligibility first. A missing visit record counts as a missed visit only if the person was eligible. For those with a visit record, the score shows whether a depression measurement was available.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
| schedule = pl.DataFrame(
{
"id": ["p2", "p2", "p2", "p3", "p3", "p3"],
"wave": [1, 2, 3, 1, 2, 3],
"entry_wave": [1, 1, 1, 2, 2, 2],
"record_present": [True, False, True, False, True, True],
"dep": [5, None, 8, None, None, 8],
}
).with_columns(
eligible=pl.col("wave") >= pl.col("entry_wave"),
score_observed=pl.col("dep").is_not_null(),
)
schedule.height
focal = schedule.filter(
((pl.col("id") == "p2") & (pl.col("wave") == 2))
| ((pl.col("id") == "p3") & pl.col("wave").is_in([1, 2]))
).with_columns(
status=pl.when(~pl.col("eligible"))
.then(pl.lit("not eligible"))
.when(~pl.col("record_present"))
.then(pl.lit("eligible, no record"))
.when(~pl.col("score_observed"))
.then(pl.lit("record, score missing"))
.otherwise(pl.lit("record, score observed"))
)
focal.select("id", "wave", "eligible", "record_present", "score_observed", "status")
|
1
2
3
4
5
6
7
8
9
10
11
| 6
shape: (3, 6)
┌─────┬──────┬──────────┬────────────────┬────────────────┬───────────────────────┐
│ id ┆ wave ┆ eligible ┆ record_present ┆ score_observed ┆ status │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ bool ┆ bool ┆ bool ┆ str │
╞═════╪══════╪══════════╪════════════════╪════════════════╪═══════════════════════╡
│ p2 ┆ 2 ┆ true ┆ false ┆ false ┆ eligible, no record │
│ p3 ┆ 1 ┆ false ┆ false ┆ false ┆ not eligible │
│ p3 ┆ 2 ┆ true ┆ true ┆ false ┆ record, score missing │
└─────┴──────┴──────────┴────────────────┴────────────────┴───────────────────────┘
|
Of the three rows with missing scores, only p2’s wave-2 row represents a missed visit. For p3, the wave-1 blank predates enrollment, and the wave-2 blank is a missing score at a recorded visit.
In the practice panel, participants from 0001 to 0300 entered at wave 1 and those from 0301 to 0315 at wave 2. Each was eligible from entry onward. A visit date records attendance even when both totals are missing. The rows for 0001 at wave 3, 0002 at wave 2 and 0301 at wave 1 all lack a depression total.
1
2
3
4
5
6
7
| panel_long |>
filter(
(id == "0001" & wave == "w3") |
(id == "0002" & wave == "w2") |
(id == "0301" & wave == "w1")
) |>
select(id, wave, date, dep, anx)
|
1
2
3
4
5
6
| # A tibble: 3 × 5
id wave date dep anx
<chr> <chr> <date> <chr> <chr>
1 0001 w3 2025-03-25 <NA> <NA>
2 0002 w2 NA <NA> <NA>
3 0301 w1 NA <NA> <NA>
|
1
2
3
4
5
6
7
8
9
| (
panel_long.filter(
((pl.col("id") == "0001") & (pl.col("wave") == "w3"))
| ((pl.col("id") == "0002") & (pl.col("wave") == "w2"))
| ((pl.col("id") == "0301") & (pl.col("wave") == "w1"))
)
.select("id", "wave", "date", "dep", "anx")
.sort("id")
)
|
1
2
3
4
5
6
7
8
9
10
| shape: (3, 5)
┌──────┬──────┬────────────┬──────┬──────┐
│ id ┆ wave ┆ date ┆ dep ┆ anx │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ date ┆ str ┆ str │
╞══════╪══════╪════════════╪══════╪══════╡
│ 0001 ┆ w3 ┆ 2025-03-25 ┆ null ┆ null │
│ 0002 ┆ w2 ┆ null ┆ null ┆ null │
│ 0301 ┆ w1 ┆ null ┆ null ┆ null │
└──────┴──────┴────────────┴──────┴──────┘
|
The date 2025-03-25 records a wave-3 visit for 0001 despite the two missing totals. The other two rows have neither a date nor a total. 0002 was already enrolled at wave 2 and missed that visit. Wave 1 was before 0301 enrolled, so there was no visit to miss.
The same reasoning sorts the 118 undated rows in the long panel. The 15 participants who entered at wave 2 each have an undated wave-1 row from before enrollment. The other 103 undated rows belong to people who were enrolled at that wave, so they are missed visits.