Post

Reading Heterogeneous Source Files

The same survey can arrive as a workbook containing question text above the responses or as a statistical file containing numeric codes and their labels. Reading either file into a table does not, by itself, establish which rows are observations or what the values mean. We need to interpret each source’s conventions before comparing or combining its records. In this chapter, we work through spreadsheets, labeled data, and a text report, then assemble trial exports whose formats changed. We identify the data within each source, record the outcome of each import, and compare the resulting values at the precision the sources actually provide.

16.1 Spreadsheet sheets, headers, and cell types

The survey workbook, data/raw/survey/survey_raw.xlsx, contains both questions and answers. On a worksheet, a column letter and a row number locate a cell. Which of the first three rows contains the first submission? Inspecting those rows will establish where the response table begins.

In R, readxl comes with tidyverse and is loaded separately. excel_sheets() lists the sheets, and read_excel() with range = "A1:D3" reads the first four columns of those rows. For Python, install openpyxl in .venv through Packages: Install Package. load_workbook() opens the file, and iter_rows(values_only=True) returns the cell values one row at a time.

1
2
3
4
5
6
7
8
9
10
11
library(tidyverse)
library(readxl)
survey_path <- "data/raw/survey/survey_raw.xlsx"
excel_sheets(survey_path)
read_excel(
  survey_path,
  sheet = "Responses",
  range = "A1:D3",
  col_names = c("A", "B", "C", "D"),
  col_types = "text"
)
1
2
3
4
5
6
7
[1] "Responses"
# A tibble: 3 × 4
  A              B                   C                   D             
  <chr>          <chr>               <chr>               <chr>         
1 ResponseId     Start Date          End Date            ID            
2 Response ID    Response start time Response end time   Participant ID
3 R_Z4kK41wEM10D 2024-04-01 08:43:31 2024-04-01 08:53:09 429           
1
2
3
4
5
6
7
8
9
import polars as pl
import openpyxl

survey_path = "data/raw/survey/survey_raw.xlsx"
workbook = openpyxl.load_workbook(survey_path)
workbook.sheetnames
sheet = workbook["Responses"]
for row in sheet.iter_rows(max_row=3, max_col=4, values_only=True):
    print(row)
1
2
3
4
['Responses']
('ResponseId', 'Start Date', 'End Date', 'ID')
('Response ID', 'Response start time', 'Response end time', 'Participant ID')
('R_Z4kK41wEM10D', '2024-04-01 08:43:31', '2024-04-01 08:53:09', 429)

Row 1 names the variables. Row 2 describes each field, including the participant ID. The first submission is on row 3. A separate table for the descriptions lets us look up the wording of a question without counting it as an answer.

readxl::read_excel() can read the names, question descriptions, and responses separately. With n_max = 0, it reads no data rows, so names() gives the names from row 1. Passing those names back as col_names means the next read needs no header row. With skip = 1, n_max = 1, only the row of descriptions is read, and pivot_longer() places them in question_text. For the responses, skip = 2 starts at row 3.

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
survey_names <- names(read_excel(survey_path, sheet = "Responses", n_max = 0))
questions <- read_excel(
  survey_path,
  sheet = "Responses",
  col_names = survey_names,
  skip = 1,
  n_max = 1,
  col_types = "text"
)
question_text <- pivot_longer(
  questions,
  everything(),
  names_to = "variable",
  values_to = "question"
)
survey <- read_excel(
  survey_path,
  sheet = "Responses",
  col_names = survey_names,
  skip = 2
)
dim(survey)
filter(question_text, variable %in% c("ResponseId", "ID", "SAT_1"))
survey |>
  select(ResponseId, ID, SAT_1) |>
  head(1)
1
2
3
4
5
6
7
8
9
10
11
[1] 503  32
# A tibble: 3 × 2
  variable   question                                     
  <chr>      <chr>                                        
1 ResponseId Response ID                                  
2 ID         Participant ID                               
3 SAT_1      I am mostly satisfied with my life right now.
# A tibble: 1 × 3
  ResponseId        ID SAT_1            
  <chr>          <dbl> <chr>            
1 R_Z4kK41wEM10D   429 Strongly disagree

The result has 503 response rows and 32 variables. The first submission records Strongly disagree for SAT_1. In question_text, that item reads “I am mostly satisfied with my life right now.”

ID arrived as a double because its cells store numbers. This survey’s participant identifiers use four-digit text, including leading zeros. sprintf() with "%04d" writes a whole number with at least four digits, padding on the left with zeros. For the response recorded under 7, id_text shows the formatted identifier beside the number in ID.

1
2
3
4
5
range(survey$ID)
survey <- mutate(survey, id_text = sprintf("%04d", ID), .after = ID)
survey |>
  filter(ID == 7) |>
  select(ResponseId, ID, id_text)
1
2
3
4
5
[1]   1 520
# A tibble: 1 × 3
  ResponseId        ID id_text
  <chr>          <dbl> <chr>  
1 R_D7sLfnz61bpc     7 0007   

The stored 7 becomes 0007 under the four-digit convention, while ID still has the original value. All observed identifiers fit within four digits.

list(sheet.iter_rows(values_only=True)) returns the worksheet rows as tuples. The first tuple contains the variable names, the second contains the descriptions, and each subsequent tuple represents a submission. pl.DataFrame(..., orient="row", schema=names) uses the names for the response columns. infer_schema_length=None considers all records when choosing their types.

1
2
3
4
5
6
7
rows = list(sheet.iter_rows(values_only=True))
names, descriptions, records = rows[0], rows[1], rows[2:]
question_text = pl.DataFrame({"variable": names, "question": descriptions})
survey = pl.DataFrame(records, schema=names, orient="row", infer_schema_length=None)
(len(rows), survey.shape)
question_text.filter(pl.col("variable").is_in(["ResponseId", "ID", "SAT_1"]))
survey.select("ResponseId", "ID", "SAT_1").head(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
(505, (503, 32))
shape: (3, 2)
┌────────────┬─────────────────────────────────┐
│ variable   ┆ question                        │
│ ---        ┆ ---                             │
│ str        ┆ str                             │
╞════════════╪═════════════════════════════════╡
│ ResponseId ┆ Response ID                     │
│ ID         ┆ Participant ID                  │
│ SAT_1      ┆ I am mostly satisfied with my … │
└────────────┴─────────────────────────────────┘
shape: (1, 3)
┌────────────────┬─────┬───────────────────┐
│ ResponseId     ┆ ID  ┆ SAT_1             │
│ ---            ┆ --- ┆ ---               │
│ str            ┆ i64 ┆ str               │
╞════════════════╪═════╪═══════════════════╡
│ R_Z4kK41wEM10D ┆ 429 ┆ Strongly disagree │
└────────────────┴─────┴───────────────────┘

Of the 505 worksheet rows, 503 are submissions. The first submission records Strongly disagree for SAT_1, whose wording is in question_text.

openpyxl reads the numeric ID cells as integers, so the Polars column has type i64. This survey uses four-digit participant IDs. After cast(pl.String), str.zfill(4) adds leading zeros where needed. The new column id_text records the formatted identifier beside the original integer.

1
2
3
(survey["ID"].min(), survey["ID"].max())
survey = survey.with_columns(id_text=pl.col("ID").cast(pl.String).str.zfill(4))
survey.filter(pl.col("ID") == 7).select("ResponseId", "ID", "id_text")
1
2
3
4
5
6
7
8
9
(1, 520)
shape: (1, 3)
┌────────────────┬─────┬─────────┐
│ ResponseId     ┆ ID  ┆ id_text │
│ ---            ┆ --- ┆ ---     │
│ str            ┆ i64 ┆ str     │
╞════════════════╪═════╪═════════╡
│ R_D7sLfnz61bpc ┆ 7   ┆ 0007    │
└────────────────┴─────┴─────────┘

The recorded identifiers range from 1 to 520, so all fit within four digits. For R_D7sLfnz61bpc, the new text is 0007 beside the recorded integer 7.

Does the workbook import agree with the practice file? The practice file records ID as four-digit text. Matching on ResponseId lets you compare participant IDs for the same submission. The other counts distinguish submissions, question descriptions, and participants who may have submitted more than once.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
practice <- read_csv(
  "data/practice/survey.csv",
  col_types = cols(.default = col_character()),
  na = "",
  trim_ws = FALSE
)
id_check <- inner_join(
  select(survey, ResponseId, id_text),
  select(practice, ResponseId, ID),
  by = join_by(ResponseId),
  relationship = "one-to-one"
)
c(
  responses = nrow(survey),
  questions = nrow(question_text),
  ids = n_distinct(survey$id_text),
  matched = nrow(id_check),
  same_id = sum(id_check$id_text == id_check$ID)
)
1
2
responses questions       ids   matched   same_id 
      503        32       500       503       503 
1
2
3
4
5
6
7
8
9
10
11
practice = pl.read_csv("data/practice/survey.csv", infer_schema=False)
id_check = survey.select("ResponseId", "id_text").join(
    practice.select("ResponseId", "ID"), on="ResponseId", validate="1:1"
)
(
    survey.height,
    question_text.height,
    survey["id_text"].n_unique(),
    id_check.height,
    (id_check["id_text"] == id_check["ID"]).sum(),
)
1
(503, 32, 500, 503, 503)

All 503 submissions match the practice file by ResponseId, and the four-digit participant IDs agree in every pair. There are 500 distinct participants. The 32 rows in question_text describe worksheet columns, including identifiers and dates.

Dates stored in two ways

The workbook import now identifies submissions correctly, but a column’s imported type may still conceal differences between its source cells. In data/raw/panel/panel_w2.xlsx, ordinary type inference reads 2024. 9. 25. and 45560 in the same date column on the Wave 2 sheet. The original cells, B2 and B3, reveal how each was stored.

In Python, pl.read_excel() reads a worksheet into a DataFrame with engine="openpyxl" selecting the openpyxl library. A cell’s data_type gives the stored type, text (s) or numeric (n), and number_format describes the display format.

1
2
3
4
5
w2_path <- "data/raw/panel/panel_w2.xlsx"
guessed <- read_excel(w2_path, sheet = "Wave 2")
guessed |>
  select(id, date) |>
  head(3)
1
2
3
4
5
6
# A tibble: 3 × 2
     id date        
  <dbl> <chr>       
1     1 2024. 9. 25.
2     3 45560       
3     4 45541       
1
2
3
4
5
6
7
8
9
w2_path = "data/raw/panel/panel_w2.xlsx"
guessed = pl.read_excel(w2_path, sheet_name="Wave 2", engine="openpyxl")
guessed.select("id", "date").head(3)
panel_book = openpyxl.load_workbook(w2_path)
wave_2 = panel_book["Wave 2"]
[
    (wave_2[cell].value, wave_2[cell].data_type, wave_2[cell].number_format)
    for cell in ["B2", "B3"]
]
1
2
3
4
5
6
7
8
9
10
11
shape: (3, 2)
┌─────┬──────────────┐
│ id  ┆ date         │
│ --- ┆ ---          │
│ i64 ┆ str          │
╞═════╪══════════════╡
│ 1   ┆ 2024. 9. 25. │
│ 3   ┆ 45560        │
│ 4   ┆ 45541        │
└─────┴──────────────┘
[('2024. 9. 25.', 's', 'General'), (45560, 'n', 'General')]

Both tables display the date column as text. In the worksheet itself, B2 contains the string 2024. 9. 25. and B3 contains the number 45560.

Both cells have the General display format, which does not identify either value as a date. The panel specifies that numbers in its date field, including 45560 in B3, are Excel date serials. Text entries in the same field give the year, month and day. The source convention therefore determines how each value should be interpreted.

A serial counts days from an origin set by the workbook. This workbook uses the 1900 date system. For the modern dates here, its origin is December 30, 1899; the 1904 system uses January 1, 1904. To show why the workbook’s setting matters, as.Date() in R and datetime.timedelta in Python convert B3 using both origins. In openpyxl, panel_book.epoch reports the workbook’s origin.

1
2
as.Date(45560, origin = "1899-12-30")
as.Date(45560, origin = "1904-01-01")
1
2
[1] "2024-09-25"
[1] "2028-09-26"
1
2
3
4
5
import datetime

panel_book.epoch
(panel_book.epoch + datetime.timedelta(days=45560)).date()
datetime.date(1904, 1, 1) + datetime.timedelta(days=45560)
1
2
3
datetime.datetime(1899, 12, 30, 0, 0)
datetime.date(2024, 9, 25)
datetime.date(2028, 9, 26)

The workbook reports the 1899-12-30 epoch, so the number in B3 represents September 25, 2024, the same date written out in B2. With the other origin it would fall in 2028.

The conversion must distinguish numeric cells from text cells before assigning a date. In readxl::read_excel(), col_types = c("numeric", "list") stores each date cell with its own type in a list column, while cell_cols("A:B") limits the read to identifiers and dates. map_chr() with class records the cell type. The two following maps place each value in either serial or text, with the other field missing.

For serials, if_else() selects the date from as.Date() with the workbook’s 1899-12-30 origin. For text, it selects the date from ymd(), which parses the year, month and day separated by dots and spaces.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
wave_2_dates <- read_excel(
  w2_path,
  sheet = "Wave 2",
  range = cell_cols("A:B"),
  col_types = c("numeric", "list")
)
wave_2_dates <- wave_2_dates |>
  mutate(
    cell_type = map_chr(date, class),
    serial = map_dbl(date, \(x) if (is.numeric(x)) x else NA_real_),
    text = map_chr(date, \(x) if (is.character(x)) x else NA_character_),
    date_value = if_else(
      cell_type == "numeric",
      as.Date(serial, origin = "1899-12-30"),
      ymd(text)
    )
  )
filter(wave_2_dates, id %in% c(1, 3))
1
2
3
4
5
# A tibble: 2 × 6
     id date      cell_type serial text         date_value
  <dbl> <list>    <chr>      <dbl> <chr>        <date>    
1     1 <chr [1]> character     NA 2024. 9. 25. 2024-09-25
2     3 <dbl [1]> numeric    45560 <NA>         2024-09-25

The text for ID 1 and the serial for ID 3 both resolve to September 25, 2024. The text and serial columns record the two source representations.

By default, openpyxl returns cell objects from iter_rows(). The loop records the participant ID and each date cell’s coordinate, data_type, and original value. Numeric values go into serial and strings into text. For numeric cells, the code adds pl.duration(days=...) to the workbook’s origin. str.to_date("%Y. %-m. %-d.") parses the text dates, including months and days without 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
cells = []
for id_cell, date_cell in wave_2.iter_rows(min_row=2, max_col=2):
    is_number = date_cell.data_type == "n"
    cells.append(
        (
            id_cell.value,
            date_cell.coordinate,
            date_cell.data_type,
            date_cell.value if is_number else None,
            None if is_number else date_cell.value,
        )
    )

wave_2_dates = pl.DataFrame(
    cells, schema=["id", "cell", "cell_type", "serial", "text"], orient="row"
)
origin = panel_book.epoch.date()
wave_2_dates = wave_2_dates.with_columns(
    date=pl.when(pl.col("cell_type") == "n")
    .then(pl.lit(origin) + pl.duration(days=pl.col("serial")))
    .otherwise(pl.col("text").str.to_date("%Y. %-m. %-d."))
)
wave_2_dates.filter(pl.col("id").is_in([1, 3]))
1
2
3
4
5
6
7
8
9
shape: (2, 6)
┌─────┬──────┬───────────┬────────┬──────────────┬────────────┐
│ id  ┆ cell ┆ cell_type ┆ serial ┆ text         ┆ date       │
│ --- ┆ ---  ┆ ---       ┆ ---    ┆ ---          ┆ ---        │
│ i64 ┆ str  ┆ str       ┆ i64    ┆ str          ┆ date       │
╞═════╪══════╪═══════════╪════════╪══════════════╪════════════╡
│ 1   ┆ B2   ┆ s         ┆ null   ┆ 2024. 9. 25. ┆ 2024-09-25 │
│ 3   ┆ B3   ┆ n         ┆ 45560  ┆ null         ┆ 2024-09-25 │
└─────┴──────┴───────────┴────────┴──────────────┴────────────┘

B2 and B3 both give September 25, 2024. B2’s row shows the original date in text, and B3’s shows 45560 in serial.

For each cell type, the summary gives the number of records, the number of missing dates, and the earliest and latest converted dates. R names the types character and numeric, while openpyxl uses the worksheet markers s and n.

1
2
3
4
5
6
7
8
wave_2_dates |>
  group_by(cell_type) |>
  summarise(
    n = n(),
    missing = sum(is.na(date_value)),
    first = min(date_value),
    last = max(date_value)
  )
1
2
3
4
5
# A tibble: 2 × 5
  cell_type     n missing first      last      
  <chr>     <int>   <int> <date>     <date>    
1 character   105       0 2024-09-02 2024-09-27
2 numeric     168       0 2024-09-02 2024-09-27
1
2
3
4
5
6
7
8
9
10
(
    wave_2_dates.group_by("cell_type")
    .agg(
        n=pl.len(),
        missing=pl.col("date").null_count(),
        first=pl.col("date").min(),
        last=pl.col("date").max(),
    )
    .sort("cell_type")
)
1
2
3
4
5
6
7
8
9
shape: (2, 5)
┌───────────┬─────┬─────────┬────────────┬────────────┐
│ cell_type ┆ n   ┆ missing ┆ first      ┆ last       │
│ ---       ┆ --- ┆ ---     ┆ ---        ┆ ---        │
│ str       ┆ u32 ┆ u32     ┆ date       ┆ date       │
╞═══════════╪═════╪═════════╪════════════╪════════════╡
│ n         ┆ 168 ┆ 0       ┆ 2024-09-02 ┆ 2024-09-27 │
│ s         ┆ 105 ┆ 0       ┆ 2024-09-02 ┆ 2024-09-27 │
└───────────┴─────┴─────────┴────────────┴────────────┘

All 168 numeric cells and 105 text cells yield dates. Both sets range from September 2 to September 27, 2024.

16.2 Labeled data and user-defined missing codes

The survey workbook records agreement answers in words. The export from the statistics package SPSS, data/raw/survey/survey_raw.sav, records them as numeric codes with labels. Interpreting this source requires both the recorded numbers and their metadata: which code means Neutral on STR_7, and which codes indicate nonresponse?

In R, haven comes with tidyverse and is loaded separately. Its read_sav() returns the numeric values with their labels attached to the column. For Python, install pyreadstat in .venv through Packages: Install Package. pyreadstat.read_sav() with output_format="polars" returns a table of values and a separate metadata object. We first inspect one rating and its label.

1
2
3
4
library(haven)
sav_path <- "data/raw/survey/survey_raw.sav"
plain <- read_sav(sav_path)
plain$STR_7[1]
1
2
3
4
5
6
7
8
9
10
11
<labelled<double>[1]>: I felt in control of my life.
[1] 3

Labels:
 value             label
     1 Strongly disagree
     2          Disagree
     3           Neutral
     4             Agree
     5    Strongly agree
   -99           Refused
1
2
3
4
5
6
import pyreadstat

sav_path = "data/raw/survey/survey_raw.sav"
plain, plain_meta = pyreadstat.read_sav(sav_path, output_format="polars")
plain["STR_7"][0]
plain_meta.variable_value_labels["STR_7"]
1
2
3.0
{1.0: 'Strongly disagree', 2.0: 'Disagree', 3.0: 'Neutral', 4.0: 'Agree', 5.0: 'Strongly agree', -99.0: 'Refused'}

Both readers return the number 3. Its value label is Neutral. To interpret that rating, we also need the wording of STR_7.

The variable label gives the question. haven::read_sav() puts it in the column’s label attribute, while pyreadstat.read_sav() returns it in column_names_to_labels. attr() retrieves one attribute by name, here label. The worksheet description in question_text gives a second source for the wording.

1
2
attr(plain$STR_7, "label")
attr(plain$STR_7, "label") == question_text$question[question_text$variable == "STR_7"]
1
2
[1] "I felt in control of my life."
[1] TRUE
1
2
3
4
plain_meta.column_names_to_labels["STR_7"]
question_text.filter(pl.col("variable") == "STR_7")["question"][0] == (
    plain_meta.column_names_to_labels["STR_7"]
)
1
2
'I felt in control of my life.'
True

Both labels give the statement “I felt in control of my life.” The recorded 3 is therefore a neutral rating of that statement.

A skipped STR_7 answer is system missing, the built-in missing value in SPSS. A refusal is recorded as -99, a number the file declares missing for this variable. The code 6 is outside the agreement scale of 1 to 5 and has no such declaration. Which of these cases can we distinguish after a default import?

1
2
3
4
5
6
7
8
9
10
focal_ids <- c(
  "R_Z4kK41wEM10D",
  "R_UOPO9ilgPEuT",
  "R_NzfZtZHd75Ls",
  "R_3o97WxB74jOQ",
  "R_AQMrJ5pWxGfl"
)
plain |>
  filter(ResponseId %in% focal_ids) |>
  select(ResponseId, STR_7)
1
2
3
4
5
6
7
8
# A tibble: 5 × 2
  ResponseId     STR_7       
  <chr>          <dbl+lbl>   
1 R_Z4kK41wEM10D  3 [Neutral]
2 R_NzfZtZHd75Ls NA          
3 R_AQMrJ5pWxGfl  3 [Neutral]
4 R_3o97WxB74jOQ  6          
5 R_UOPO9ilgPEuT NA          
1
2
3
4
5
6
7
8
focal_ids = [
    "R_Z4kK41wEM10D",
    "R_UOPO9ilgPEuT",
    "R_NzfZtZHd75Ls",
    "R_3o97WxB74jOQ",
    "R_AQMrJ5pWxGfl",
]
plain.filter(pl.col("ResponseId").is_in(focal_ids)).select("ResponseId", "STR_7")
1
2
3
4
5
6
7
8
9
10
11
12
shape: (5, 2)
┌────────────────┬───────┐
│ ResponseId     ┆ STR_7 │
│ ---            ┆ ---   │
│ str            ┆ f64   │
╞════════════════╪═══════╡
│ R_Z4kK41wEM10D ┆ 3.0   │
│ R_NzfZtZHd75Ls ┆ null  │
│ R_AQMrJ5pWxGfl ┆ 3.0   │
│ R_3o97WxB74jOQ ┆ 6.0   │
│ R_UOPO9ilgPEuT ┆ null  │
└────────────────┴───────┘

The invalid 6 is still visible. The skip and the refusal both appear as missing. Although the value labels tell us that -99 means Refused, the imported values no longer identify which submission recorded it.

With user_na = TRUE, haven::read_sav() returns declared missing codes as values in haven_labelled_spss columns. Their declarations are in the na_values attribute. The same records now show STR_7, BirthYear, and Q_OPEN together. The is.na() result shows which STR_7 values still count as missing.

1
2
3
4
5
6
7
survey_sav <- read_sav(sav_path, user_na = TRUE)
focal <- survey_sav |>
  filter(ResponseId %in% focal_ids) |>
  select(ResponseId, STR_7, BirthYear, Q_OPEN)
focal
attr(survey_sav$STR_7, "na_values")
is.na(focal$STR_7)
1
2
3
4
5
6
7
8
9
10
# A tibble: 5 × 4
  ResponseId     STR_7              BirthYear             Q_OPEN              
  <chr>          <dbl+lbl>          <dbl+lbl>             <chr>               
1 R_Z4kK41wEM10D   3 [Neutral]      1965                  ""                  
2 R_NzfZtZHd75Ls  NA                1982                  ""                  
3 R_AQMrJ5pWxGfl   3 [Neutral]       999 (NA) [No answer] ""                  
4 R_3o97WxB74jOQ   6                1965                  ""                  
5 R_UOPO9ilgPEuT -99 (NA) [Refused] 1994                  "Made a to-do list."
[1] -99
[1] FALSE  TRUE FALSE FALSE  TRUE

For R_UOPO9ilgPEuT, the refusal now appears as -99 (NA) [Refused]. The skipped answer for R_NzfZtZHd75Ls is still NA. is.na() returns TRUE for both because this column declares -99 a missing value. The 999 in BirthYear has the label No answer, and empty open answers appear as "".

Converting the labeled columns to ordinary numbers separates their values from the metadata needed to interpret them. The working table uses across(where(is.labelled), as.numeric), and attributes() checks the resulting column. To preserve the interpretation, str_7_labels extracts the codes and names from the original labels attribute, while variable_info collects each question label and missing code by variable name.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
survey_codes <- mutate(survey_sav, across(where(is.labelled), as.numeric))
attributes(survey_codes$STR_7)
survey_codes |>
  filter(ResponseId %in% focal_ids) |>
  select(ResponseId, STR_7, BirthYear)
min(survey_codes$BirthYear)
str_7_labels <- tibble(
  code = attr(survey_sav$STR_7, "labels"),
  label = names(attr(survey_sav$STR_7, "labels"))
)
variable_info <- tibble(
  variable = c("STR_7", "BirthYear"),
  label = map_chr(variable, \(name) attr(survey_sav[[name]], "label")),
  missing_code = map_dbl(variable, \(name) attr(survey_sav[[name]], "na_values"))
)
str_7_labels
variable_info
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
NULL
# A tibble: 5 × 3
  ResponseId     STR_7 BirthYear
  <chr>          <dbl>     <dbl>
1 R_Z4kK41wEM10D     3      1965
2 R_NzfZtZHd75Ls    NA      1982
3 R_AQMrJ5pWxGfl     3       999
4 R_3o97WxB74jOQ     6      1965
5 R_UOPO9ilgPEuT   -99      1994
[1] 999
# A tibble: 6 × 2
   code label            
  <dbl> <chr>            
1     1 Strongly disagree
2     2 Disagree         
3     3 Neutral          
4     4 Agree            
5     5 Strongly agree   
6   -99 Refused          
# A tibble: 2 × 3
  variable  label                         missing_code
  <chr>     <chr>                                <dbl>
1 STR_7     I felt in control of my life.          -99
2 BirthYear Birth year                             999

After conversion, attributes() returns NULL for STR_7, and the codes -99 and 999 are ordinary numbers. The minimum of BirthYear is 999. The BirthYear row in variable_info marks 999 as a missing code, so it must be excluded to find the earliest recorded birth year.

In pyreadstat.read_sav(), user_missing=True makes declared missing codes visible as values, and apply_value_formats=False returns the numeric codes. The missing_ranges metadata and birth-year labels show which numbers denote nonresponse.

1
2
3
4
5
6
7
8
9
10
11
survey_sav, meta = pyreadstat.read_sav(
    sav_path,
    output_format="polars",
    user_missing=True,
    apply_value_formats=False,
)
survey_sav.filter(pl.col("ResponseId").is_in(focal_ids)).select(
    "ResponseId", "STR_7", "BirthYear", "Q_OPEN"
)
(meta.missing_ranges["STR_7"], meta.missing_ranges["BirthYear"])
meta.variable_value_labels["BirthYear"]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
shape: (5, 4)
┌────────────────┬───────┬───────────┬────────────────────┐
│ ResponseId     ┆ STR_7 ┆ BirthYear ┆ Q_OPEN             │
│ ---            ┆ ---   ┆ ---       ┆ ---                │
│ str            ┆ f64   ┆ f64       ┆ str                │
╞════════════════╪═══════╪═══════════╪════════════════════╡
│ R_Z4kK41wEM10D ┆ 3.0   ┆ 1965.0    ┆                    │
│ R_NzfZtZHd75Ls ┆ null  ┆ 1982.0    ┆                    │
│ R_AQMrJ5pWxGfl ┆ 3.0   ┆ 999.0     ┆                    │
│ R_3o97WxB74jOQ ┆ 6.0   ┆ 1965.0    ┆                    │
│ R_UOPO9ilgPEuT ┆ -99.0 ┆ 1994.0    ┆ Made a to-do list. │
└────────────────┴───────┴───────────┴────────────────────┘
([{'lo': -99.0, 'hi': -99.0}], [{'lo': 999.0, 'hi': 999.0}])
{999.0: 'No answer'}

The refusal is now -99.0 and the skipped answer is null. In missing_ranges, equal lower and upper limits identify a single missing code for each variable. It is -99 for STR_7 and 999 for BirthYear. The latter has the label No answer. The blank-looking Q_OPEN cells contain empty strings.

The Polars table contains the numbers. Their SPSS labels and missing-value declarations are in meta. The table str_7_labels pairs each code with its label, and variable_info pairs each variable with its description and missing code. For both STR_7 and BirthYear, the range has identical limits, so its lower limit gives the missing code.

1
2
3
4
5
6
7
8
9
10
11
12
13
(survey_sav.schema["STR_7"], survey_sav["BirthYear"].min())
labels = meta.variable_value_labels["STR_7"]
str_7_labels = pl.DataFrame({"code": list(labels), "label": list(labels.values())})
info_names = ["STR_7", "BirthYear"]
variable_info = pl.DataFrame(
    {
        "variable": info_names,
        "label": [meta.column_names_to_labels[name] for name in info_names],
        "missing_code": [meta.missing_ranges[name][0]["lo"] for name in info_names],
    }
)
str_7_labels
variable_info
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
(Float64, 999.0)
shape: (6, 2)
┌───────┬───────────────────┐
│ code  ┆ label             │
│ ---   ┆ ---               │
│ f64   ┆ str               │
╞═══════╪═══════════════════╡
│ 1.0   ┆ Strongly disagree │
│ 2.0   ┆ Disagree          │
│ 3.0   ┆ Neutral           │
│ 4.0   ┆ Agree             │
│ 5.0   ┆ Strongly agree    │
│ -99.0 ┆ Refused           │
└───────┴───────────────────┘
shape: (2, 3)
┌───────────┬───────────────────────────────┬──────────────┐
│ variable  ┆ label                         ┆ missing_code │
│ ---       ┆ ---                           ┆ ---          │
│ str       ┆ str                           ┆ f64          │
╞═══════════╪═══════════════════════════════╪══════════════╡
│ STR_7     ┆ I felt in control of my life. ┆ -99.0        │
│ BirthYear ┆ Birth year                    ┆ 999.0        │
└───────────┴───────────────────────────────┴──────────────┘

STR_7 is an ordinary Float64 column, and the minimum BirthYear is 999.0. The companion variable_info table contains the declaration needed to interpret that value as nonresponse.

The imported codes can now be compared with the workbook answers. ResponseId links each selected SPSS record to the same submission in the workbook. The workbook uses agreement labels for codes 1 to 5, text -99 for refusal, text 6 for the invalid code, and blank cells for skipped answers. The comparison must reproduce these representations before testing equality.

In R, joining str_7_labels to the SPSS records provides the labels needed to construct sav_text. na_if(Q_OPEN, "") represents empty open answers as missing. vctrs::vec_equal(..., na_equal = TRUE) compares vectors element by element, treating paired missing values as equal. vctrs is installed with tidyverse.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
compared <- survey_codes |>
  filter(ResponseId %in% focal_ids) |>
  select(ResponseId, STR_7, Q_OPEN) |>
  left_join(str_7_labels, by = join_by(STR_7 == code)) |>
  mutate(
    sav_text = if_else(STR_7 %in% 1:5, label, as.character(STR_7)),
    sav_open = na_if(Q_OPEN, "")
  ) |>
  inner_join(
    select(survey, ResponseId, xlsx_STR_7 = STR_7, xlsx_open = Q_OPEN),
    by = join_by(ResponseId),
    relationship = "one-to-one"
  ) |>
  mutate(
    same_answer = vctrs::vec_equal(sav_text, xlsx_STR_7, na_equal = TRUE),
    same_open = vctrs::vec_equal(sav_open, xlsx_open, na_equal = TRUE)
  ) |>
  arrange(ResponseId)
select(compared, ResponseId, STR_7, sav_text, xlsx_STR_7, same_answer)
select(compared, ResponseId, Q_OPEN, xlsx_open, same_open)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# A tibble: 5 × 5
  ResponseId     STR_7 sav_text xlsx_STR_7 same_answer
  <chr>          <dbl> <chr>    <chr>      <lgl>      
1 R_3o97WxB74jOQ     6 6        6          TRUE       
2 R_AQMrJ5pWxGfl     3 Neutral  Neutral    TRUE       
3 R_NzfZtZHd75Ls    NA <NA>     <NA>       TRUE       
4 R_UOPO9ilgPEuT   -99 -99      -99        TRUE       
5 R_Z4kK41wEM10D     3 Neutral  Neutral    TRUE       
# A tibble: 5 × 4
  ResponseId     Q_OPEN               xlsx_open          same_open
  <chr>          <chr>                <chr>              <lgl>    
1 R_3o97WxB74jOQ ""                   <NA>               TRUE     
2 R_AQMrJ5pWxGfl ""                   <NA>               TRUE     
3 R_NzfZtZHd75Ls ""                   <NA>               TRUE     
4 R_UOPO9ilgPEuT "Made a to-do list." Made a to-do list. TRUE     
5 R_Z4kK41wEM10D ""                   <NA>               TRUE     

All five selected answers match, including the refusal and invalid code. The second display also pairs each empty SPSS string with an empty worksheet cell.

The Polars join adds the agreement labels to the selected SPSS rows. pl.when() uses labels for codes 1 to 5 and casts other codes through Int64 to text, so that -99.0 becomes -99 as in the workbook. replace("", None) turns empty open answers into nulls. The workbook join validates a one-to-one key, and eq_missing() treats two nulls as equal. The paired records appear in ResponseId order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
compared = (
    survey_sav.filter(pl.col("ResponseId").is_in(focal_ids))
    .select("ResponseId", "STR_7", "Q_OPEN")
    .join(str_7_labels, left_on="STR_7", right_on="code", how="left")
    .with_columns(
        sav_text=pl.when(pl.col("STR_7").is_between(1, 5))
        .then(pl.col("label"))
        .otherwise(pl.col("STR_7").cast(pl.Int64).cast(pl.String)),
        sav_open=pl.col("Q_OPEN").replace("", None),
    )
    .join(
        survey.select("ResponseId", xlsx_STR_7="STR_7", xlsx_open="Q_OPEN"),
        on="ResponseId",
        validate="1:1",
    )
    .with_columns(
        same_answer=pl.col("sav_text").eq_missing(pl.col("xlsx_STR_7")),
        same_open=pl.col("sav_open").eq_missing(pl.col("xlsx_open")),
    )
    .sort("ResponseId")
)
compared.select("ResponseId", "STR_7", "sav_text", "xlsx_STR_7", "same_answer")
compared.select("ResponseId", "Q_OPEN", "xlsx_open", "same_open")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
shape: (5, 5)
┌────────────────┬───────┬──────────┬────────────┬─────────────┐
│ ResponseId     ┆ STR_7 ┆ sav_text ┆ xlsx_STR_7 ┆ same_answer │
│ ---            ┆ ---   ┆ ---      ┆ ---        ┆ ---         │
│ str            ┆ f64   ┆ str      ┆ str        ┆ bool        │
╞════════════════╪═══════╪══════════╪════════════╪═════════════╡
│ R_3o97WxB74jOQ ┆ 6.0   ┆ 6        ┆ 6          ┆ true        │
│ R_AQMrJ5pWxGfl ┆ 3.0   ┆ Neutral  ┆ Neutral    ┆ true        │
│ R_NzfZtZHd75Ls ┆ null  ┆ null     ┆ null       ┆ true        │
│ R_UOPO9ilgPEuT ┆ -99.0 ┆ -99      ┆ -99        ┆ true        │
│ R_Z4kK41wEM10D ┆ 3.0   ┆ Neutral  ┆ Neutral    ┆ true        │
└────────────────┴───────┴──────────┴────────────┴─────────────┘
shape: (5, 4)
┌────────────────┬────────────────────┬────────────────────┬───────────┐
│ ResponseId     ┆ Q_OPEN             ┆ xlsx_open          ┆ same_open │
│ ---            ┆ ---                ┆ ---                ┆ ---       │
│ str            ┆ str                ┆ str                ┆ bool      │
╞════════════════╪════════════════════╪════════════════════╪═══════════╡
│ R_3o97WxB74jOQ ┆                    ┆ null               ┆ true      │
│ R_AQMrJ5pWxGfl ┆                    ┆ null               ┆ true      │
│ R_NzfZtZHd75Ls ┆                    ┆ null               ┆ true      │
│ R_UOPO9ilgPEuT ┆ Made a to-do list. ┆ Made a to-do list. ┆ true      │
│ R_Z4kK41wEM10D ┆                    ┆ null               ┆ true      │
└────────────────┴────────────────────┴────────────────────┴───────────┘

All five selected submissions match on STR_7 and Q_OPEN. For STR_7, code 3.0 corresponds to Neutral. For Q_OPEN, four empty SPSS strings match worksheet blanks. The remaining submission records Made a to-do list. in both files.

Dates and their declared format

The third panel wave, data/raw/panel/panel_w3.sav, also relies on metadata, this time for dates. The stored type and format of DATE explain how each reader can return survey dates from a numeric field.

1
2
3
w3 <- read_sav("data/raw/panel/panel_w3.sav", user_na = TRUE)
attributes(w3$DATE)
range(w3$DATE)
1
2
3
4
5
6
7
8
9
10
$label
[1] "Survey date"

$class
[1] "Date"

$format.spss
[1] "DATE11"

[1] "2025-03-03" "2025-03-28"
1
2
3
4
5
6
7
8
9
10
11
12
w3, w3_meta = pyreadstat.read_sav(
    "data/raw/panel/panel_w3.sav",
    output_format="polars",
    user_missing=True,
    apply_value_formats=False,
)
(
    w3_meta.column_names_to_labels["DATE"],
    w3_meta.original_variable_types["DATE"],
    w3_meta.readstat_variable_types["DATE"],
)
(w3["DATE"].dtype, w3["DATE"].min(), w3["DATE"].max())
1
2
('Survey date', 'DATE11', 'double')
(Date, datetime.date(2025, 3, 3), datetime.date(2025, 3, 28))

The SPSS field DATE stores numbers with the DATE11 format. Both readers use the SPSS date declaration to return dates from March 3 to March 28, 2025. The Excel origin from the workbook example does not apply here.

16.3 Encodings and tables formatted for readers

The previous sources required cell types or metadata to interpret their values. The population file data/raw/public/population_cp1252.csv first requires the correct text encoding, then a distinction between district records and report headings or totals. It uses Windows-1252; an en dash in its title and a dagger in its footnote provide checks on the decoded text.

We begin with the bytes that encode those characters. R’s readBin() returns raw bytes, and which() locates bytes above the last ASCII code, 0x7f. In Python, Path.read_bytes() returns the file’s bytes, and the comprehension locates the same values and displays them with hex().

1
2
3
4
5
population_path <- "data/raw/public/population_cp1252.csv"
bytes <- readBin(population_path, "raw", n = file.size(population_path))
length(bytes)
which(bytes > as.raw(0x7f))
bytes[bytes > as.raw(0x7f)]
1
2
3
[1] 15445
[1]    41 15381
[1] 96 86
1
2
3
4
5
6
from pathlib import Path

population_path = Path("data/raw/public/population_cp1252.csv")
raw = population_path.read_bytes()
len(raw)
[(position, hex(byte)) for position, byte in enumerate(raw) if byte > 0x7F]
1
2
15445
[(40, '0x96'), (15380, '0x86')]

Only two bytes exceed the ASCII range. In Windows-1252, 0x96 is an en dash and 0x86 is a dagger. R’s position 41 and Python’s position 40 identify the first of these bytes because indexing starts at 1 and 0, respectively. In UTF-8, bytes from 0x80 to 0xbf can follow the first byte of a multibyte character. Here 0x96 follows an ASCII digit and 0x86 starts a line, so neither is valid at its position.

readr::read_lines() defaults to UTF-8. validUTF8() tests the strings it returns. With locale(encoding = "windows-1252"), the same function decodes the bytes in the file’s own encoding, and utf8ToInt() reports the resulting Unicode code points.

1
2
3
4
5
6
7
8
as_utf8 <- read_lines(population_path)
length(as_utf8)
sum(!validUTF8(as_utf8))
as_utf8[1]
lines <- read_lines(population_path, locale = locale(encoding = "windows-1252"))
lines[c(1, 251)]
utf8ToInt(lines[1])[41]
utf8ToInt(lines[251])[1]
1
2
3
4
5
6
7
[1] 251
[1] 2
[1] "\"Registered population by district, 2019\x962023 (synthetic data for this textbook)\",,,,,,"
[1] "\"Registered population by district, 2019–2023 (synthetic data for this textbook)\",,,,,,"
[2] "† These figures are synthetic data made for this textbook.,,,,,,"                         
[1] 8211
[1] 8224

read_lines() returned all 251 lines, but two fail validUTF8(). The title contains an undecoded \x96 byte. Under Windows-1252, the title and footnote display correctly. The code points 8211 and 8224 are U+2013, the en dash, and U+2020, the dagger.

Path.read_text(encoding="utf-8") attempts to decode the whole file. Run this deliberate failure separately from the corrected read below.

1
2
# Deliberate error: decoding the Windows-1252 bytes as UTF-8
population_path.read_text(encoding="utf-8")
1
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 40: invalid start byte

Path.read_text() stops at the invalid start byte. With encoding="windows-1252", it can decode the full file. splitlines() returns one string per line. In this file, lines[0] is the title and lines[-1] is the footnote.

1
2
3
4
5
6
text = population_path.read_text(encoding="windows-1252")
lines = text.splitlines()
len(lines)
lines[0]
lines[-1]
(hex(ord(lines[0][40])), hex(ord(lines[-1][0])))
1
2
3
4
251
'"Registered population by district, 2019–2023 (synthetic data for this textbook)",,,,,,'
'† These figures are synthetic data made for this textbook.,,,,,,'
('0x2013', '0x2020')

The title and footnote now display the en dash and dagger. Both are among the 251 decoded lines, so 251 cannot be the number of districts.

Lines and their roles

The first seven lines show where district records begin, and the final line shows how the report ends. R’s paste() adds each number to its text for writeLines(). Python uses lines[number - 1] because list positions start at zero.

1
2
excerpt_lines <- c(1:7, 251)
writeLines(paste(excerpt_lines, lines[excerpt_lines]))
1
2
3
4
5
6
7
8
1 "Registered population by district, 2019–2023 (synthetic data for this textbook)",,,,,,
2 Province,District,2019,2020,2021,2022,2023
3 ,,Total population (persons),Total population (persons),Total population (persons),Total population (persons),Total population (persons)
4 Nationwide,Total,"51,052,236","51,082,752","51,157,486","51,229,421","51,299,993"
5 Seoul,Subtotal,"9,924,388","9,900,388","9,875,346","9,844,752","9,819,920"
6 ,Jongno-gu,"440,154","437,997","439,663","438,216","437,036"
7 ,Jung-gu,"281,421","280,684","279,144","278,021","277,639"
251 † These figures are synthetic data made for this textbook.,,,,,,
1
2
3
excerpt_lines = [1, 2, 3, 4, 5, 6, 7, 251]
for number in excerpt_lines:
    print(number, lines[number - 1])
1
2
3
4
5
6
7
8
1 "Registered population by district, 2019–2023 (synthetic data for this textbook)",,,,,,
2 Province,District,2019,2020,2021,2022,2023
3 ,,Total population (persons),Total population (persons),Total population (persons),Total population (persons),Total population (persons)
4 Nationwide,Total,"51,052,236","51,082,752","51,157,486","51,229,421","51,299,993"
5 Seoul,Subtotal,"9,924,388","9,900,388","9,875,346","9,844,752","9,819,920"
6 ,Jongno-gu,"440,154","437,997","439,663","438,216","437,036"
7 ,Jung-gu,"281,421","280,684","279,144","278,021","277,639"
251 † These figures are synthetic data made for this textbook.,,,,,,

Line 1 is the title, and lines 2 and 3 contain column names and units. The national total follows, then Seoul’s subtotal and its districts. A subtotal is the sum of a region’s district rows. The footnote ends the file. The source calls the regional field Province, and population counts contain thousands separators. Only the district lines describe individual districts.

Passing seven column names to readr::read_csv() makes the title the first record. All fields are read as Windows-1252 text. Each CSV record occupies one line in this file, so row_number() identifies the source line before filtering. case_when() identifies the title and headers by line number, the totals by field_2, and the footnote by its final position. A blank field_1 then identifies a district. Any line that meets none of these conditions is unclassified.

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
field_names <- paste0("field_", 1:7)
population_rows <- read_csv(
  population_path,
  col_names = field_names,
  col_types = cols(.default = col_character()),
  na = "",
  trim_ws = FALSE,
  locale = locale(encoding = "windows-1252")
) |>
  mutate(line = row_number(), .before = 1) |>
  mutate(
    role = case_when(
      line == 1 ~ "title",
      line %in% 2:3 ~ "header",
      field_2 == "Total" ~ "national total",
      field_2 == "Subtotal" ~ "province subtotal",
      line == n() ~ "footnote",
      is.na(field_1) ~ "district",
      .default = "unclassified"
    )
  )
nrow(population_rows)
population_rows |>
  filter(line %in% excerpt_lines) |>
  select(line, role, field_2, field_1)
1
2
3
4
5
6
7
8
9
10
11
12
[1] 251
# A tibble: 8 × 4
   line role              field_2   field_1                                     
  <int> <chr>             <chr>     <chr>                                       
1     1 title             <NA>      Registered population by district, 2019–202…
2     2 header            District  Province                                    
3     3 header            <NA>      <NA>                                        
4     4 national total    Total     Nationwide                                  
5     5 province subtotal Subtotal  Seoul                                       
6     6 district          Jongno-gu <NA>                                        
7     7 district          Jung-gu   <NA>                                        
8   251 footnote          <NA>      † These figures are synthetic data made for…

In pl.read_csv(), encoding="windows-1252" sets the decoding rule. has_header=False reads every line as a record, new_columns names the fields, and infer_schema=False reads them as text. Each CSV record here occupies one line, so with_row_index("line", offset=1) records each record’s source line. The ordered pl.when() tests assign the first matching role, with len(lines) marking the final footnote.

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
field_names = ["field_" + str(number) for number in range(1, 8)]
population_rows = (
    pl.read_csv(
        population_path,
        has_header=False,
        new_columns=field_names,
        infer_schema=False,
        encoding="windows-1252",
    )
    .with_row_index("line", offset=1)
    .with_columns(
        role=pl.when(pl.col("line") == 1)
        .then(pl.lit("title"))
        .when(pl.col("line").is_in([2, 3]))
        .then(pl.lit("header"))
        .when(pl.col("field_2") == "Total")
        .then(pl.lit("national total"))
        .when(pl.col("field_2") == "Subtotal")
        .then(pl.lit("province subtotal"))
        .when(pl.col("line") == len(lines))
        .then(pl.lit("footnote"))
        .when(pl.col("field_1").is_null())
        .then(pl.lit("district"))
        .otherwise(pl.lit("unclassified"))
    )
)
population_rows.height
population_rows.filter(pl.col("line").is_in(excerpt_lines)).select(
    "line", "role", "field_2", "field_1"
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
251
shape: (8, 4)
┌──────┬───────────────────┬───────────┬─────────────────────────────────┐
│ line ┆ role              ┆ field_2   ┆ field_1                         │
│ ---  ┆ ---               ┆ ---       ┆ ---                             │
│ u32  ┆ str               ┆ str       ┆ str                             │
╞══════╪═══════════════════╪═══════════╪═════════════════════════════════╡
│ 1    ┆ title             ┆ null      ┆ Registered population by distr… │
│ 2    ┆ header            ┆ District  ┆ Province                        │
│ 3    ┆ header            ┆ null      ┆ null                            │
│ 4    ┆ national total    ┆ Total     ┆ Nationwide                      │
│ 5    ┆ province subtotal ┆ Subtotal  ┆ Seoul                           │
│ 6    ┆ district          ┆ Jongno-gu ┆ null                            │
│ 7    ┆ district          ┆ Jung-gu   ┆ null                            │
│ 251  ┆ footnote          ┆ null      ┆ † These figures are synthetic … │
└──────┴───────────────────┴───────────┴─────────────────────────────────┘

Line 3 and the district lines 6 and 7 all have a blank first field. Line 3 is classified as a header because its line number is checked before the rule for a blank field.

Finding a district’s region

The exported table names each region once, on its subtotal row, and Province is blank on the district rows below. A district therefore belongs to the nearest preceding subtotal. Lines 29 through 33 show how that convention works where the table moves from Seoul to Busan. The column field_7 contains the 2023 population.

1
2
3
population_rows |>
  filter(line %in% 29:33) |>
  select(line, field_1, field_2, field_7, role)
1
2
3
4
5
6
7
8
# A tibble: 5 × 5
   line field_1 field_2     field_7   role             
  <int> <chr>   <chr>       <chr>     <chr>            
1    29 <NA>    Songpa-gu   216,117   district         
2    30 <NA>    Gangdong-gu 547,315   district         
3    31 Busan   Subtotal    4,149,666 province subtotal
4    32 <NA>    Jung-gu     147,067   district         
5    33 <NA>    Seo-gu      153,869   district         
1
2
3
population_rows.filter(pl.col("line").is_between(29, 33)).select(
    "line", "field_1", "field_2", "field_7", "role"
)
1
2
3
4
5
6
7
8
9
10
11
12
shape: (5, 5)
┌──────┬─────────┬─────────────┬───────────┬───────────────────┐
│ line ┆ field_1 ┆ field_2     ┆ field_7   ┆ role              │
│ ---  ┆ ---     ┆ ---         ┆ ---       ┆ ---               │
│ u32  ┆ str     ┆ str         ┆ str       ┆ str               │
╞══════╪═════════╪═════════════╪═══════════╪═══════════════════╡
│ 29   ┆ null    ┆ Songpa-gu   ┆ 216,117   ┆ district          │
│ 30   ┆ null    ┆ Gangdong-gu ┆ 547,315   ┆ district          │
│ 31   ┆ Busan   ┆ Subtotal    ┆ 4,149,666 ┆ province subtotal │
│ 32   ┆ null    ┆ Jung-gu     ┆ 147,067   ┆ district          │
│ 33   ┆ null    ┆ Seo-gu      ┆ 153,869   ┆ district          │
└──────┴─────────┴─────────────┴───────────┴───────────────────┘

Busan’s subtotal on line 31 gives the region for Jung-gu on line 32 and Seo-gu on line 33. Neither district row repeats the name Busan.

Several districts are called Jung-gu. Their source line numbers locate them relative to the subtotals that name their regions.

1
2
3
population_rows |>
  filter(role == "district", field_2 == "Jung-gu") |>
  select(line, field_1, field_2, role)
1
2
3
4
5
6
7
8
9
# A tibble: 6 × 4
   line field_1 field_2 role    
  <int> <chr>   <chr>   <chr>   
1     7 <NA>    Jung-gu district
2    32 <NA>    Jung-gu district
3    49 <NA>    Jung-gu district
4    59 <NA>    Jung-gu district
5    77 <NA>    Jung-gu district
6    82 <NA>    Jung-gu district
1
2
3
population_rows.filter(
    (pl.col("role") == "district") & (pl.col("field_2") == "Jung-gu")
).select("line", "field_1", "field_2", "role")
1
2
3
4
5
6
7
8
9
10
11
12
13
shape: (6, 4)
┌──────┬─────────┬─────────┬──────────┐
│ line ┆ field_1 ┆ field_2 ┆ role     │
│ ---  ┆ ---     ┆ ---     ┆ ---      │
│ u32  ┆ str     ┆ str     ┆ str      │
╞══════╪═════════╪═════════╪══════════╡
│ 7    ┆ null    ┆ Jung-gu ┆ district │
│ 32   ┆ null    ┆ Jung-gu ┆ district │
│ 49   ┆ null    ┆ Jung-gu ┆ district │
│ 59   ┆ null    ┆ Jung-gu ┆ district │
│ 77   ┆ null    ┆ Jung-gu ┆ district │
│ 82   ┆ null    ┆ Jung-gu ┆ district │
└──────┴─────────┴─────────┴──────────┘

Six district rows are named Jung-gu. Line 7 is Seoul’s Jung-gu because it follows the Seoul subtotal on line 5. Line 32 is Busan’s because it follows the Busan subtotal on line 31. Without the subtotal lines, the six district names alone would give no way to assign their regions.

Totals apart from districts

Before separating the records, a count by role checks whether any lines remain unclassified. A sum of district populations should count each resident once, so districts contains only district records. The separate totals table preserves the national and regional totals for comparison and the regional names needed to interpret district rows.

1
2
3
4
5
6
7
count(population_rows, role)
totals <- filter(population_rows, role %in% c("national total", "province subtotal"))
districts <- filter(population_rows, role == "district")
c(totals = nrow(totals), districts = nrow(districts))
totals |>
  select(line, field_1, field_2, field_7) |>
  head(3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# A tibble: 6 × 2
  role                  n
  <chr>             <int>
1 district            229
2 footnote              1
3 header                2
4 national total        1
5 province subtotal    17
6 title                 1
   totals districts 
       18       229 
# A tibble: 3 × 4
   line field_1    field_2  field_7   
  <int> <chr>      <chr>    <chr>     
1     4 Nationwide Total    51,299,993
2     5 Seoul      Subtotal 9,819,920 
3    31 Busan      Subtotal 4,149,666 
1
2
3
4
5
6
7
population_rows.group_by("role").agg(n=pl.len()).sort("role")
totals = population_rows.filter(
    pl.col("role").is_in(["national total", "province subtotal"])
)
districts = population_rows.filter(pl.col("role") == "district")
(totals.height, districts.height)
totals.select("line", "field_1", "field_2", "field_7").head(3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
shape: (6, 2)
┌───────────────────┬─────┐
│ role              ┆ n   │
│ ---               ┆ --- │
│ str               ┆ u32 │
╞═══════════════════╪═════╡
│ district          ┆ 229 │
│ footnote          ┆ 1   │
│ header            ┆ 2   │
│ national total    ┆ 1   │
│ province subtotal ┆ 17  │
│ title             ┆ 1   │
└───────────────────┴─────┘
(18, 229)
shape: (3, 4)
┌──────┬────────────┬──────────┬────────────┐
│ line ┆ field_1    ┆ field_2  ┆ field_7    │
│ ---  ┆ ---        ┆ ---      ┆ ---        │
│ u32  ┆ str        ┆ str      ┆ str        │
╞══════╪════════════╪══════════╪════════════╡
│ 4    ┆ Nationwide ┆ Total    ┆ 51,299,993 │
│ 5    ┆ Seoul      ┆ Subtotal ┆ 9,819,920  │
│ 31   ┆ Busan      ┆ Subtotal ┆ 4,149,666  │
└──────┴────────────┴──────────┴────────────┘

All 251 lines have assigned roles, including 229 district records and 18 totals. Seoul’s 2023 subtotal, 9,819,920, belongs in totals because adding it to its constituent district rows would count that population twice. The line numbers in districts let us find each district’s region on the preceding subtotal in totals.

16.4 Export versions, empty files, and file inventories

The population report required us to distinguish records within one file. The trial exports add a second task: accounting for every source file, including one that contributes no records. We will list the files, translate the two export formats into a common representation, and record the outcome of each import.

The pattern sub-*.csv in data/raw/trials/ selects the participant exports. Listing those paths before reading any records includes the empty sub-041_ses-1.csv in the inventory and excludes the lookup file stimuli.csv.

In R, Sys.glob() lists the paths that match sub-*.csv, and file.size() reports bytes. In Python, glob() finds paths, sorted() orders them, and stat().st_size returns their sizes. In both patterns, * stands for any sequence of characters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
trial_paths <- Sys.glob("data/raw/trials/sub-*.csv")
inventory <- tibble(
  path = trial_paths,
  file = basename(trial_paths),
  bytes = file.size(trial_paths)
)
nrow(inventory)
example_files <- c(
  "sub-001_ses-1.csv",
  "sub-006_ses-1.csv",
  "sub-007_ses-1.csv",
  "sub-041_ses-1.csv"
)
inventory |>
  filter(file %in% example_files) |>
  select(file, bytes)
1
2
3
4
5
6
7
8
[1] 43
# A tibble: 4 × 2
  file              bytes
  <chr>             <dbl>
1 sub-001_ses-1.csv 12121
2 sub-006_ses-1.csv 12351
3 sub-007_ses-1.csv  3487
4 sub-041_ses-1.csv     0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
trial_paths = sorted(Path("data/raw/trials").glob("sub-*.csv"))
inventory = pl.DataFrame(
    {
        "path": [str(path) for path in trial_paths],
        "file": [path.name for path in trial_paths],
        "bytes": [path.stat().st_size for path in trial_paths],
    }
)
inventory.height
example_files = [
    "sub-001_ses-1.csv",
    "sub-006_ses-1.csv",
    "sub-007_ses-1.csv",
    "sub-041_ses-1.csv",
]
inventory.filter(pl.col("file").is_in(example_files)).select("file", "bytes")
1
2
3
4
5
6
7
8
9
10
11
12
43
shape: (4, 2)
┌───────────────────┬───────┐
│ file              ┆ bytes │
│ ---               ┆ ---   │
│ str               ┆ i64   │
╞═══════════════════╪═══════╡
│ sub-001_ses-1.csv ┆ 12121 │
│ sub-006_ses-1.csv ┆ 12351 │
│ sub-007_ses-1.csv ┆ 3487  │
│ sub-041_ses-1.csv ┆ 0     │
└───────────────────┴───────┘

The inventory contains 43 paths. The size of sub-041_ses-1.csv is zero bytes, enough to mark it verified empty without opening it. A nonzero size, such as the 3,487 bytes of sub-007_ses-1.csv, establishes only that the file contains bytes. We must read it to determine how many records it contributes. Before applying one reader to the inventory, we need to reconcile the two export formats.

A common representation for two formats

The headers of sub-001_ses-1.csv and sub-006_ses-1.csv show how the two export formats name the same fields.

1
2
read_lines("data/raw/trials/sub-001_ses-1.csv", n_max = 1)
read_lines("data/raw/trials/sub-006_ses-1.csv", n_max = 1)
1
2
[1] "Participant,Session,Block,Trial,TrialType,Stim,Resp,Correct,RT_ms,Time,Survey"
[1] "participant,session,block,trial,trial_type,stim,resp,correct,rt,timestamp,response_json"
1
2
Path("data/raw/trials/sub-001_ses-1.csv").read_text().splitlines()[0]
Path("data/raw/trials/sub-006_ses-1.csv").read_text().splitlines()[0]
1
2
'Participant,Session,Block,Trial,TrialType,Stim,Resp,Correct,RT_ms,Time,Survey'
'participant,session,block,trial,trial_type,stim,resp,correct,rt,timestamp,response_json'

The earlier program used RT_ms and the newer one uses rt. Both record response times in milliseconds. Table 16.1 shows the names used in the combined table. For correctness and time, it includes both the recorded text and the converted value.

Table 16.1. Field correspondence between the old and new trial exports.

Old fieldNew fieldFields in the combined tableRecorded values
Participantparticipantparticipantsub-001 in the old example, sub-006 in the new example
Session, Block, Trialsession, block, trialsession, block, trialNumbers. Block and trial are blank on the questionnaire row.
TrialType, Stim, Resptrial_type, stim, resptrial_type, stim, respThe same codes in both formats
Correctcorrectcorrect_recorded, correctOld files use True or False. New files use 1 or 0.
RT_msrtrtMilliseconds in both formats
Timetimestamptime_recorded, onsetOld example 26/03/2024 09:55:11, new example 2024-03-15 12:25:08.549
Surveyresponse_jsonresponse_jsonJSON text on the questionnaire row

Correctness and time need value conversion as well as renaming. Old True and new 1 both mean correct, while False and 0 mean incorrect. The common correct field uses integers 1 and 0 and is missing for questionnaires.

Both export formats use the Asia/Seoul clock. Old files record day-first dates and whole seconds; new files record year-first dates and milliseconds. The converted onset values will support time calculations, while time_recorded preserves the digits actually supplied by each file.

In R, read_trial_file() reads all fields as text, with empty fields as NA and no trimming. A Participant header selects the old-format branch. rename(all_of(old_to_canonical)) uses a named vector whose names are canonical fields and values are old fields. In the new-format branch, new_to_canonical renames only correct and timestamp, because the other new names are already canonical.

The function converts times with dmy_hms() for old files and ymd_hms() for new ones, both with tz = "Asia/Seoul", and applies the correctness map with recode_values(). It also records version, file, and source-row position. The check after the function compares the column names across formats, then inspects the converted values for block 1, trial 1 in each file. %OS3 makes milliseconds visible in the displayed times.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
old_to_canonical <- c(
  participant = "Participant",
  session = "Session",
  block = "Block",
  trial = "Trial",
  trial_type = "TrialType",
  stim = "Stim",
  resp = "Resp",
  correct_recorded = "Correct",
  rt = "RT_ms",
  time_recorded = "Time",
  response_json = "Survey"
)
new_to_canonical <- c(correct_recorded = "correct", time_recorded = "timestamp")
read_trial_file <- function(path) {
  records <- read_csv(
    path,
    col_types = cols(.default = col_character()),
    na = "",
    trim_ws = FALSE
  )
  if ("Participant" %in% names(records)) {
    records <- records |>
      rename(all_of(old_to_canonical)) |>
      mutate(version = "old", onset = dmy_hms(time_recorded, tz = "Asia/Seoul"))
  } else {
    records <- records |>
      rename(all_of(new_to_canonical)) |>
      mutate(version = "new", onset = ymd_hms(time_recorded, tz = "Asia/Seoul"))
  }
  records |>
    mutate(file = basename(path), source_row = row_number(), .before = 1) |>
    mutate(
      correct = recode_values(
        correct_recorded,
        from = c("True", "False", "1", "0"),
        to = c(1L, 0L, 1L, 0L)
      )
    )
}
old_trials <- read_trial_file("data/raw/trials/sub-001_ses-1.csv")
new_trials <- read_trial_file("data/raw/trials/sub-006_ses-1.csv")
identical(names(old_trials), names(new_trials))
first_trials <- bind_rows(old_trials, new_trials) |>
  filter(block == "1", trial == "1")
select(first_trials, file, source_row, version, correct_recorded, correct)
select(first_trials, file, source_row, time_recorded, onset)
format(first_trials$onset, "%H:%M:%OS3")
1
2
3
4
5
6
7
8
9
10
11
12
[1] TRUE
# A tibble: 2 × 5
  file              source_row version correct_recorded correct
  <chr>                  <int> <chr>   <chr>              <int>
1 sub-001_ses-1.csv          9 old     True                   1
2 sub-006_ses-1.csv          9 new     1                      1
# A tibble: 2 × 4
  file              source_row time_recorded           onset              
  <chr>                  <int> <chr>                   <dttm>             
1 sub-001_ses-1.csv          9 26/03/2024 09:55:11     2024-03-26 09:55:11
2 sub-006_ses-1.csv          9 2024-03-15 12:25:08.549 2024-03-15 12:25:08
[1] "09:55:11.000" "12:25:08.549"

The two tables have the same column names. At block 1, trial 1, both True and 1 convert to integer 1. The old time displays as 09:55:11.000 even though time_recorded ends at 09:55:11. Only the newer file records the fraction shown in its output, .549.

Recording each import outcome

The reader now returns comparable records from either format. Applying it across the inventory also requires a record of any failure, distinct from the zero-byte files already identified. attempt_read() therefore returns a list with a status, the records, and a diagnostic.

tryCatch() runs the read expression and calls its error function if the expression signals an error. After success, the status is read, the records are the table, and the diagnostic is missing. After failure, the status is failed read, the records are NULL, and conditionMessage() supplies the diagnostic. The deliberately nonexistent sub-099_ses-1.csv exercises the failure case without adding a file to the inventory.

1
2
3
4
5
6
7
8
9
10
11
attempt_read <- function(path) {
  tryCatch(
    list(status = "read", records = read_trial_file(path), diagnostic = NA_character_),
    error = function(e) {
      list(status = "failed read", records = NULL, diagnostic = conditionMessage(e))
    }
  )
}
test_attempt <- attempt_read("data/raw/trials/sub-099_ses-1.csv")
test_attempt$status
test_attempt$diagnostic
1
2
[1] "failed read"
[1] "'data/raw/trials/sub-099_ses-1.csv' does not exist in current working\ndirectory: '/Users/alex/Documents/book'."

The failed-read diagnostic identifies the missing path. Its working-directory text will vary by computer. This attempted failure is distinct from a zero-byte source identified by the earlier size check.

The inventory can now distinguish three outcomes: verified empty, read, and failed read. map2() applies a function to each path and size, assigning verified empty to zero-byte files and passing the other paths to attempt_read(). map_chr() and map_int() collect the outcomes, and NROW(NULL) gives zero for an attempt that returned no table.

bind_rows() combines the returned tables, skipping NULL. To check that all imported rows are represented once, we compare the inventory’s row total, the combined table’s height, and its distinct file/row count. The inventory separately accounts for files that contributed no rows.

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
attempts <- map2(inventory$path, inventory$bytes, \(path, bytes) {
  if (bytes == 0) {
    list(status = "verified empty", records = NULL, diagnostic = NA_character_)
  } else {
    attempt_read(path)
  }
})
inventory <- inventory |>
  mutate(
    status = map_chr(attempts, \(attempt) attempt$status),
    rows = map_int(attempts, \(attempt) NROW(attempt$records)),
    diagnostic = map_chr(attempts, \(attempt) attempt$diagnostic)
  )
count(inventory, status)
inventory |>
  filter(file %in% example_files) |>
  select(file, bytes, status, rows, diagnostic)
trials <- bind_rows(map(attempts, \(attempt) attempt$records))
c(
  considered = nrow(inventory),
  rows = sum(inventory$rows),
  combined = nrow(trials),
  sources = n_distinct(trials$file, trials$source_row),
  diagnostics = sum(!is.na(inventory$diagnostic))
)
trials |>
  group_by(version) |>
  summarise(files = n_distinct(file), rows = n())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# A tibble: 2 × 2
  status             n
  <chr>          <int>
1 read              42
2 verified empty     1
# A tibble: 4 × 5
  file              bytes status          rows diagnostic
  <chr>             <dbl> <chr>          <int> <chr>     
1 sub-001_ses-1.csv 12121 read             201 <NA>      
2 sub-006_ses-1.csv 12351 read             201 <NA>      
3 sub-007_ses-1.csv  3487 read              56 <NA>      
4 sub-041_ses-1.csv     0 verified empty     0 <NA>      
 considered        rows    combined     sources diagnostics 
         43        8152        8152        8152           0 
# A tibble: 2 × 3
  version files  rows
  <chr>   <int> <int>
1 new        37  7147
2 old         5  1005

Of the 43 files, 42 were read and one was verified empty. No file in the inventory failed to read. The 56 rows from sub-007_ses-1.csv are eight practice trials and 48 test trials, so read can describe an incomplete run. The five old and 37 new exports contribute 8,152 rows. Each row has a distinct pair of file and source_row.

pl.read_csv() with infer_schema=False reads both formats as text. A Participant header identifies an old file, and rename() maps its field names to the common names. Only correct and timestamp need renaming in new files.

replace_strict() converts the correctness codes, and str.to_datetime() parses each time format with the same millisecond unit and Asia/Seoul zone. with_row_index() numbers records within each file, while pl.lit() adds the file name and version. The subsequent checks compare the schemas and inspect the converted values for block 1, trial 1 in each file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
old_to_canonical = {
    "Participant": "participant",
    "Session": "session",
    "Block": "block",
    "Trial": "trial",
    "TrialType": "trial_type",
    "Stim": "stim",
    "Resp": "resp",
    "Correct": "correct_recorded",
    "RT_ms": "rt",
    "Time": "time_recorded",
    "Survey": "response_json",
}
new_to_canonical = {"correct": "correct_recorded", "timestamp": "time_recorded"}
correct_codes = {"True": 1, "False": 0, "1": 1, "0": 0}


def read_trial_file(path):
    records = pl.read_csv(path, infer_schema=False)
    if "Participant" in records.columns:
        version = "old"
        records = records.rename(old_to_canonical)
        time_format = "%d/%m/%Y %H:%M:%S"
    else:
        version = "new"
        records = records.rename(new_to_canonical)
        time_format = "%Y-%m-%d %H:%M:%S%.3f"
    return records.with_row_index("source_row", offset=1).with_columns(
        file=pl.lit(Path(path).name),
        version=pl.lit(version),
        onset=pl.col("time_recorded").str.to_datetime(time_format, time_unit="ms", time_zone="Asia/Seoul"),
        correct=pl.col("correct_recorded").replace_strict(
            correct_codes, default=None, return_dtype=pl.Int64
        ),
    )


old_trials = read_trial_file("data/raw/trials/sub-001_ses-1.csv")
new_trials = read_trial_file("data/raw/trials/sub-006_ses-1.csv")
old_trials.schema == new_trials.schema
first_trials = pl.concat([old_trials, new_trials], how="vertical").filter(
    (pl.col("block") == "1") & (pl.col("trial") == "1")
)
first_trials.select("file", "source_row", "version", "correct_recorded", "correct")
first_trials.select("file", "source_row", "time_recorded", "onset")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
True
shape: (2, 5)
┌───────────────────┬────────────┬─────────┬──────────────────┬─────────┐
│ file              ┆ source_row ┆ version ┆ correct_recorded ┆ correct │
│ ---               ┆ ---        ┆ ---     ┆ ---              ┆ ---     │
│ str               ┆ u32        ┆ str     ┆ str              ┆ i64     │
╞═══════════════════╪════════════╪═════════╪══════════════════╪═════════╡
│ sub-001_ses-1.csv ┆ 9          ┆ old     ┆ True             ┆ 1       │
│ sub-006_ses-1.csv ┆ 9          ┆ new     ┆ 1                ┆ 1       │
└───────────────────┴────────────┴─────────┴──────────────────┴─────────┘
shape: (2, 4)
┌───────────────────┬────────────┬─────────────────────────┬─────────────────────────────┐
│ file              ┆ source_row ┆ time_recorded           ┆ onset                       │
│ ---               ┆ ---        ┆ ---                     ┆ ---                         │
│ str               ┆ u32        ┆ str                     ┆ datetime[ms, Asia/Seoul]    │
╞═══════════════════╪════════════╪═════════════════════════╪═════════════════════════════╡
│ sub-001_ses-1.csv ┆ 9          ┆ 26/03/2024 09:55:11     ┆ 2024-03-26 09:55:11 KST     │
│ sub-006_ses-1.csv ┆ 9          ┆ 2024-03-15 12:25:08.549 ┆ 2024-03-15 12:25:08.549 KST │
└───────────────────┴────────────┴─────────────────────────┴─────────────────────────────┘

The two schemas match. For the old trial, time_recorded ends at 09:55:11. The Polars column can represent milliseconds, but the old file gives no fraction of a second for this trial. The new file records .549.

Recording each import outcome

The reader now returns comparable records from either format. Applying it across the inventory also requires a record of any failure, distinct from a verified empty file. attempt_read() returns the status read with a table after success, or failed read with a diagnostic after failure.

The handler uses try/except: Python runs the try block and, if one of the listed exception types is raised there, runs the except block instead. The clause as error names the exception. pl.exceptions.PolarsError covers Polars errors and OSError covers filesystem errors. The diagnostic combines type(error).__name__ with the message. The deliberately nonexistent sub-099_ses-1.csv tests a missing path outside the inventory.

1
2
3
4
5
6
7
8
9
10
11
def attempt_read(path):
    try:
        return {"status": "read", "records": read_trial_file(path), "diagnostic": None}
    except (pl.exceptions.PolarsError, OSError) as error:
        diagnostic = type(error).__name__ + ": " + str(error)
        return {"status": "failed read", "records": None, "diagnostic": diagnostic}


test_attempt = attempt_read("data/raw/trials/sub-099_ses-1.csv")
test_attempt["status"]
test_attempt["diagnostic"]
1
2
'failed read'
'FileNotFoundError: No such file or directory (os error 2): data/raw/trials/sub-099_ses-1.csv'

The handler returns failed read with a FileNotFoundError naming the path.

The inventory can now distinguish three outcomes: verified empty, read, and failed read. zip() pairs paths with sizes. The loop records verified empty for zero bytes and otherwise stores the attempt_read() result. pl.Series() adds statuses, counts, and diagnostics to the inventory.

Only returned tables are stacked. To check that all imported rows are represented once, we compare their combined height with the inventory’s row total and the count of distinct file/row pairs. Files that contribute no rows remain visible in the inventory.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
attempts = []
for path, size in zip(inventory["path"], inventory["bytes"]):
    if size == 0:
        attempts.append(
            {"status": "verified empty", "records": None, "diagnostic": None}
        )
    else:
        attempts.append(attempt_read(path))

inventory = inventory.with_columns(
    status=pl.Series([attempt["status"] for attempt in attempts]),
    rows=pl.Series(
        [
            0 if attempt["records"] is None else attempt["records"].height
            for attempt in attempts
        ]
    ),
    diagnostic=pl.Series(
        [attempt["diagnostic"] for attempt in attempts], dtype=pl.String
    ),
)
inventory.group_by("status").agg(n=pl.len()).sort("status")
inventory.filter(pl.col("file").is_in(example_files)).select(
    "file", "bytes", "status", "rows", "diagnostic"
)
trials = pl.concat(
    [attempt["records"] for attempt in attempts if attempt["records"] is not None],
    how="vertical",
)
(
    inventory.height,
    inventory["rows"].sum(),
    trials.height,
    trials.select("file", "source_row").n_unique(),
    inventory["diagnostic"].is_not_null().sum(),
)
trials.group_by("version").agg(files=pl.col("file").n_unique(), rows=pl.len()).sort(
    "version"
)
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
shape: (2, 2)
┌────────────────┬─────┐
│ status         ┆ n   │
│ ---            ┆ --- │
│ str            ┆ u32 │
╞════════════════╪═════╡
│ read           ┆ 42  │
│ verified empty ┆ 1   │
└────────────────┴─────┘
shape: (4, 5)
┌───────────────────┬───────┬────────────────┬──────┬────────────┐
│ file              ┆ bytes ┆ status         ┆ rows ┆ diagnostic │
│ ---               ┆ ---   ┆ ---            ┆ ---  ┆ ---        │
│ str               ┆ i64   ┆ str            ┆ i64  ┆ str        │
╞═══════════════════╪═══════╪════════════════╪══════╪════════════╡
│ sub-001_ses-1.csv ┆ 12121 ┆ read           ┆ 201  ┆ null       │
│ sub-006_ses-1.csv ┆ 12351 ┆ read           ┆ 201  ┆ null       │
│ sub-007_ses-1.csv ┆ 3487  ┆ read           ┆ 56   ┆ null       │
│ sub-041_ses-1.csv ┆ 0     ┆ verified empty ┆ 0    ┆ null       │
└───────────────────┴───────┴────────────────┴──────┴────────────┘
(43, 8152, 8152, 8152, 0)
shape: (2, 3)
┌─────────┬───────┬──────┐
│ version ┆ files ┆ rows │
│ ---     ┆ ---   ┆ ---  │
│ str     ┆ u32   ┆ u32  │
╞═════════╪═══════╪══════╡
│ new     ┆ 37    ┆ 7147 │
│ old     ┆ 5     ┆ 1005 │
└─────────┴───────┴──────┘

Of the 43 files, 42 were read, one was verified empty, and none failed to read. The 8,152 combined rows have 8,152 distinct pairs of file and source_row. The zero-byte file has an inventory row and no row in trials.

The 56 rows for sub-007_ses-1.csv include eight practice trials and 48 test trials. Its successful import therefore does not establish that the participant completed the run. File readability and completeness of the recorded task require different checks.

16.5 Comparing representations without inventing precision

The combined table preserves both converted values and their recorded text. We can use that distinction to compare it with the practice file at the precision the sources actually provide. One trial begins at 09:55:11 in an old export and 09:55:11.927 in the practice file. Because the old format recorded only whole seconds, the unequal strings alone do not establish a disagreement.

We first select the same participants in both sources. %in% in R and is_in() in Polars restrict data/practice/trials.csv to the participants in the old exports.

1
2
3
4
5
6
7
8
9
old_exports <- filter(trials, version == "old")
practice_trials <- read_csv(
  "data/practice/trials.csv",
  col_types = cols(.default = col_character()),
  na = "",
  trim_ws = FALSE
) |>
  filter(participant %in% old_exports$participant)
c(old = nrow(old_exports), practice = nrow(practice_trials))
1
2
     old practice 
    1005     1005 
1
2
3
4
5
old_exports = trials.filter(pl.col("version") == "old")
practice_trials = pl.read_csv("data/practice/trials.csv", infer_schema=False).filter(
    pl.col("participant").is_in(old_exports["participant"].unique().to_list())
)
(old_exports.height, practice_trials.height)
1
(1005, 1005)

Each source has 1,005 records, but matching them requires two keys. Keyboard rows use participant, session, block, and trial. Each completed run also has one questionnaire, with no block or trial. Its key is participant, session, and row type.

If we use the keyboard key for every row, the questionnaire match depends on two blank fields. By default, dplyr::inner_join() matches missing keys, and na_matches = "never" prevents that match. A Polars join() excludes null-key matches by default. In the dplyr result, .x identifies the row type from the first table.

1
2
3
4
trial_keys <- join_by(participant, session, block, trial)
missing_keys <- inner_join(old_exports, practice_trials, by = trial_keys)
count(missing_keys, trial_type.x)
nrow(inner_join(old_exports, practice_trials, by = trial_keys, na_matches = "never"))
1
2
3
4
5
6
# A tibble: 2 × 2
  trial_type.x     n
  <chr>        <int>
1 keyboard      1000
2 survey           5
[1] 1000
1
2
trial_keys = ["participant", "session", "block", "trial"]
old_exports.join(practice_trials, on=trial_keys).height
1
1000

The default dplyr join pairs five questionnaires because their participant and session match and both trial fields are missing on each side. Excluding missing-key matches gives only the 1,000 keyboard records in both languages. Matching questionnaires separately lets us use the fields that actually identify them.

At 09:55:11.927, dropping the fraction gives 09:55:11, while rounding gives 09:55:12. Which rule reproduces the whole seconds in the old exports? For each rule, we can count how many practice timestamps differ from their counterparts in the old export.

The separate joins now use the appropriate key for each row type: trial_keys for keyboard trials, and participant, session, and trial_type for questionnaires. Both use relationship = "one-to-one" to detect multiple matches. Suffixes identify the two sources, and the counts show whether every record found a counterpart before we compare values.

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
keyboard_pairs <- inner_join(
  filter(old_exports, trial_type == "keyboard"),
  filter(practice_trials, trial_type == "keyboard"),
  by = trial_keys,
  relationship = "one-to-one",
  suffix = c("_old", "_practice")
)
questionnaire_pairs <- inner_join(
  filter(old_exports, trial_type == "survey"),
  filter(practice_trials, trial_type == "survey"),
  by = join_by(participant, session, trial_type),
  relationship = "one-to-one",
  suffix = c("_old", "_practice")
)
count(old_exports, trial_type, name = "old") |>
  left_join(
    count(practice_trials, trial_type, name = "practice"),
    by = join_by(trial_type)
  ) |>
  mutate(
    matched = if_else(
      trial_type == "keyboard",
      nrow(keyboard_pairs),
      nrow(questionnaire_pairs)
    )
  )
1
2
3
4
5
# A tibble: 2 × 4
  trial_type   old practice matched
  <chr>      <int>    <int>   <int>
1 keyboard    1000     1000    1000
2 survey         5        5       5

All 1,000 keyboard records and five questionnaires in each source have exactly one counterpart. The field comparisons can therefore include every intended record.

ymd_hms() reads practice times in the Asia/Seoul source zone. floor_date(..., "second") truncates them to the second, giving practice_second for comparison with onset; round_date() supplies the nearest-second alternative. The example pair shows exactly which seconds are compared.

The summaries also compare the other recorded fields. Practice correctness is converted to an integer, and vctrs::vec_equal(..., na_equal = TRUE) treats paired missing responses or response times as equal.

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
keyboard_pairs <- keyboard_pairs |>
  mutate(
    practice_onset = ymd_hms(timestamp, tz = "Asia/Seoul"),
    practice_second = floor_date(practice_onset, "second"),
    same_second = practice_second == onset
  )
keyboard_pairs |>
  filter(participant == "sub-001", block == "1", trial == "1") |>
  select(time_recorded, timestamp, practice_second, same_second)
keyboard_pairs |>
  summarise(
    pairs = n(),
    stim = sum(stim_old != stim_practice),
    resp = sum(!vctrs::vec_equal(resp_old, resp_practice, na_equal = TRUE)),
    correct = sum(correct_old != as.integer(correct_practice)),
    rt = sum(!vctrs::vec_equal(rt_old, rt_practice, na_equal = TRUE)),
    second = sum(!same_second),
    rounded = sum(round_date(practice_onset, "second") != onset)
  )
questionnaire_pairs |>
  summarise(
    pairs = n(),
    rt = sum(rt_old != rt_practice),
    json = sum(response_json_old != response_json_practice),
    second = sum(floor_date(ymd_hms(timestamp, tz = "Asia/Seoul"), "second") != onset)
  )
1
2
3
4
5
6
7
8
9
10
11
12
# A tibble: 1 × 4
  time_recorded       timestamp               practice_second     same_second
  <chr>               <chr>                   <dttm>              <lgl>      
1 26/03/2024 09:55:11 2024-03-26 09:55:11.927 2024-03-26 09:55:11 TRUE       
# A tibble: 1 × 7
  pairs  stim  resp correct    rt second rounded
  <int> <int> <int>   <int> <int>  <int>   <int>
1  1000     0     0       0     0      0     485
# A tibble: 1 × 4
  pairs    rt  json second
  <int> <int> <int>  <int>
1     5     0     0      0

For the practice time ending in .927, truncation gives 09:55:11 and rounding gives 09:55:12. Truncation matches all 1,000 old keyboard timestamps. Rounding disagrees on 485. Stimuli, responses, correctness, and response times agree across those pairs. All five questionnaire pairs agree on response time, JSON text, and time to the second.

Each row type has its own join key. In Polars’ join(), validate="1:1" checks uniqueness and suffix="_practice" identifies fields from the practice table when names repeat. For each type, group_by() with pl.len() counts the source rows and pl.when() places the corresponding matched count beside them.

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
keyboard_pairs = old_exports.filter(pl.col("trial_type") == "keyboard").join(
    practice_trials.filter(pl.col("trial_type") == "keyboard"),
    on=trial_keys,
    validate="1:1",
    suffix="_practice",
)
questionnaire_pairs = old_exports.filter(pl.col("trial_type") == "survey").join(
    practice_trials.filter(pl.col("trial_type") == "survey"),
    on=["participant", "session", "trial_type"],
    validate="1:1",
    suffix="_practice",
)
(
    old_exports.group_by("trial_type")
    .agg(old=pl.len())
    .join(
        practice_trials.group_by("trial_type").agg(practice=pl.len()),
        on="trial_type",
    )
    .with_columns(
        matched=pl.when(pl.col("trial_type") == "keyboard")
        .then(keyboard_pairs.height)
        .otherwise(questionnaire_pairs.height)
    )
    .sort("trial_type")
)
1
2
3
4
5
6
7
8
9
shape: (2, 4)
┌────────────┬──────┬──────────┬─────────┐
│ trial_type ┆ old  ┆ practice ┆ matched │
│ ---        ┆ ---  ┆ ---      ┆ ---     │
│ str        ┆ u32  ┆ u32      ┆ i32     │
╞════════════╪══════╪══════════╪═════════╡
│ keyboard   ┆ 1000 ┆ 1000     ┆ 1000    │
│ survey     ┆ 5    ┆ 5        ┆ 5       │
└────────────┴──────┴──────────┴─────────┘

With the two keys, all 1,000 keyboard rows and five questionnaires are matched. Null trial fields no longer exclude the questionnaire records.

str.to_datetime() reads practice timestamps with the same millisecond type and Asia/Seoul zone as onset. dt.truncate("1s") derives whole-second values, while dt.round("1s") gives the alternative. For field comparisons, eq_missing() treats paired nulls as equal and cast(pl.Int64) aligns the correctness representation.

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
millisecond_format = "%Y-%m-%d %H:%M:%S%.3f"
keyboard_pairs = keyboard_pairs.with_columns(
    practice_onset=pl.col("timestamp").str.to_datetime(
        millisecond_format, time_unit="ms", time_zone="Asia/Seoul"
    )
).with_columns(
    practice_second=pl.col("practice_onset").dt.truncate("1s"),
).with_columns(same_second=pl.col("practice_second") == pl.col("onset"))
keyboard_pairs.filter(
    (pl.col("participant") == "sub-001")
    & (pl.col("block") == "1")
    & (pl.col("trial") == "1")
).select("time_recorded", "timestamp", "practice_second", "same_second")
keyboard_pairs.select(
    pairs=pl.len(),
    stim=(pl.col("stim") != pl.col("stim_practice")).sum(),
    resp=(~pl.col("resp").eq_missing(pl.col("resp_practice"))).sum(),
    correct=(pl.col("correct") != pl.col("correct_practice").cast(pl.Int64)).sum(),
    rt=(~pl.col("rt").eq_missing(pl.col("rt_practice"))).sum(),
    second=(~pl.col("same_second")).sum(),
    rounded=(pl.col("practice_onset").dt.round("1s") != pl.col("onset")).sum(),
)
questionnaire_pairs.select(
    pairs=pl.len(),
    rt=(pl.col("rt") != pl.col("rt_practice")).sum(),
    json=(pl.col("response_json") != pl.col("response_json_practice")).sum(),
    second=(
        pl.col("timestamp")
        .str.to_datetime(millisecond_format, time_unit="ms", time_zone="Asia/Seoul")
        .dt.truncate("1s")
        != pl.col("onset")
    ).sum(),
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
shape: (1, 4)
┌─────────────────────┬─────────────────────────┬──────────────────────────┬─────────────┐
│ time_recorded       ┆ timestamp               ┆ practice_second          ┆ same_second │
│ ---                 ┆ ---                     ┆ ---                      ┆ ---         │
│ str                 ┆ str                     ┆ datetime[ms, Asia/Seoul] ┆ bool        │
╞═════════════════════╪═════════════════════════╪══════════════════════════╪═════════════╡
│ 26/03/2024 09:55:11 ┆ 2024-03-26 09:55:11.927 ┆ 2024-03-26 09:55:11 KST  ┆ true        │
└─────────────────────┴─────────────────────────┴──────────────────────────┴─────────────┘
shape: (1, 7)
┌───────┬──────┬──────┬─────────┬─────┬────────┬─────────┐
│ pairs ┆ stim ┆ resp ┆ correct ┆ rt  ┆ second ┆ rounded │
│ ---   ┆ ---  ┆ ---  ┆ ---     ┆ --- ┆ ---    ┆ ---     │
│ u32   ┆ u32  ┆ u32  ┆ u32     ┆ u32 ┆ u32    ┆ u32     │
╞═══════╪══════╪══════╪═════════╪═════╪════════╪═════════╡
│ 1000  ┆ 0    ┆ 0    ┆ 0       ┆ 0   ┆ 0      ┆ 485     │
└───────┴──────┴──────┴─────────┴─────┴────────┴─────────┘
shape: (1, 4)
┌───────┬─────┬──────┬────────┐
│ pairs ┆ rt  ┆ json ┆ second │
│ ---   ┆ --- ┆ ---  ┆ ---    │
│ u32   ┆ u32 ┆ u32  ┆ u32    │
╞═══════╪═════╪══════╪════════╡
│ 5     ┆ 0   ┆ 0    ┆ 0      │
└───────┴─────┴──────┴────────┘

The second and rounded columns count keyboard pairs whose timestamps disagree. Across 1,000 pairs, dropping the milliseconds gives zero disagreements. Rounding gives 485. The five questionnaire pairs agree on response time, the JSON text of the answers, and the timestamp to the second. The .927 is available only in the practice record of the example trial.

Survey codes and labels

The timestamp comparison allowed for different recording precision. Survey answers require a different correspondence: the workbook records words or text codes where SPSS records numbers. We compared five selected submissions in Section 16.2; we can now check all twenty items on every form. One form, for example, uses Strongly agree on SAT_4 and Strongly Agree on SAT_5. Both spellings should correspond to the same agreement code.

Each item entry is identified by ResponseId and item. In R, pivot_longer() creates one row per entry. The five standard labels map to codes from 1 to 5, and the spelling variant also maps to 5. Text -99, 0, and 6 maps to the corresponding numeric codes; blanks remain missing. The kind column distinguishes labels, spelling variants, text codes, and blanks so that we can inspect agreement for each representation.

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
items <- c(paste0("SAT_", 1:10), paste0("STR_", 1:10))
agreement_labels <- c(
  "Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"
)
text_to_code <- tibble(
  text = c(agreement_labels, "Strongly Agree", "-99", "0", "6"),
  text_code = c(1:5, 5, -99, 0, 6)
)
sav_items <- survey_codes |>
  select(ResponseId, all_of(items)) |>
  pivot_longer(-ResponseId, names_to = "item", values_to = "code")
xlsx_items <- survey |>
  select(ResponseId, all_of(items)) |>
  pivot_longer(-ResponseId, names_to = "item", values_to = "text") |>
  left_join(text_to_code, by = join_by(text))
item_pairs <- inner_join(
  sav_items,
  xlsx_items,
  by = join_by(ResponseId, item),
  relationship = "one-to-one"
) |>
  mutate(
    kind = case_when(
      is.na(text) ~ "blank",
      text %in% agreement_labels ~ "label",
      text == "Strongly Agree" ~ "label variant",
      .default = "code as text"
    ),
    agree = vctrs::vec_equal(code, text_code, na_equal = TRUE)
  )
item_pairs |>
  filter(ResponseId == "R_95DSbCu9tEU4", item %in% c("SAT_4", "SAT_5"))
count(item_pairs, kind, agree)
1
2
3
4
5
6
7
8
9
10
11
12
# A tibble: 2 × 7
  ResponseId     item   code text           text_code kind          agree
  <chr>          <chr> <dbl> <chr>              <dbl> <chr>         <lgl>
1 R_95DSbCu9tEU4 SAT_4     5 Strongly agree         5 label         TRUE 
2 R_95DSbCu9tEU4 SAT_5     5 Strongly Agree         5 label variant TRUE 
# A tibble: 4 × 3
  kind          agree     n
  <chr>         <lgl> <int>
1 blank         TRUE    211
2 code as text  TRUE     47
3 label         TRUE   9798
4 label variant TRUE      4

The two spellings on this submission both match SPSS code 5. All 10,060 pairs agree, including the 47 workbook entries written as codes. Agreement on a refusal or an invalid code tells us how the two files recorded the answer. Neither can be used as an agreement rating.

In Polars, unpivot() makes one row per submission and item in each table. The text_to_code table maps workbook text to numbers. Joining on ResponseId and item pairs the two entries, and validate="1:1" checks the keys for duplicates. eq_missing() treats paired nulls as equal. Grouping by kind and agree shows which representations match.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
items = ["SAT_" + str(number) for number in range(1, 11)] + [
    "STR_" + str(number) for number in range(1, 11)
]
agreement_labels = [
    "Strongly disagree",
    "Disagree",
    "Neutral",
    "Agree",
    "Strongly agree",
]
text_to_code = pl.DataFrame(
    {
        "text": agreement_labels + ["Strongly Agree", "-99", "0", "6"],
        "text_code": [1.0, 2.0, 3.0, 4.0, 5.0, 5.0, -99.0, 0.0, 6.0],
    }
)
sav_items = survey_sav.select(["ResponseId"] + items).unpivot(
    on=items, index="ResponseId", variable_name="item", value_name="code"
)
xlsx_items = (
    survey.select(["ResponseId"] + items)
    .unpivot(on=items, index="ResponseId", variable_name="item", value_name="text")
    .join(text_to_code, on="text", how="left")
)
item_pairs = sav_items.join(
    xlsx_items, on=["ResponseId", "item"], validate="1:1"
).with_columns(
    kind=pl.when(pl.col("text").is_null())
    .then(pl.lit("blank"))
    .when(pl.col("text").is_in(agreement_labels))
    .then(pl.lit("label"))
    .when(pl.col("text") == "Strongly Agree")
    .then(pl.lit("label variant"))
    .otherwise(pl.lit("code as text")),
    agree=pl.col("code").eq_missing(pl.col("text_code")),
)
item_pairs.filter(
    (pl.col("ResponseId") == "R_95DSbCu9tEU4")
    & pl.col("item").is_in(["SAT_4", "SAT_5"])
).sort("item")
item_pairs.group_by("kind", "agree").agg(n=pl.len()).sort("kind")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
shape: (2, 7)
┌────────────────┬───────┬──────┬────────────────┬───────────┬───────────────┬───────┐
│ ResponseId     ┆ item  ┆ code ┆ text           ┆ text_code ┆ kind          ┆ agree │
│ ---            ┆ ---   ┆ ---  ┆ ---            ┆ ---       ┆ ---           ┆ ---   │
│ str            ┆ str   ┆ f64  ┆ str            ┆ f64       ┆ str           ┆ bool  │
╞════════════════╪═══════╪══════╪════════════════╪═══════════╪═══════════════╪═══════╡
│ R_95DSbCu9tEU4 ┆ SAT_4 ┆ 5.0  ┆ Strongly agree ┆ 5.0       ┆ label         ┆ true  │
│ R_95DSbCu9tEU4 ┆ SAT_5 ┆ 5.0  ┆ Strongly Agree ┆ 5.0       ┆ label variant ┆ true  │
└────────────────┴───────┴──────┴────────────────┴───────────┴───────────────┴───────┘
shape: (4, 3)
┌───────────────┬───────┬──────┐
│ kind          ┆ agree ┆ n    │
│ ---           ┆ ---   ┆ ---  │
│ str           ┆ bool  ┆ u32  │
╞═══════════════╪═══════╪══════╡
│ blank         ┆ true  ┆ 211  │
│ code as text  ┆ true  ┆ 47   │
│ label         ┆ true  ┆ 9798 │
│ label variant ┆ true  ┆ 4    │
└───────────────┴───────┴──────┘

All 10,060 entries match across the two exports. The workbook contains 9,798 standard labels, four instances of Strongly Agree, 47 codes written as text, and 211 blanks. A match for -99, for example, confirms that both files recorded a refusal; it does not make that value an agreement rating.

Across these sources, a faithful import depends on identifying the observations, interpreting values with the source’s conventions, and checking the resulting records against their origin. Those checks establish what was recorded. The next task is to decide which recorded values can support each description of the data.

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