Post

Preparing Survey Responses

One person can submit two survey forms, and each form can contain several answers contributing to a satisfaction or stress score. To produce one row per participant, we need to decide which submission to use and which of its answers can be scored. The workbook and SPSS exports provide complementary descriptions of those answers. This chapter first reconciles the exports and distinguishes valid responses from missing or uninterpretable values. We then select submissions, examine response-quality flags, and calculate scale scores under explicit rules. The resulting participant table remains linked to the response and item records that explain each score or its absence.

20.1 Reconciling two exports of the same responses

The workbook data/raw/survey/survey_raw.xlsx and the SPSS file data/raw/survey/survey_raw.sav describe the same survey submissions. The workbook gives each answer as it was written, while the SPSS file gives numeric codes with their labels and declared missing values. Interpreting an answer can require both, so each workbook row has to be paired with the right SPSS row.

ID identifies a participant. If someone submitted twice, even a correctly formatted ID would match each of their two workbook rows to both SPSS rows. ResponseId identifies one submission, so it pairs each workbook row with its counterpart. We can then compare the participant IDs on that pair.

Table 20.1 maps the corresponding fields. Some differ only in name, while others use different representations. Agreement labels in the workbook, for example, correspond to labeled numeric codes in SPSS. The multiple-response question needs separate treatment because its single workbook field corresponds to eight indicator columns, each marking whether its option was chosen.

Table 20.1. Corresponding fields of the two survey exports.

Workbook fieldSPSS variableWorkbook formSPSS form
ResponseIdResponseIdtext keytext key
IDIDnumber, such as 7four characters, such as 0007
Start Date, End DateStartDate, EndDateclock readings as textdate-times
Birth YearBirthYearnumber, 999 for no answernumber, 999 declared missing
Duration (in seconds)Durationsecondsseconds
Gender, Regionsame nameslabel textcodes with value labels
SAT_1 to SAT_10, STR_1 to STR_10same namesagreement labels, -99, blanks, 0, 6labeled codes 1 to 5, −99 declared missing, system-missing values, unlabeled 0 and 6
ATTN_1ATTN_1agreement labels or a blanklabeled codes 1 to 5, system-missing for the blank
Q_MULTIQ_MULTI_1 to Q_MULTI_8chosen codes joined by ;one indicator per option
Q_OPENQ_OPENtext, blank for no answertext, empty for no answer
FinishedFinishedTRUE or FALSE1 or 0 with labels

The Responses sheet has column names in row 1, question text in row 2, and submissions from row 3 onward. Using the names from row 1 in col_names, readxl::read_excel() reads the question row with skip = 1 and n_max = 1. For the responses, skip = 2 starts at row 3, and trim_ws = FALSE reads the trailing space in Male . The outputs show one submission’s STR_1 answer and the wording of that question.

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
library(tidyverse)
library(readxl)
library(haven)
xlsx_path <- "data/raw/survey/survey_raw.xlsx"
sav_path <- "data/raw/survey/survey_raw.sav"
survey_names <- names(read_excel(xlsx_path, sheet = "Responses", n_max = 0))
question_text <- read_excel(
  xlsx_path,
  sheet = "Responses",
  col_names = survey_names,
  skip = 1,
  n_max = 1,
  col_types = "text",
  trim_ws = FALSE
) |>
  pivot_longer(everything(), names_to = "variable", values_to = "question")
xlsx_responses <- read_excel(
  xlsx_path,
  sheet = "Responses",
  col_names = survey_names,
  skip = 2,
  trim_ws = FALSE
)
dim(xlsx_responses)
xlsx_responses |>
  filter(ResponseId == "R_D7sLfnz61bpc") |>
  select(ResponseId, ID, `End Date`, STR_1, Finished)
filter(question_text, variable == "STR_1")
1
2
3
4
5
6
7
8
9
[1] 503  32
# A tibble: 1 × 5
  ResponseId        ID `End Date`          STR_1          Finished
  <chr>          <dbl> <chr>               <chr>          <chr>   
1 R_D7sLfnz61bpc     7 2024-04-19 10:00:55 Strongly agree TRUE    
# A tibble: 1 × 2
  variable question                                                   
  <chr>    <chr>                                                      
1 STR_1    In the past month, I felt rushed by the things I had to do.

In haven::read_sav(), user_na = TRUE makes the recorded −99 available alongside the SPSS declaration that it is missing. For STR_1, label gives the question, labels gives the code meanings, and na_values lists the declared missing codes. rename() uses sav_to_xlsx to give four SPSS fields their workbook names.

1
2
3
4
5
6
7
8
9
10
11
12
sav_responses <- read_sav(sav_path, user_na = TRUE)
dim(sav_responses)
attr(sav_responses$STR_1, "label")
attr(sav_responses$STR_1, "labels")
attr(sav_responses$STR_1, "na_values")
sav_to_xlsx <- c(
  `Start Date` = "StartDate",
  `End Date` = "EndDate",
  `Birth Year` = "BirthYear",
  `Duration (in seconds)` = "Duration"
)
sav_keyed <- rename(sav_responses, all_of(sav_to_xlsx))
1
2
3
4
5
6
7
[1] 503  39
[1] "In the past month, I felt rushed by the things I had to do."
Strongly disagree          Disagree           Neutral             Agree 
                1                 2                 3                 4 
   Strongly agree           Refused 
                5               -99 
[1] -99

The survey uses four-character participant identifiers. sprintf("%04d", ID) gives the workbook’s numeric ID the same width in a new column. full_join() on ResponseId includes keys from either export, and relationship = "one-to-one" stops the join if a row matches more than one row in the other export. The suffixes _xlsx and _sav distinguish fields from the two files. In the rows for 0449, the participant IDs should agree across files even though the two submissions have different response keys.

1
2
3
4
5
6
7
8
9
10
11
12
13
xlsx_responses <- mutate(xlsx_responses, id_text = sprintf("%04d", ID), .after = ID)
responses <- full_join(
  xlsx_responses,
  sav_keyed,
  by = join_by(ResponseId),
  suffix = c("_xlsx", "_sav"),
  relationship = "one-to-one"
)
count(responses, in_xlsx = !is.na(ID_xlsx), in_sav = !is.na(ID_sav))
sum(responses$id_text == responses$ID_sav)
responses |>
  filter(ID_sav == "0449") |>
  select(ResponseId, ID_xlsx, id_text, ID_sav, `End Date_xlsx`, Finished_xlsx)
1
2
3
4
5
6
7
8
9
10
# A tibble: 1 × 3
  in_xlsx in_sav     n
  <lgl>   <lgl>  <int>
1 TRUE    TRUE     503
[1] 503
# A tibble: 2 × 6
  ResponseId     ID_xlsx id_text ID_sav `End Date_xlsx`     Finished_xlsx
  <chr>            <dbl> <chr>   <chr>  <chr>               <chr>        
1 R_EY0X7OFCR5OJ     449 0449    0449   2024-04-17 14:26:18 TRUE         
2 R_D0utZ1mh1tHG     449 0449    0449   2024-04-22 16:27:19 TRUE         

In Python, openpyxl reads the workbook cells as stored, including the numeric ID. iter_rows(values_only=True) returns tuples. The first gives the column names. The second contains the questions and belongs in question_text. Including it in xlsx_responses would add a submission nobody made. In pl.DataFrame(), orient="row" makes each remaining tuple one response. The two outputs show the answer Strongly agree in a response and the wording of STR_1 in question_text.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import openpyxl
import polars as pl
import pyreadstat

xlsx_path = "data/raw/survey/survey_raw.xlsx"
sav_path = "data/raw/survey/survey_raw.sav"
sheet = openpyxl.load_workbook(xlsx_path)["Responses"]
rows = list(sheet.iter_rows(values_only=True))
names = list(rows[0])
question_text = pl.DataFrame({"variable": names, "question": list(rows[1])})
xlsx_responses = pl.DataFrame(
    rows[2:], schema=names, orient="row", infer_schema_length=None
)
xlsx_responses.shape
xlsx_responses.filter(pl.col("ResponseId") == "R_D7sLfnz61bpc").select(
    "ResponseId", "ID", "End Date", "STR_1", "Finished"
)
question_text.filter(pl.col("variable") == "STR_1")["question"][0]
1
2
3
4
5
6
7
8
9
10
(503, 32)
shape: (1, 5)
┌────────────────┬─────┬─────────────────────┬────────────────┬──────────┐
│ ResponseId     ┆ ID  ┆ End Date            ┆ STR_1          ┆ Finished │
│ ---            ┆ --- ┆ ---                 ┆ ---            ┆ ---      │
│ str            ┆ i64 ┆ str                 ┆ str            ┆ str      │
╞════════════════╪═════╪═════════════════════╪════════════════╪══════════╡
│ R_D7sLfnz61bpc ┆ 7   ┆ 2024-04-19 10:00:55 ┆ Strongly agree ┆ TRUE     │
└────────────────┴─────┴─────────────────────┴────────────────┴──────────┘
'In the past month, I felt rushed by the things I had to do.'

With output_format="polars", pyreadstat.read_sav() returns a Polars table and a separate metadata object. With user_missing=True and apply_value_formats=False, declared missing codes and labeled answers are read as their stored numbers. For STR_1, sav_meta gives the question, the value labels, and the missing range. The sav_to_xlsx dictionary matches fields by name because the eight SPSS columns for Q_MULTI shift the fields that follow.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
sav_responses, sav_meta = pyreadstat.read_sav(
    sav_path, output_format="polars", user_missing=True, apply_value_formats=False
)
sav_responses.shape
sav_meta.column_names_to_labels["STR_1"]
sav_meta.variable_value_labels["STR_1"]
sav_meta.missing_ranges["STR_1"]
sav_to_xlsx = {
    "StartDate": "Start Date",
    "EndDate": "End Date",
    "BirthYear": "Birth Year",
    "Duration": "Duration (in seconds)",
}
sav_keyed = sav_responses.rename(sav_to_xlsx)
(names[29], sav_responses.columns[29])
1
2
3
4
5
(503, 39)
'In the past month, I felt rushed by the things I had to do.'
{1.0: 'Strongly disagree', 2.0: 'Disagree', 3.0: 'Neutral', 4.0: 'Agree', 5.0: 'Strongly agree', -99.0: 'Refused'}
[{'lo': -99.0, 'hi': -99.0}]
('Q_OPEN', 'Q_MULTI_2')

cast(pl.String).str.zfill(4) gives each numeric workbook ID its four-character form. In join() on ResponseId, how="full" includes keys from either file, coalesce=True combines the key columns, and validate="1:1" requires unique keys on each side. Only shared names from the right table get a suffix, so STR_1 is the workbook text and STR_1_sav is the SPSS code. For 0449, the two matched rows should still have different response keys.

1
2
3
4
5
6
7
8
9
10
11
12
13
xlsx_responses = xlsx_responses.with_columns(
    id_text=pl.col("ID").cast(pl.String).str.zfill(4)
)
responses = xlsx_responses.join(
    sav_keyed, on="ResponseId", how="full", coalesce=True, suffix="_sav", validate="1:1"
)
responses.group_by(
    in_xlsx=pl.col("ID").is_not_null(), in_sav=pl.col("ID_sav").is_not_null()
).agg(n=pl.len())
(responses["id_text"] == responses["ID_sav"]).sum()
responses.filter(pl.col("ID_sav") == "0449").sort("End Date").select(
    "ResponseId", "ID", "id_text", "ID_sav", "End Date", "Finished"
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
shape: (1, 3)
┌─────────┬────────┬─────┐
│ in_xlsx ┆ in_sav ┆ n   │
│ ---     ┆ ---    ┆ --- │
│ bool    ┆ bool   ┆ u32 │
╞═════════╪════════╪═════╡
│ true    ┆ true   ┆ 503 │
└─────────┴────────┴─────┘
503
shape: (2, 6)
┌────────────────┬─────┬─────────┬────────┬─────────────────────┬──────────┐
│ ResponseId     ┆ ID  ┆ id_text ┆ ID_sav ┆ End Date            ┆ Finished │
│ ---            ┆ --- ┆ ---     ┆ ---    ┆ ---                 ┆ ---      │
│ str            ┆ i64 ┆ str     ┆ str    ┆ str                 ┆ str      │
╞════════════════╪═════╪═════════╪════════╪═════════════════════╪══════════╡
│ R_EY0X7OFCR5OJ ┆ 449 ┆ 0449    ┆ 0449   ┆ 2024-04-17 14:26:18 ┆ TRUE     │
│ R_D0utZ1mh1tHG ┆ 449 ┆ 0449    ┆ 0449   ┆ 2024-04-22 16:27:19 ┆ TRUE     │
└────────────────┴─────┴─────────┴────────┴─────────────────────┴──────────┘

All 503 response keys match, including the two completed submissions of 0449, five days apart. The restored participant identifiers also match, with workbook number 7 corresponding to SPSS text 0007.

With the submissions paired, the answers can be compared. Three STR_1 rows show a standard label, a refusal, and an out-of-range value beside their SPSS codes. The haven column displays each labeled code with its label. In Polars, replace_strict(..., default=None) looks up each code and returns null for an unlisted code.

1
2
3
4
responses |>
  filter(ResponseId %in% c("R_D7sLfnz61bpc", "R_VTxENlIOXGUf", "R_0fleAyxSUwzC")) |>
  arrange(ResponseId) |>
  select(ResponseId, ID_xlsx, ID_sav, STR_1_xlsx, STR_1_sav)
1
2
3
4
5
6
# A tibble: 3 × 5
  ResponseId     ID_xlsx ID_sav STR_1_xlsx     STR_1_sav           
  <chr>            <dbl> <chr>  <chr>          <dbl+lbl>           
1 R_0fleAyxSUwzC     209 0209   6                6                 
2 R_D7sLfnz61bpc       7 0007   Strongly agree   5 [Strongly agree]
3 R_VTxENlIOXGUf     321 0321   -99            -99 (NA) [Refused]  
1
2
3
4
5
6
7
8
9
10
str_1_labels = sav_meta.variable_value_labels["STR_1"]
focal_ids = ["R_D7sLfnz61bpc", "R_VTxENlIOXGUf", "R_0fleAyxSUwzC"]
responses.filter(pl.col("ResponseId").is_in(focal_ids)).sort("ResponseId").select(
    "ResponseId",
    "ID",
    "ID_sav",
    "STR_1",
    "STR_1_sav",
    label_sav=pl.col("STR_1_sav").replace_strict(str_1_labels, default=None),
)
1
2
3
4
5
6
7
8
9
10
shape: (3, 6)
┌────────────────┬─────┬────────┬────────────────┬───────────┬────────────────┐
│ ResponseId     ┆ ID  ┆ ID_sav ┆ STR_1          ┆ STR_1_sav ┆ label_sav      │
│ ---            ┆ --- ┆ ---    ┆ ---            ┆ ---       ┆ ---            │
│ str            ┆ i64 ┆ str    ┆ str            ┆ f64       ┆ str            │
╞════════════════╪═════╪════════╪════════════════╪═══════════╪════════════════╡
│ R_0fleAyxSUwzC ┆ 209 ┆ 0209   ┆ 6              ┆ 6.0       ┆ null           │
│ R_D7sLfnz61bpc ┆ 7   ┆ 0007   ┆ Strongly agree ┆ 5.0       ┆ Strongly agree │
│ R_VTxENlIOXGUf ┆ 321 ┆ 0321   ┆ -99            ┆ -99.0     ┆ Refused        │
└────────────────┴─────┴────────┴────────────────┴───────────┴────────────────┘

Strongly agree corresponds to code 5, and workbook text -99 corresponds to SPSS code −99 labeled Refused. Both exports record 6, which falls outside the five-point scale. Agreement between exports therefore does not establish that an answer can be scored.

Before interpreting the answers, the assertions confirm that each submission has exactly one matching row and identifies the same participant in both files. The interpretation can then use question_text for the workbook questions and the SPSS labels and missing declarations from the R column attributes or Python’s sav_meta.

1
2
3
4
5
6
7
stopifnot(
  "every response in both exports" =
    all(!is.na(responses$ID_xlsx) & !is.na(responses$ID_sav)),
  "one row per response" = n_distinct(responses$ResponseId) == nrow(responses),
  "restored IDs equal the SPSS IDs" = all(responses$id_text == responses$ID_sav)
)
dim(responses)
1
[1] 503  71
1
2
3
4
5
in_both = responses["ID"].is_not_null() & responses["ID_sav"].is_not_null()
assert in_both.all(), "every response in both exports"
assert responses["ResponseId"].is_unique().all(), "one row per response"
assert (responses["id_text"] == responses["ID_sav"]).all(), "restored IDs equal"
responses.shape
1
(503, 71)

20.2 Interpreting labels, invalid values, and missing answers

The two exports agree on entries such as 6 and -99, but neither entry is a score. A 6 falls outside the agreement scale, and -99 records a refusal. The scale runs from 1 for Strongly disagree to 5 for Strongly agree. The known spelling Strongly Agree also scores 5. Recognized labels are observed, blanks are skipped, and -99 is refused. Other whole numbers outside the scale are invalid. Text with no established interpretation is unresolved.

Each row in item_table represents one question on one submission, identified by item and ResponseId. The ten satisfaction items make up the SAT scale and the ten stress items the STR scale. Each row contains the workbook text in raw_answer, its score in item_score, and its status in item_status. At this stage a 5 means strong agreement even for a negatively worded item. The attention answer, demographics, and open text are recorded once per submission.

In R, recode_values() uses agreement_scores to map the six recognized spellings to five scores. answer_status() classifies the other entries. Its patterns test the text directly, so signs, leading zeros, and digit strings too large for an integer can be classified. In 0*, * allows any number of zeros, including none. Numeric text from 1 to 5 is unresolved because the workbook uses labels for those answers.

matches() selects all 20 workbook item columns and pivot_longer() creates one answer row per submission and item. Removing _xlsx recovers the item name, and str_extract() takes its leading letters as the scale. Applying the mapping and status rules to these rows produces the item table used for scoring.

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
agreement_scores <- c(
  "Strongly disagree" = 1L,
  "Disagree" = 2L,
  "Neutral" = 3L,
  "Agree" = 4L,
  "Strongly agree" = 5L,
  "Strongly Agree" = 5L
)
answer_status <- function(raw_answer, score) {
  whole_number <- str_detect(raw_answer, "^[+-]?[0-9]+\\z")
  on_scale <- str_detect(raw_answer, "^\\+?0*[1-5]\\z")
  case_when(
    is.na(raw_answer) ~ "skipped",
    !is.na(score) ~ "observed",
    raw_answer == "-99" ~ "refused",
    whole_number & !on_scale ~ "invalid",
    .default = "unresolved"
  )
}
item_table <- responses |>
  select(ResponseId, matches("^(SAT|STR)_[0-9]+_xlsx$")) |>
  pivot_longer(-ResponseId, names_to = "item", values_to = "raw_answer") |>
  mutate(
    item = str_remove(item, "_xlsx$"),
    scale = str_extract(item, "^[A-Z]+"),
    item_score = recode_values(
      raw_answer,
      from = names(agreement_scores),
      to = agreement_scores
    ),
    item_status = answer_status(raw_answer, item_score)
  ) |>
  select(ResponseId, item, scale, raw_answer, item_score, item_status)
mapping_cases <- c(
  "R_D7sLfnz61bpc", "R_VRPHoHzpgLBH", "R_RxhFoDMIWcdQ", "R_VTxENlIOXGUf",
  "R_0fleAyxSUwzC"
)
item_table |>
  filter(item == "STR_1", ResponseId %in% mapping_cases) |>
  arrange(item_status, raw_answer)
count(item_table, item_status)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# A tibble: 5 × 6
  ResponseId     item  scale raw_answer     item_score item_status
  <chr>          <chr> <chr> <chr>               <int> <chr>      
1 R_0fleAyxSUwzC STR_1 STR   6                      NA invalid    
2 R_VRPHoHzpgLBH STR_1 STR   Strongly Agree          5 observed   
3 R_D7sLfnz61bpc STR_1 STR   Strongly agree          5 observed   
4 R_VTxENlIOXGUf STR_1 STR   -99                    NA refused    
5 R_RxhFoDMIWcdQ STR_1 STR   <NA>                   NA skipped    
# A tibble: 4 × 2
  item_status     n
  <chr>       <int>
1 invalid         7
2 observed     9802
3 refused        40
4 skipped       211

The five displayed cases distinguish invalid, refused, and skipped answers even though all three have missing scores. The two spellings of Strongly agree both map to 5, and the status counts contain no unresolved entries. Four constructed answers test whether a sign, leading zeros, or a 20-digit value changes how the text is classified.

1
2
3
4
5
pattern_cases <- c("+3", "003", "-2", "12345678901234567890")
tibble(
  raw_answer = pattern_cases,
  item_status = answer_status(pattern_cases, NA_integer_)
)
1
2
3
4
5
6
7
# A tibble: 4 × 2
  raw_answer           item_status
  <chr>                <chr>      
1 +3                   unresolved 
2 003                  unresolved 
3 -2                   invalid    
4 12345678901234567890 invalid    

Both +3 and 003 denote 3, but the workbook uses the label Neutral for that score. The two strings therefore stay unresolved. The other two strings denote whole numbers outside 1 to 5. The patterns can classify even the 20-digit string as invalid without converting it to an integer.

The scale-item table describes 20 answers per submission. Other information is recorded once for the submission as a whole, beginning with the attention answer. The workbook’s attention item reads, “For this item, please select ‘Disagree’.” The same mapping gives that answer code 2. Its score and status go into a separate attention table because the question belongs to neither ten-item scale.

1
2
3
4
5
6
7
8
9
10
11
attention <- responses |>
  select(ResponseId, attention_recorded = ATTN_1_xlsx) |>
  mutate(
    attention_score = recode_values(
      attention_recorded,
      from = names(agreement_scores),
      to = agreement_scores
    ),
    attention_status = answer_status(attention_recorded, attention_score)
  )
count(attention, attention_recorded, attention_score, attention_status)
1
2
3
4
5
6
7
8
# A tibble: 5 × 4
  attention_recorded attention_score attention_status     n
  <chr>                        <int> <chr>            <int>
1 Agree                            4 observed             2
2 Disagree                         2 observed           497
3 Strongly agree                   5 observed             2
4 Strongly disagree                1 observed             1
5 <NA>                            NA skipped              1

Gender, region, open text, and birth year also describe the submission as a whole. In response_attributes, one row per ResponseId stores these fields. For gender, the matched SPSS codes give the labels for workbook variants such as F, female, and text with extra spaces. haven::as_factor() applies those labels, and as.character() converts them to text in gender.

The workbook text and SPSS code beside the category show why, for example, F became Female. Region and open text come from the workbook, where unanswered cells are missing. For the open-text question, the last two counts compare blank workbook cells with empty SPSS strings.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
response_attributes <- responses |>
  select(
    ResponseId,
    gender_recorded = Gender_xlsx,
    gender_code = Gender_sav,
    region = Region_xlsx,
    open_text = Q_OPEN_xlsx,
    birth_year_recorded = `Birth Year_xlsx`,
    birth_year_code = `Birth Year_sav`
  ) |>
  mutate(
    gender = as.character(as_factor(gender_code)),
    gender_code = as.numeric(gender_code),
    .after = gender_code
  )
response_attributes |>
  filter(is.na(gender_recorded) | gender_recorded != gender) |>
  count(gender_recorded, gender_code, gender)
c(
  gender = sum(is.na(response_attributes$gender)),
  region = sum(is.na(response_attributes$region)),
  open_text = sum(is.na(response_attributes$open_text)),
  empty_sav_text = sum(responses$Q_OPEN_sav == "")
)
1
2
3
4
5
6
7
8
9
10
11
12
# A tibble: 7 × 4
  gender_recorded gender_code gender     n
  <chr>                 <dbl> <chr>  <int>
1 " Female"                 2 Female     6
2 "F"                       2 Female     4
3 "M"                       1 Male       9
4 "Male "                   1 Male       7
5 "female"                  2 Female     7
6 "male"                    1 Male       7
7  <NA>                    NA <NA>       3
        gender         region      open_text empty_sav_text 
             3              4            216            216 

SPSS labels the birth-year code 999 as No answer. attr() retrieves its missing-value declaration. The documented birth years for this cohort range from 1965 to 2005. The recorded years 1890 and 2030 fall outside that range, and neither export identifies the correct years. All three give a missing birth_year. The reason is declared missing for 999 and outside cohort range for the other two.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
response_attributes <- response_attributes |>
  mutate(
    birth_year_reason = case_when(
      as.numeric(birth_year_code) %in% attr(birth_year_code, "na_values") ~
        "declared missing",
      !between(birth_year_recorded, 1965, 2005) ~ "outside cohort range",
      .default = "observed"
    ),
    birth_year = if_else(birth_year_reason == "observed", birth_year_recorded, NA),
    birth_year_code = as.numeric(birth_year_code)
  )
birth_year_cases <- c("R_AQMrJ5pWxGfl", "R_GX9zDKulMrgE", "R_lkAt7hRguT1E")
response_attributes |>
  filter(ResponseId %in% birth_year_cases) |>
  arrange(birth_year_recorded) |>
  select(ResponseId, birth_year_recorded, birth_year, birth_year_reason)
count(response_attributes, birth_year_reason)
1
2
3
4
5
6
7
8
9
10
11
12
# A tibble: 3 × 4
  ResponseId     birth_year_recorded birth_year birth_year_reason   
  <chr>                        <dbl>      <dbl> <chr>               
1 R_AQMrJ5pWxGfl                 999         NA declared missing    
2 R_lkAt7hRguT1E                1890         NA outside cohort range
3 R_GX9zDKulMrgE                2030         NA outside cohort range
# A tibble: 3 × 2
  birth_year_reason        n
  <chr>                <int>
1 declared missing         5
2 observed               496
3 outside cohort range     2

In Polars, agreement_scores maps labels to scores. In answer_status(), the first pattern recognizes whole numbers written with or without a sign. The second recognizes values from 1 to 5, including an optional plus sign and leading zeros. Both test the text directly. The exact code -99 means refusal. Other off-scale whole numbers are invalid. A number from 1 to 5 written in place of a label is unresolved.

unpivot() creates one answer row per submission and item. The first with_columns() identifies the scale and maps the answer to item_score. The second can then use that score to assign item_status. The resulting table separates the recorded answer, its interpretation, and its availability for scoring.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
agreement_scores = {
    "Strongly disagree": 1,
    "Disagree": 2,
    "Neutral": 3,
    "Agree": 4,
    "Strongly agree": 5,
    "Strongly Agree": 5,
}


def answer_status(raw_answer, score):
    whole_number = raw_answer.str.contains(r"^[+-]?[0-9]+\z")
    on_scale = raw_answer.str.contains(r"^\+?0*[1-5]\z")
    return (
        pl.when(raw_answer.is_null())
        .then(pl.lit("skipped"))
        .when(score.is_not_null())
        .then(pl.lit("observed"))
        .when(raw_answer == "-99")
        .then(pl.lit("refused"))
        .when(whole_number & ~on_scale)
        .then(pl.lit("invalid"))
        .otherwise(pl.lit("unresolved"))
    )


item_names = [name for name in names if name.startswith(("SAT_", "STR_"))]
item_table = (
    responses.unpivot(
        index="ResponseId",
        on=item_names,
        variable_name="item",
        value_name="raw_answer",
    )
    .with_columns(
        scale=pl.col("item").str.extract(r"^([A-Z]+)"),
        item_score=pl.col("raw_answer").replace_strict(agreement_scores, default=None),
    )
    .with_columns(
        item_status=answer_status(pl.col("raw_answer"), pl.col("item_score"))
    )
    .select("ResponseId", "item", "scale", "raw_answer", "item_score", "item_status")
)
mapping_cases = [
    "R_D7sLfnz61bpc",
    "R_VRPHoHzpgLBH",
    "R_RxhFoDMIWcdQ",
    "R_VTxENlIOXGUf",
    "R_0fleAyxSUwzC",
]
item_table.filter(
    (pl.col("item") == "STR_1") & pl.col("ResponseId").is_in(mapping_cases)
).sort("item_status", "raw_answer")
item_table.group_by("item_status").agg(n=pl.len()).sort("item_status")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
shape: (5, 6)
┌────────────────┬───────┬───────┬────────────────┬────────────┬─────────────┐
│ ResponseId     ┆ item  ┆ scale ┆ raw_answer     ┆ item_score ┆ item_status │
│ ---            ┆ ---   ┆ ---   ┆ ---            ┆ ---        ┆ ---         │
│ str            ┆ str   ┆ str   ┆ str            ┆ i64        ┆ str         │
╞════════════════╪═══════╪═══════╪════════════════╪════════════╪═════════════╡
│ R_0fleAyxSUwzC ┆ STR_1 ┆ STR   ┆ 6              ┆ null       ┆ invalid     │
│ R_VRPHoHzpgLBH ┆ STR_1 ┆ STR   ┆ Strongly Agree ┆ 5          ┆ observed    │
│ R_D7sLfnz61bpc ┆ STR_1 ┆ STR   ┆ Strongly agree ┆ 5          ┆ observed    │
│ R_VTxENlIOXGUf ┆ STR_1 ┆ STR   ┆ -99            ┆ null       ┆ refused     │
│ R_RxhFoDMIWcdQ ┆ STR_1 ┆ STR   ┆ null           ┆ null       ┆ skipped     │
└────────────────┴───────┴───────┴────────────────┴────────────┴─────────────┘
shape: (4, 2)
┌─────────────┬──────┐
│ item_status ┆ n    │
│ ---         ┆ ---  │
│ str         ┆ u32  │
╞═════════════╪══════╡
│ invalid     ┆ 7    │
│ observed    ┆ 9802 │
│ refused     ┆ 40   │
│ skipped     ┆ 211  │
└─────────────┴──────┘

The blank, -99, and 6 all have a null score. Their item_status values distinguish a skipped answer, a refusal, and an invalid entry. Both spellings of Strongly agree score 5, and no item answer in the survey is unresolved. Four constructed answers show whether a sign, leading zeros, or a 20-digit value changes how those patterns classify the text.

1
2
3
4
5
6
pattern_cases = pl.DataFrame(
    {"raw_answer": ["+3", "003", "-2", "12345678901234567890"]}
)
pattern_cases.with_columns(
    item_status=answer_status(pl.col("raw_answer"), pl.lit(None, dtype=pl.Int64))
)
1
2
3
4
5
6
7
8
9
10
11
shape: (4, 2)
┌──────────────────────┬─────────────┐
│ raw_answer           ┆ item_status │
│ ---                  ┆ ---         │
│ str                  ┆ str         │
╞══════════════════════╪═════════════╡
│ +3                   ┆ unresolved  │
│ 003                  ┆ unresolved  │
│ -2                   ┆ invalid     │
│ 12345678901234567890 ┆ invalid     │
└──────────────────────┴─────────────┘

+3 and 003 look like the code for Neutral, but neither is a documented workbook label. Both are unresolved. The patterns identify -2 and the 20-digit string as invalid from their characters alone.

The scale-item table describes 20 answers per submission. The attention answer is recorded separately because it describes how the submission was completed and belongs to neither ten-item scale. ATTN_1 uses the same dictionary and status expression. The question asks for Disagree, which scores 2; its score and status form the attention table.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
attention = (
    responses.select("ResponseId", attention_recorded=pl.col("ATTN_1"))
    .with_columns(
        attention_score=pl.col("attention_recorded").replace_strict(
            agreement_scores, default=None
        )
    )
    .with_columns(
        attention_status=answer_status(
            pl.col("attention_recorded"), pl.col("attention_score")
        )
    )
)
attention.group_by("attention_recorded", "attention_score", "attention_status").agg(
    n=pl.len()
).sort("attention_recorded")
1
2
3
4
5
6
7
8
9
10
11
12
shape: (5, 4)
┌────────────────────┬─────────────────┬──────────────────┬─────┐
│ attention_recorded ┆ attention_score ┆ attention_status ┆ n   │
│ ---                ┆ ---             ┆ ---              ┆ --- │
│ str                ┆ i64             ┆ str              ┆ u32 │
╞════════════════════╪═════════════════╪══════════════════╪═════╡
│ null               ┆ null            ┆ skipped          ┆ 1   │
│ Agree              ┆ 4               ┆ observed         ┆ 2   │
│ Disagree           ┆ 2               ┆ observed         ┆ 497 │
│ Strongly agree     ┆ 5               ┆ observed         ┆ 2   │
│ Strongly disagree  ┆ 1               ┆ observed         ┆ 1   │
└────────────────────┴─────────────────┴──────────────────┴─────┘

Gender, region, open text, and birth year also describe the submission as a whole. response_attributes therefore has one row per ResponseId. For gender, replace_strict() maps each SPSS code to its label in variable_value_labels. The adjacent gender_recorded column shows how the answer was written in the workbook.

The comparison filter includes missing entries and recorded text that differs from its category. A trailing space may be difficult to see in the Polars display: the apparent Male row passes the filter because its recorded value is Male . Unanswered region and open-text fields are null. The last two counts compare blank workbook cells with empty SPSS strings for the open-text question.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
gender_labels = sav_meta.variable_value_labels["Gender"]
response_attributes = responses.select(
    "ResponseId",
    gender_recorded=pl.col("Gender"),
    gender_code=pl.col("Gender_sav"),
    gender=pl.col("Gender_sav").replace_strict(gender_labels, default=None),
    region=pl.col("Region"),
    open_text=pl.col("Q_OPEN"),
    birth_year_recorded=pl.col("Birth Year"),
    birth_year_code=pl.col("Birth Year_sav"),
)
is_repaired = pl.col("gender_recorded").is_null() | (
    pl.col("gender_recorded") != pl.col("gender")
)
response_attributes.filter(is_repaired).group_by(
    "gender_recorded", "gender_code", "gender"
).agg(n=pl.len()).sort("gender_recorded")
response_attributes.select(
    gender=pl.col("gender").null_count(),
    region=pl.col("region").null_count(),
    open_text=pl.col("open_text").null_count(),
    empty_sav_text=(responses["Q_OPEN_sav"] == "").sum(),
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
shape: (7, 4)
┌─────────────────┬─────────────┬────────┬─────┐
│ gender_recorded ┆ gender_code ┆ gender ┆ n   │
│ ---             ┆ ---         ┆ ---    ┆ --- │
│ str             ┆ f64         ┆ str    ┆ u32 │
╞═════════════════╪═════════════╪════════╪═════╡
│ null            ┆ null        ┆ null   ┆ 3   │
│  Female         ┆ 2.0         ┆ Female ┆ 6   │
│ F               ┆ 2.0         ┆ Female ┆ 4   │
│ M               ┆ 1.0         ┆ Male   ┆ 9   │
│ Male            ┆ 1.0         ┆ Male   ┆ 7   │
│ female          ┆ 2.0         ┆ Female ┆ 7   │
│ male            ┆ 1.0         ┆ Male   ┆ 7   │
└─────────────────┴─────────────┴────────┴─────┘
shape: (1, 4)
┌────────┬────────┬───────────┬────────────────┐
│ gender ┆ region ┆ open_text ┆ empty_sav_text │
│ ---    ┆ ---    ┆ ---       ┆ ---            │
│ u32    ┆ u32    ┆ u32       ┆ i32            │
╞════════╪════════╪═══════════╪════════════════╡
│ 3      ┆ 4      ┆ 216       ┆ 216            │
└────────┴────────┴───────────┴────────────────┘

Six variant spellings of the gender labels account for 40 workbook entries. Three submissions have no gender code. For the open-text question, each export has 216 unanswered entries.

SPSS declares 999 missing in missing_ranges. That check comes first because 999 is also outside the cohort’s range from 1965 to 2005. The second with_columns() assigns birth_year only for observed years. The recorded value and birth_year_reason show why the other entries have no usable year.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
declared = sav_meta.missing_ranges["BirthYear"][0]
response_attributes = response_attributes.with_columns(
    birth_year_reason=pl.when(
        pl.col("birth_year_code").is_between(declared["lo"], declared["hi"])
    )
    .then(pl.lit("declared missing"))
    .when(~pl.col("birth_year_recorded").is_between(1965, 2005))
    .then(pl.lit("outside cohort range"))
    .otherwise(pl.lit("observed"))
).with_columns(
    birth_year=pl.when(pl.col("birth_year_reason") == "observed").then(
        pl.col("birth_year_recorded")
    )
)
birth_year_cases = ["R_AQMrJ5pWxGfl", "R_GX9zDKulMrgE", "R_lkAt7hRguT1E"]
response_attributes.filter(pl.col("ResponseId").is_in(birth_year_cases)).sort(
    "birth_year_recorded"
).select(
    "ResponseId", "birth_year_recorded", "birth_year", "birth_year_reason"
)
response_attributes.group_by("birth_year_reason").agg(n=pl.len()).sort(
    "birth_year_reason"
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
shape: (3, 4)
┌────────────────┬─────────────────────┬────────────┬──────────────────────┐
│ ResponseId     ┆ birth_year_recorded ┆ birth_year ┆ birth_year_reason    │
│ ---            ┆ ---                 ┆ ---        ┆ ---                  │
│ str            ┆ i64                 ┆ i64        ┆ str                  │
╞════════════════╪═════════════════════╪════════════╪══════════════════════╡
│ R_AQMrJ5pWxGfl ┆ 999                 ┆ null       ┆ declared missing     │
│ R_lkAt7hRguT1E ┆ 1890                ┆ null       ┆ outside cohort range │
│ R_GX9zDKulMrgE ┆ 2030                ┆ null       ┆ outside cohort range │
└────────────────┴─────────────────────┴────────────┴──────────────────────┘
shape: (3, 2)
┌──────────────────────┬─────┐
│ birth_year_reason    ┆ n   │
│ ---                  ┆ --- │
│ str                  ┆ u32 │
╞══════════════════════╪═════╡
│ declared missing     ┆ 5   │
│ observed             ┆ 496 │
│ outside cohort range ┆ 2   │
└──────────────────────┴─────┘

The two tables have different keys. With 20 scale items on each of 503 forms, item_table should have 10,060 distinct response/item pairs; response_attributes should have one row per response. The attention answer joins the latter table by ResponseId.

For an observed item answer, its score should still equal the SPSS code because reversal comes later. In R, as.numeric() extracts the codes before the columns are lengthened. Polars strips _sav after unpivot() to match the item names. If an observed workbook answer has no SPSS code to compare it with, fill_null(False) makes the check fail.

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
sav_codes <- responses |>
  select(ResponseId, matches("^(SAT|STR)_[0-9]+_sav$")) |>
  mutate(across(-ResponseId, as.numeric)) |>
  pivot_longer(-ResponseId, names_to = "item", values_to = "sav_code") |>
  mutate(item = str_remove(item, "_sav$"))
item_check <- left_join(
  item_table,
  sav_codes,
  by = join_by(ResponseId, item),
  relationship = "one-to-one"
)
response_attributes <- left_join(
  response_attributes,
  attention,
  by = join_by(ResponseId),
  relationship = "one-to-one"
)
observed_items <- filter(item_check, item_status == "observed")
tibble(
  item_rows = nrow(item_table),
  unique_keys = nrow(distinct(item_table, ResponseId, item)),
  responses = n_distinct(item_table$ResponseId),
  all_20 = all(count(item_table, ResponseId)$n == 20),
  scores_1_5 = all(item_table$item_score %in% c(1:5, NA)),
  same_code = all(observed_items$item_score == observed_items$sav_code),
  attribute_rows = nrow(response_attributes)
)
1
2
3
4
# A tibble: 1 × 7
  item_rows unique_keys responses all_20 scores_1_5 same_code attribute_rows
      <int>       <int>     <int> <lgl>  <lgl>      <lgl>              <int>
1     10060       10060       503 TRUE   TRUE       TRUE                 503
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
sav_codes = responses.unpivot(
    index="ResponseId",
    on=[name + "_sav" for name in item_names],
    variable_name="item",
    value_name="sav_code",
).with_columns(pl.col("item").str.strip_suffix("_sav"))
item_check = item_table.join(
    sav_codes, on=["ResponseId", "item"], how="left", validate="1:1"
)
response_attributes = response_attributes.join(
    attention, on="ResponseId", how="left", validate="1:1"
)
observed_items = item_check.filter(pl.col("item_status") == "observed")
{
    "item_rows": item_table.height,
    "unique_keys": item_table.select("ResponseId", "item").is_unique().all(),
    "responses": item_table["ResponseId"].n_unique(),
    "all_20": (item_table.group_by("ResponseId").agg(n=pl.len())["n"] == 20).all(),
    "scores_1_5": item_table["item_score"].drop_nulls().is_between(1, 5).all(),
    "same_code": (observed_items["item_score"] == observed_items["sav_code"]).fill_null(False).all(),
    "attribute_rows": response_attributes.height,
}
1
{'item_rows': 10060, 'unique_keys': True, 'responses': 503, 'all_20': True, 'scores_1_5': True, 'same_code': True, 'attribute_rows': 503}

The checks account for all 10,060 item rows and 503 response-attribute rows. Observed item scores match the SPSS codes.

20.3 Repeated responses and response-quality flags

The participant table needs one submission per person. When someone completes two, which answers go into that row? For this analysis, we use the earliest completed submission, comparing end times in Asia/Seoul. A form marked TRUE in Finished counts as completed even if some answers are blank. If end times tie, we take the form whose ResponseId sorts first. Only participants with a completed form can be selected. Quality flags play no part in that choice.

0301 repeated the same answers, 0449 later submitted different answers, and 0489 left one submission unfinished before completing another. For each of the 503 submissions, audit records the decision as earliest completed, later completed, or unfinished.

ymd_hms() parses the end times in Seoul time. Only completed submissions enter the ranking, so row_number() starts at 1 for each participant’s earliest completed form. Unfinished forms have no rank after the left join. In R, %in% 1 returns FALSE for that missing value. case_when() labels the three selection reasons, and selected_keys records the chosen response and participant keys.

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
submissions <- responses |>
  select(
    ResponseId,
    participant = id_text,
    finished_recorded = Finished_xlsx,
    end_recorded = `End Date_xlsx`,
    duration = `Duration (in seconds)_xlsx`
  ) |>
  mutate(
    finished = finished_recorded == "TRUE",
    end = ymd_hms(end_recorded, tz = "Asia/Seoul")
  )
completed_order <- submissions |>
  filter(finished) |>
  arrange(participant, end, ResponseId) |>
  mutate(completed_order = row_number(), .by = participant) |>
  select(ResponseId, completed_order)
audit <- submissions |>
  left_join(completed_order, by = join_by(ResponseId), relationship = "one-to-one") |>
  mutate(
    selected = finished & completed_order %in% 1,
    selection_reason = case_when(
      !finished ~ "unfinished",
      completed_order == 1 ~ "earliest completed",
      .default = "later completed"
    )
  )
selected_keys <- audit |>
  filter(selected) |>
  select(ResponseId, participant)
audit |>
  filter(participant %in% c("0301", "0449", "0489")) |>
  arrange(participant, end) |>
  select(participant, ResponseId, end, finished, selection_reason)
count(audit, selected, selection_reason)
c(selected = nrow(selected_keys), participants = n_distinct(selected_keys$participant))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# A tibble: 6 × 5
  participant ResponseId     end                 finished selection_reason  
  <chr>       <chr>          <dttm>              <lgl>    <chr>             
1 0301        R_WEanrtqrVeIp 2024-04-02 16:48:04 TRUE     earliest completed
2 0301        R_LmcIXkg8nskK 2024-04-02 16:48:51 TRUE     later completed   
3 0449        R_EY0X7OFCR5OJ 2024-04-17 14:26:18 TRUE     earliest completed
4 0449        R_D0utZ1mh1tHG 2024-04-22 16:27:19 TRUE     later completed   
5 0489        R_JbfYiyWlRfK2 2024-04-16 14:11:04 FALSE    unfinished        
6 0489        R_fer2gcP8qhbe 2024-04-17 14:13:31 TRUE     earliest completed
# A tibble: 3 × 3
  selected selection_reason       n
  <lgl>    <chr>              <int>
1 FALSE    later completed        2
2 FALSE    unfinished             1
3 TRUE     earliest completed   500
    selected participants 
         500          500 

In Polars, str.to_datetime(..., time_zone="Asia/Seoul") parses the end times. After sorting completed submissions by participant, end time, and ResponseId, cum_count().over("participant") gives each person’s earliest a rank of 1. Unfinished forms have a null rank after the left join, so fill_null(False) marks them unselected. The audit records each reason, and selected_keys lists the chosen submissions.

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
submissions = responses.select(
    "ResponseId",
    participant=pl.col("id_text"),
    finished_recorded=pl.col("Finished"),
    end_recorded=pl.col("End Date"),
    duration=pl.col("Duration (in seconds)"),
).with_columns(
    finished=pl.col("finished_recorded") == "TRUE",
    end=pl.col("end_recorded").str.to_datetime(
        "%Y-%m-%d %H:%M:%S", time_zone="Asia/Seoul"
    ),
)
completed_order = (
    submissions.filter(pl.col("finished"))
    .sort("participant", "end", "ResponseId")
    .with_columns(completed_order=pl.col("ResponseId").cum_count().over("participant"))
    .select("ResponseId", "completed_order")
)
audit = submissions.join(
    completed_order, on="ResponseId", how="left", validate="1:1"
).with_columns(
    selected=pl.col("finished") & (pl.col("completed_order") == 1).fill_null(False),
    selection_reason=pl.when(~pl.col("finished"))
    .then(pl.lit("unfinished"))
    .when(pl.col("completed_order") == 1)
    .then(pl.lit("earliest completed"))
    .otherwise(pl.lit("later completed")),
)
selected_keys = audit.filter(pl.col("selected")).select("ResponseId", "participant")
audit.filter(pl.col("participant").is_in(["0301", "0449", "0489"])).sort(
    "participant", "end"
).select("participant", "ResponseId", "end", "finished", "selection_reason")
audit.group_by("selected", "selection_reason").agg(n=pl.len()).sort("selection_reason")
(selected_keys.height, selected_keys["participant"].n_unique())
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, 5)
┌─────────────┬────────────────┬──────────────────────────┬──────────┬────────────────────┐
│ participant ┆ ResponseId     ┆ end                      ┆ finished ┆ selection_reason   │
│ ---         ┆ ---            ┆ ---                      ┆ ---      ┆ ---                │
│ str         ┆ str            ┆ datetime[μs, Asia/Seoul] ┆ bool     ┆ str                │
╞═════════════╪════════════════╪══════════════════════════╪══════════╪════════════════════╡
│ 0301        ┆ R_WEanrtqrVeIp ┆ 2024-04-02 16:48:04 KST  ┆ true     ┆ earliest completed │
│ 0301        ┆ R_LmcIXkg8nskK ┆ 2024-04-02 16:48:51 KST  ┆ true     ┆ later completed    │
│ 0449        ┆ R_EY0X7OFCR5OJ ┆ 2024-04-17 14:26:18 KST  ┆ true     ┆ earliest completed │
│ 0449        ┆ R_D0utZ1mh1tHG ┆ 2024-04-22 16:27:19 KST  ┆ true     ┆ later completed    │
│ 0489        ┆ R_JbfYiyWlRfK2 ┆ 2024-04-16 14:11:04 KST  ┆ false    ┆ unfinished         │
│ 0489        ┆ R_fer2gcP8qhbe ┆ 2024-04-17 14:13:31 KST  ┆ true     ┆ earliest completed │
└─────────────┴────────────────┴──────────────────────────┴──────────┴────────────────────┘
shape: (3, 3)
┌──────────┬────────────────────┬─────┐
│ selected ┆ selection_reason   ┆ n   │
│ ---      ┆ ---                ┆ --- │
│ bool     ┆ str                ┆ u32 │
╞══════════╪════════════════════╪═════╡
│ true     ┆ earliest completed ┆ 500 │
│ false    ┆ later completed    ┆ 2   │
│ false    ┆ unfinished         ┆ 1   │
└──────────┴────────────────────┴─────┘
(500, 500)

The rule selects one completed response for every participant. It selects the earlier completed form for 0301 and 0449. For 0489, it selects the later form because the earlier one was unfinished.

Completion determines which form is selected, but it does not establish how carefully that form was answered. Duration and attention answers provide separate descriptive flags. Here short_duration means a response took less than 60 seconds, a cutoff chosen for this survey. An observed attention answer other than Disagree raises attention_failed. The requested answer scores 2 and gives a false flag; a blank gives a missing flag.

Someone who chose Agree on every item would have selected the same answer 20 times. After reverse scoring, those answers would appear as a mixture of 4s and 2s. The straightlining flag therefore compares the original agreement scores. If all 20 items have valid scores, the flag is true when the scores are all equal and false when they differ. Otherwise the flag is missing.

In R, ResponseId links the duration in audit to the attention answer and to the counts of observed answers and distinct unreversed scores. if_else() gives straightlining a value only when all 20 scores are present. The duration display includes submissions under 180 seconds so that it shows forms on both sides of the 60-second cutoff.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
item_pattern <- item_table |>
  summarise(
    n_observed = sum(item_status == "observed"),
    n_values = n_distinct(item_score, na.rm = TRUE),
    .by = ResponseId
  ) |>
  mutate(straightlining = if_else(n_observed == 20, n_values == 1, NA))
audit <- audit |>
  left_join(
    select(response_attributes, ResponseId, attention_score, attention_status),
    by = join_by(ResponseId),
    relationship = "one-to-one"
  ) |>
  left_join(item_pattern, by = join_by(ResponseId), relationship = "one-to-one") |>
  mutate(
    short_duration = duration < 60,
    attention_failed = if_else(
      attention_status == "observed",
      attention_score != 2L,
      NA
    )
  )
audit |>
  filter(duration < 180) |>
  arrange(duration) |>
  select(ResponseId, duration, finished, short_duration)
count(audit, attention_score, attention_status, attention_failed)
count(audit, complete = n_observed == 20, straightlining)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# A tibble: 6 × 4
  ResponseId     duration finished short_duration
  <chr>             <dbl> <lgl>    <lgl>         
1 R_pD8hOVRPP3qf       27 TRUE     TRUE          
2 R_CmI48WhFskb3       38 TRUE     TRUE          
3 R_a7ogmS2VIrzM       43 TRUE     TRUE          
4 R_YjImVViSIMBb       51 TRUE     TRUE          
5 R_JbfYiyWlRfK2      140 FALSE    FALSE         
6 R_qGhFUxOG4YsF      176 TRUE     FALSE         
# A tibble: 5 × 4
  attention_score attention_status attention_failed     n
            <int> <chr>            <lgl>            <int>
1               1 observed         TRUE                 1
2               2 observed         FALSE              497
3               4 observed         TRUE                 2
4               5 observed         TRUE                 2
5              NA skipped          NA                   1
# A tibble: 3 × 3
  complete straightlining     n
  <lgl>    <lgl>          <int>
1 FALSE    NA               191
2 TRUE     FALSE            309
3 TRUE     TRUE               3

In Polars, drop_nulls().n_unique() counts distinct observed scores on a form. The straightlining and attention flags use pl.when() without otherwise(). An incomplete set gets a null pattern flag, and an unanswered attention item gets a null attention flag. The joins require unique response keys. The final comparison checks whether the same submissions are selected after the joins.

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
item_pattern = item_table.group_by("ResponseId").agg(
    n_observed=(pl.col("item_status") == "observed").sum(),
    n_values=pl.col("item_score").drop_nulls().n_unique(),
).with_columns(
    straightlining=pl.when(pl.col("n_observed") == 20).then(pl.col("n_values") == 1)
)
audit = (
    audit.join(
        response_attributes.select("ResponseId", "attention_score", "attention_status"),
        on="ResponseId",
        how="left",
        validate="1:1",
    )
    .join(item_pattern, on="ResponseId", how="left", validate="1:1")
    .with_columns(
        short_duration=pl.col("duration") < 60,
        attention_failed=pl.when(pl.col("attention_status") == "observed").then(
            pl.col("attention_score") != 2
        ),
    )
)
audit.filter(pl.col("duration") < 180).sort("duration").select(
    "ResponseId", "duration", "finished", "short_duration"
)
audit.group_by("attention_score", "attention_status", "attention_failed").agg(
    n=pl.len()
).sort("attention_score", nulls_last=True)
audit.group_by(
    complete=pl.col("n_observed") == 20, straightlining=pl.col("straightlining")
).agg(n=pl.len()).sort("complete", "straightlining")

reselected = audit.filter(pl.col("selected"))["ResponseId"].sort()
reselected.equals(selected_keys["ResponseId"].sort())
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
shape: (6, 4)
┌────────────────┬──────────┬──────────┬────────────────┐
│ ResponseId     ┆ duration ┆ finished ┆ short_duration │
│ ---            ┆ ---      ┆ ---      ┆ ---            │
│ str            ┆ i64      ┆ bool     ┆ bool           │
╞════════════════╪══════════╪══════════╪════════════════╡
│ R_pD8hOVRPP3qf ┆ 27       ┆ true     ┆ true           │
│ R_CmI48WhFskb3 ┆ 38       ┆ true     ┆ true           │
│ R_a7ogmS2VIrzM ┆ 43       ┆ true     ┆ true           │
│ R_YjImVViSIMBb ┆ 51       ┆ true     ┆ true           │
│ R_JbfYiyWlRfK2 ┆ 140      ┆ false    ┆ false          │
│ R_qGhFUxOG4YsF ┆ 176      ┆ true     ┆ false          │
└────────────────┴──────────┴──────────┴────────────────┘
shape: (5, 4)
┌─────────────────┬──────────────────┬──────────────────┬─────┐
│ attention_score ┆ attention_status ┆ attention_failed ┆ n   │
│ ---             ┆ ---              ┆ ---              ┆ --- │
│ i64             ┆ str              ┆ bool             ┆ u32 │
╞═════════════════╪══════════════════╪══════════════════╪═════╡
│ 1               ┆ observed         ┆ true             ┆ 1   │
│ 2               ┆ observed         ┆ false            ┆ 497 │
│ 4               ┆ observed         ┆ true             ┆ 2   │
│ 5               ┆ observed         ┆ true             ┆ 2   │
│ null            ┆ skipped          ┆ null             ┆ 1   │
└─────────────────┴──────────────────┴──────────────────┴─────┘
shape: (3, 3)
┌──────────┬────────────────┬─────┐
│ complete ┆ straightlining ┆ n   │
│ ---      ┆ ---            ┆ --- │
│ bool     ┆ bool           ┆ u32 │
╞══════════╪════════════════╪═════╡
│ false    ┆ null           ┆ 191 │
│ true     ┆ false          ┆ 309 │
│ true     ┆ true           ┆ 3   │
└──────────┴────────────────┴─────┘
True

Four submissions have durations below 60 seconds, five have observed attention failures, and three have identical answers across all 20 items. The 191 incomplete item sets have an undetermined pattern flag.

To count submissions with any raised flag, each form must contribute at most once. For this combined count, R’s %in% TRUE and Polars’ fill_null(False) treat a missing attention or straightlining flag as unraised. A form can therefore have flagged set to false while its individual straightlining flag is still missing.

1
2
3
4
5
audit |>
  mutate(
    flagged = short_duration | attention_failed %in% TRUE | straightlining %in% TRUE
  ) |>
  count(selected, flagged)
1
2
3
4
5
6
# A tibble: 3 × 3
  selected flagged     n
  <lgl>    <lgl>   <int>
1 FALSE    FALSE       3
2 TRUE     FALSE     488
3 TRUE     TRUE       12
1
2
3
4
5
audit.with_columns(
    flagged=pl.col("short_duration")
    | pl.col("attention_failed").fill_null(False)
    | pl.col("straightlining").fill_null(False)
).group_by("selected", "flagged").agg(n=pl.len()).sort("selected", "flagged")
1
2
3
4
5
6
7
8
9
10
shape: (3, 3)
┌──────────┬─────────┬─────┐
│ selected ┆ flagged ┆ n   │
│ ---      ┆ ---     ┆ --- │
│ bool     ┆ bool    ┆ u32 │
╞══════════╪═════════╪═════╡
│ false    ┆ false   ┆ 3   │
│ true     ┆ false   ┆ 488 │
│ true     ┆ true    ┆ 12  │
└──────────┴─────────┴─────┘

All 12 submissions with a raised flag are among the 500 selected forms. The three excluded forms were later completions or unfinished submissions. A flag records a characteristic such as 20 identical ratings. It cannot tell us why a participant gave those answers.

20.4 Constructing scale scores from valid items

On SAT_1, Agree scores 4 and indicates satisfaction. On SAT_3, Disagree scores 2 and also indicates satisfaction because the statement expresses dissatisfaction. Reversing SAT_3 with 6 - item_score gives that answer a 4 on the five-point scale.

The other reversed satisfaction items are SAT_6 and SAT_9. On the stress scale, STR_4, STR_5, STR_7, and STR_8 are reversed so higher scores mean greater stress. STR_3 asks about losing sleep to worry and already points in that direction.

For these synthetic scales, we report a mean only if at least nine of the ten items on that scale have valid answers. On each submission, we divide the sum of those adjusted scores by the number of valid answers for that scale. Scoring both submissions from the same person lets us see how the choice of form affects that person’s scale means.

In R, adjust_direction() marks items in reverse_items and adds adjusted_score beside the original score and status. Missing scores stay missing under subtraction. One form shows the changes item by item. Counts across forms reveal whether any unusable answer acquired a score.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
reverse_items <- c("SAT_3", "SAT_6", "SAT_9", "STR_4", "STR_5", "STR_7", "STR_8")
min_valid <- 9
adjust_direction <- function(items, reverse) {
  items |>
    mutate(
      is_reverse = item %in% reverse,
      adjusted_score = if_else(is_reverse, 6L - item_score, item_score)
    )
}
adjusted_items <- adjust_direction(item_table, reverse_items)
adjusted_items |>
  filter(ResponseId == "R_2RgM2mAjjyks", scale == "SAT") |>
  select(item, item_status, item_score, is_reverse, adjusted_score)
count(adjusted_items, is_reverse, item_status, has_adjusted = !is.na(adjusted_score))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# A tibble: 10 × 5
   item   item_status item_score is_reverse adjusted_score
   <chr>  <chr>            <int> <lgl>               <int>
 1 SAT_1  observed             3 FALSE                   3
 2 SAT_2  observed             4 FALSE                   4
 3 SAT_3  skipped             NA TRUE                   NA
 4 SAT_4  observed             5 FALSE                   5
 5 SAT_5  observed             3 FALSE                   3
 6 SAT_6  observed             2 TRUE                    4
 7 SAT_7  observed             4 FALSE                   4
 8 SAT_8  observed             3 FALSE                   3
 9 SAT_9  observed             4 TRUE                    2
10 SAT_10 observed             5 FALSE                   5
# A tibble: 8 × 4
  is_reverse item_status has_adjusted     n
  <lgl>      <chr>       <lgl>        <int>
1 FALSE      invalid     FALSE            3
2 FALSE      observed    TRUE          6365
3 FALSE      refused     FALSE           24
4 FALSE      skipped     FALSE          147
5 TRUE       invalid     FALSE            4
6 TRUE       observed    TRUE          3437
7 TRUE       refused     FALSE           16
8 TRUE       skipped     FALSE           64

For the displayed response, SAT_6 changes from 2 to 4 and SAT_9 from 4 to 2, while skipped SAT_3 stays missing. With .by = c(ResponseId, scale), summarise() counts observed adjusted scores in n_valid and adds them in score_sum. An all-missing scale still gets a row, with zero in both columns.

1
2
3
4
5
6
7
8
9
10
aggregate_items <- function(adjusted) {
  adjusted |>
    summarise(
      n_valid = sum(!is.na(adjusted_score)),
      score_sum = sum(adjusted_score, na.rm = TRUE),
      .by = c(ResponseId, scale)
    )
}
scale_counts <- aggregate_items(adjusted_items)
c(rows = nrow(scale_counts), keys = nrow(distinct(scale_counts, ResponseId, scale)))
1
2
rows keys 
1006 1006 

Each of the 1,006 response/scale rows now has a count and a sum. score_scales() uses if_else() to return the sum divided by the count for eligible rows and NA_real_ otherwise. The two SAT rows differ by one valid answer at the nine-item threshold.

1
2
3
4
5
6
7
score_scales <- function(counts, min_valid) {
  counts |>
    mutate(score = if_else(n_valid >= min_valid, score_sum / n_valid, NA_real_))
}
scale_scores <- score_scales(scale_counts, min_valid)
threshold_cases <- c("R_2RgM2mAjjyks", "R_7Fo8MfjVtPde")
filter(scale_scores, scale == "SAT", ResponseId %in% threshold_cases)
1
2
3
4
5
# A tibble: 2 × 5
  ResponseId     scale n_valid score_sum score
  <chr>          <chr>   <int>     <int> <dbl>
1 R_2RgM2mAjjyks SAT         9        33  3.67
2 R_7Fo8MfjVtPde SAT         8        22 NA   

In Polars, adjust_direction() creates is_reverse in one with_columns() call because expressions in that call cannot use a column created alongside them. A second call can then use is_reverse to choose between 6 - item_score and the original score. A null stays null in either branch. The SAT rows show how this affects one submission. The counts by reversal and status check that a skipped or invalid answer never acquires an adjusted score.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
reverse_items = ["SAT_3", "SAT_6", "SAT_9", "STR_4", "STR_5", "STR_7", "STR_8"]
min_valid = 9


def adjust_direction(items, reverse):
    return items.with_columns(is_reverse=pl.col("item").is_in(reverse)).with_columns(
        adjusted_score=pl.when(pl.col("is_reverse"))
        .then(6 - pl.col("item_score"))
        .otherwise(pl.col("item_score"))
    )


adjusted_items = adjust_direction(item_table, reverse_items)
adjusted_items.filter(
    pl.col("ResponseId") == "R_2RgM2mAjjyks", pl.col("scale") == "SAT"
).select("item", "item_status", "item_score", "is_reverse", "adjusted_score")
adjusted_items.group_by(
    "is_reverse", "item_status", has_adjusted=pl.col("adjusted_score").is_not_null()
).agg(n=pl.len()).sort("is_reverse", "item_status")
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
shape: (10, 5)
┌────────┬─────────────┬────────────┬────────────┬────────────────┐
│ item   ┆ item_status ┆ item_score ┆ is_reverse ┆ adjusted_score │
│ ---    ┆ ---         ┆ ---        ┆ ---        ┆ ---            │
│ str    ┆ str         ┆ i64        ┆ bool       ┆ i64            │
╞════════╪═════════════╪════════════╪════════════╪════════════════╡
│ SAT_1  ┆ observed    ┆ 3          ┆ false      ┆ 3              │
│ SAT_2  ┆ observed    ┆ 4          ┆ false      ┆ 4              │
│ SAT_3  ┆ skipped     ┆ null       ┆ true       ┆ null           │
│ SAT_4  ┆ observed    ┆ 5          ┆ false      ┆ 5              │
│ SAT_5  ┆ observed    ┆ 3          ┆ false      ┆ 3              │
│ SAT_6  ┆ observed    ┆ 2          ┆ true       ┆ 4              │
│ SAT_7  ┆ observed    ┆ 4          ┆ false      ┆ 4              │
│ SAT_8  ┆ observed    ┆ 3          ┆ false      ┆ 3              │
│ SAT_9  ┆ observed    ┆ 4          ┆ true       ┆ 2              │
│ SAT_10 ┆ observed    ┆ 5          ┆ false      ┆ 5              │
└────────┴─────────────┴────────────┴────────────┴────────────────┘
shape: (8, 4)
┌────────────┬─────────────┬──────────────┬──────┐
│ is_reverse ┆ item_status ┆ has_adjusted ┆ n    │
│ ---        ┆ ---         ┆ ---          ┆ ---  │
│ bool       ┆ str         ┆ bool         ┆ u32  │
╞════════════╪═════════════╪══════════════╪══════╡
│ false      ┆ invalid     ┆ false        ┆ 3    │
│ false      ┆ observed    ┆ true         ┆ 6365 │
│ false      ┆ refused     ┆ false        ┆ 24   │
│ false      ┆ skipped     ┆ false        ┆ 147  │
│ true       ┆ invalid     ┆ false        ┆ 4    │
│ true       ┆ observed    ┆ true         ┆ 3437 │
│ true       ┆ refused     ┆ false        ┆ 16   │
│ true       ┆ skipped     ┆ false        ┆ 64   │
└────────────┴─────────────┴──────────────┴──────┘

In the displayed SAT response, SAT_6 changes from 2 to 4, SAT_9 from 4 to 2, and the skipped SAT_3 stays null. Each ResponseId and scale pair now needs one row. Its count and sum summarize the nonnull adjusted scores. Even an all-null group returns a row, with zero in both columns.

1
2
3
4
5
6
7
8
9
def aggregate_items(adjusted):
    return adjusted.group_by("ResponseId", "scale").agg(
        n_valid=pl.col("adjusted_score").is_not_null().sum(),
        score_sum=pl.col("adjusted_score").sum(),
    )


scale_counts = aggregate_items(adjusted_items)
(scale_counts.height, scale_counts.select("ResponseId", "scale").is_unique().all())
1
(1006, True)

In score_scales(), with_columns() adds the score beside the count and sum. Without otherwise(), pl.when(...).then(...) gives a null score below the threshold. The two SAT rows show the boundary at eight and nine valid answers.

1
2
3
4
5
6
7
8
9
10
11
12
13
def score_scales(counts, min_valid):
    return counts.with_columns(
        score=pl.when(pl.col("n_valid") >= min_valid).then(
            pl.col("score_sum") / pl.col("n_valid")
        )
    )


scale_scores = score_scales(scale_counts, min_valid)
threshold_cases = ["R_2RgM2mAjjyks", "R_7Fo8MfjVtPde"]
scale_scores.filter(
    pl.col("scale") == "SAT", pl.col("ResponseId").is_in(threshold_cases)
).sort("ResponseId")
1
2
3
4
5
6
7
8
9
shape: (2, 5)
┌────────────────┬───────┬─────────┬───────────┬──────────┐
│ ResponseId     ┆ scale ┆ n_valid ┆ score_sum ┆ score    │
│ ---            ┆ ---   ┆ ---     ┆ ---       ┆ ---      │
│ str            ┆ str   ┆ u32     ┆ i64       ┆ f64      │
╞════════════════╪═══════╪═════════╪═══════════╪══════════╡
│ R_2RgM2mAjjyks ┆ SAT   ┆ 9       ┆ 33        ┆ 3.666667 │
│ R_7Fo8MfjVtPde ┆ SAT   ┆ 8       ┆ 22        ┆ null     │
└────────────────┴───────┴─────────┴───────────┴──────────┘

R_2RgM2mAjjyks has nine valid adjusted SAT items totaling 33, so its score is 33/9, about 3.67. R_7Fo8MfjVtPde has eight totaling 22, so under the stated nine-item rule its score is unavailable.

The threshold should also work when all ten answers are missing. The first table counts submissions by the number of valid items on each scale. The second applies the scoring functions to three constructed SAT forms with nine neutral answers, eight neutral answers, or no answers. All other items are blank, and a neutral answer scores 3 in either direction. These forms distinguish a valid mean of 3 from an unavailable mean, even when the sum returned by the calculation is zero.

1
2
3
4
5
6
7
8
9
10
11
count(scale_scores, scale, n_valid, available = !is.na(score))
neutral_items <- tibble(
  ResponseId = rep(c("nine", "eight", "zero"), each = 10),
  item = rep(paste0("SAT_", 1:10), times = 3),
  scale = "SAT",
  item_score = c(rep(3L, 9), NA, rep(3L, 8), NA, NA, rep(NA, 10))
)
neutral_items |>
  adjust_direction(reverse_items) |>
  aggregate_items() |>
  score_scales(min_valid)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# A tibble: 9 × 4
  scale n_valid available     n
  <chr>   <int> <lgl>     <int>
1 SAT         7 FALSE         1
2 SAT         8 FALSE        11
3 SAT         9 TRUE        106
4 SAT        10 TRUE        385
5 STR         0 FALSE         1
6 STR         6 FALSE         1
7 STR         8 FALSE         8
8 STR         9 TRUE         97
9 STR        10 TRUE        396
# A tibble: 3 × 5
  ResponseId scale n_valid score_sum score
  <chr>      <chr>   <int>     <int> <dbl>
1 nine       SAT         9        27     3
2 eight      SAT         8        24    NA
3 zero       SAT         0         0    NA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
scale_scores.group_by(
    "scale", "n_valid", available=pl.col("score").is_not_null()
).agg(n=pl.len()).sort("scale", "n_valid")
neutral_items = pl.DataFrame(
    {
        "ResponseId": ["nine"] * 10 + ["eight"] * 10 + ["zero"] * 10,
        "item": item_names[0:10] * 3,
        "scale": ["SAT"] * 30,
        "item_score": [3] * 9 + [None] + [3] * 8 + [None] * 2 + [None] * 10,
    }
)
neutral_scores = score_scales(
    aggregate_items(adjust_direction(neutral_items, reverse_items)), min_valid
)
neutral_scores.sort("n_valid", descending=True)
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
shape: (9, 4)
┌───────┬─────────┬───────────┬─────┐
│ scale ┆ n_valid ┆ available ┆ n   │
│ ---   ┆ ---     ┆ ---       ┆ --- │
│ str   ┆ u32     ┆ bool      ┆ u32 │
╞═══════╪═════════╪═══════════╪═════╡
│ SAT   ┆ 7       ┆ false     ┆ 1   │
│ SAT   ┆ 8       ┆ false     ┆ 11  │
│ SAT   ┆ 9       ┆ true      ┆ 106 │
│ SAT   ┆ 10      ┆ true      ┆ 385 │
│ STR   ┆ 0       ┆ false     ┆ 1   │
│ STR   ┆ 6       ┆ false     ┆ 1   │
│ STR   ┆ 8       ┆ false     ┆ 8   │
│ STR   ┆ 9       ┆ true      ┆ 97  │
│ STR   ┆ 10      ┆ true      ┆ 396 │
└───────┴─────────┴───────────┴─────┘
shape: (3, 5)
┌────────────┬───────┬─────────┬───────────┬───────┐
│ ResponseId ┆ scale ┆ n_valid ┆ score_sum ┆ score │
│ ---        ┆ ---   ┆ ---     ┆ ---       ┆ ---   │
│ str        ┆ str   ┆ u32     ┆ i64       ┆ f64   │
╞════════════╪═══════╪═════════╪═══════════╪═══════╡
│ nine       ┆ SAT   ┆ 9       ┆ 27        ┆ 3.0   │
│ eight      ┆ SAT   ┆ 8       ┆ 24        ┆ null  │
│ zero       ┆ SAT   ┆ 0       ┆ 0         ┆ null  │
└────────────┴───────┴─────────┴───────────┴───────┘

The constructed form with nine neutral answers scores 3. With eight or zero answers, the mean is missing. Across all 503 survey submissions, including later forms from the same person, 491 have a SAT score and 493 have a STR score. Can two forms have the same SAT mean with different numbers of valid answers?

1
2
3
scale_scores |>
  filter(scale == "SAT", score == 4) |>
  count(n_valid)
1
2
3
4
5
# A tibble: 2 × 2
  n_valid     n
    <int> <int>
1       9     3
2      10     5
1
2
3
scale_scores.filter(pl.col("scale") == "SAT", pl.col("score") == 4).group_by(
    "n_valid"
).agg(n=pl.len()).sort("n_valid")
1
2
3
4
5
6
7
8
9
shape: (2, 2)
┌─────────┬─────┐
│ n_valid ┆ n   │
│ ---     ┆ --- │
│ u32     ┆ u32 │
╞═════════╪═════╡
│ 9       ┆ 3   │
│ 10      ┆ 5   │
└─────────┴─────┘

Of the eight submissions with a SAT mean of 4, three have nine valid items and five have ten. The valid-item count shows how many answers contributed to each mean. A submission with too few answers also has a scale row, with its count beside the missing mean.

20.5 Assembling and describing the participant table

The participant table describes everyone selected for the analysis, including people without a score on one of the scales. For participant 0304, eight valid SAT answers are too few for a satisfaction score. A left join starting from the 500 selected submissions includes this person with a missing SAT mean.

In scale_scores, each submission has a SAT row and a STR row. Widening the table puts the two means side by side, each with its valid-item count. Each ResponseId and scale pair must occur just once so that each cell has only one source value.

In R, count() checks how often each submission and scale occur together. pivot_wider() puts score_SAT, score_STR, and their valid-item counts on one row per submission. The left joins then attach scores, attributes, and flags to the selected keys. same_keys checks whether the final response keys match that selection.

1
2
3
4
5
6
7
8
9
10
scale_scores |>
  count(ResponseId, scale, name = "rows") |>
  count(rows)
score_wide <- scale_scores |>
  pivot_wider(
    id_cols = ResponseId,
    names_from = scale,
    values_from = c(score, n_valid)
  )
dim(score_wide)
1
2
3
4
5
# A tibble: 1 × 2
   rows     n
  <int> <int>
1     1  1006
[1] 503   5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
participants <- selected_keys |>
  left_join(score_wide, by = join_by(ResponseId), relationship = "one-to-one") |>
  left_join(
    select(response_attributes, ResponseId, gender, region, birth_year),
    by = join_by(ResponseId),
    relationship = "one-to-one"
  ) |>
  left_join(
    select(audit, ResponseId, short_duration, attention_failed, straightlining),
    by = join_by(ResponseId),
    relationship = "one-to-one"
  )
glimpse(filter(participants, participant == "0304"))
tibble(
  rows = nrow(participants),
  distinct_participants = n_distinct(participants$participant),
  same_keys = setequal(participants$ResponseId, selected_keys$ResponseId),
  audit_rows = nrow(audit)
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Rows: 1
Columns: 12
$ ResponseId       <chr> "R_7Fo8MfjVtPde"
$ participant      <chr> "0304"
$ score_SAT        <dbl> NA
$ score_STR        <dbl> 2.1
$ n_valid_SAT      <int> 8
$ n_valid_STR      <int> 10
$ gender           <chr> "Female"
$ region           <chr> "Gyeongnam"
$ birth_year       <dbl> NA
$ short_duration   <lgl> FALSE
$ attention_failed <lgl> FALSE
$ straightlining   <lgl> NA
# A tibble: 1 × 4
   rows distinct_participants same_keys audit_rows
  <int>                 <int> <lgl>          <int>
1   500                   500 TRUE             503

In Polars, is_unique() checks that each response/scale pair occurs once before pivot() gives one row per submission. Sorting the scales sets their first-appearance order and hence the column order. The left joins with validate="1:1" attach scores, attributes, and flags to the 500 selected responses. Comparing sorted response keys checks membership regardless of row order.

1
2
3
4
5
scale_scores.select("ResponseId", "scale").is_unique().all()
score_wide = scale_scores.sort("ResponseId", "scale").pivot(
    on="scale", index="ResponseId", values=["score", "n_valid"]
)
score_wide.shape
1
2
True
(503, 5)
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
participants = (
    selected_keys.join(score_wide, on="ResponseId", how="left", validate="1:1")
    .join(
        response_attributes.select("ResponseId", "gender", "region", "birth_year"),
        on="ResponseId",
        how="left",
        validate="1:1",
    )
    .join(
        audit.select(
            "ResponseId", "short_duration", "attention_failed", "straightlining"
        ),
        on="ResponseId",
        how="left",
        validate="1:1",
    )
)
participants.filter(pl.col("participant") == "0304").glimpse()
{
    "rows": participants.height,
    "distinct_participants": participants["participant"].n_unique(),
    "same_keys": participants["ResponseId"]
    .sort()
    .equals(selected_keys["ResponseId"].sort()),
    "audit_rows": audit.height,
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Rows: 1
Columns: 12
$ ResponseId        <str> 'R_7Fo8MfjVtPde'
$ participant       <str> '0304'
$ score_SAT         <f64> null
$ score_STR         <f64> 2.1
$ n_valid_SAT       <u32> 8
$ n_valid_STR       <u32> 10
$ gender            <str> 'Female'
$ region            <str> 'Gyeongnam'
$ birth_year        <i64> null
$ short_duration   <bool> False
$ attention_failed <bool> False
$ straightlining   <bool> null
{'rows': 500, 'distinct_participants': 500, 'same_keys': True, 'audit_rows': 503}

Participant 0304 has a stress score of 2.1 from ten valid answers. Eight valid SAT answers are too few for a satisfaction mean. Straightlining requires valid answers to all 20 items, so it is undetermined on this form. The birth year is missing because the recorded value is 999, the code for No answer.

The participant table has 500 rows, but a score mean or a flag rate may describe fewer people. In the R summary, pivot_longer() puts the two scales in one score column. For each scale, n_observed counts the people who contribute to the mean. sd() reports the sample standard deviation, and quantile() interpolates linearly for the quartiles.

The flags require a separate denominator. For each flag, defined counts those who could be assessed and raised counts those with a true flag. A missing flag contributes to neither count.

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
participants |>
  pivot_longer(
    c(score_SAT, score_STR),
    names_to = "scale",
    names_prefix = "score_",
    values_to = "score"
  ) |>
  summarise(
    participants = n(),
    n_observed = sum(!is.na(score)),
    mean = mean(score, na.rm = TRUE),
    sd = sd(score, na.rm = TRUE),
    median = median(score, na.rm = TRUE),
    q1 = quantile(score, 0.25, na.rm = TRUE, names = FALSE),
    q3 = quantile(score, 0.75, na.rm = TRUE, names = FALSE),
    .by = scale
  )
participants |>
  pivot_longer(
    c(short_duration, attention_failed, straightlining),
    names_to = "flag",
    values_to = "value"
  ) |>
  summarise(
    participants = n(),
    defined = sum(!is.na(value)),
    raised = sum(value, na.rm = TRUE),
    .by = flag
  ) |>
  arrange(flag)
1
2
3
4
5
6
7
8
9
10
11
# A tibble: 2 × 8
  scale participants n_observed  mean    sd median    q1    q3
  <chr>        <int>      <int> <dbl> <dbl>  <dbl> <dbl> <dbl>
1 SAT            500        489  3.01 0.932      3   2.3  3.78
2 STR            500        491  3.06 0.989      3   2.3  3.8 
# A tibble: 3 × 4
  flag             participants defined raised
  <chr>                   <int>   <int>  <int>
1 attention_failed          500     500      5
2 short_duration            500     500      4
3 straightlining            500     310      3

In Polars, unpivot() creates one column of scale scores and str.strip_prefix() removes score_ from the scale names. count() counts observed scores, whereas pl.len() counts participants. std(ddof=1) gives the sample standard deviation, and quantile(interpolation="linear") interpolates between ordered scores for the quartiles. For Boolean flags, count() gives the number assessed and sum() the number flagged.

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
score_col = pl.col("score")
participants.unpivot(
    index="participant",
    on=["score_SAT", "score_STR"],
    variable_name="scale",
    value_name="score",
).with_columns(pl.col("scale").str.strip_prefix("score_")).group_by("scale").agg(
    participants=pl.len(),
    n_observed=score_col.count(),
    mean=score_col.mean(),
    sd=score_col.std(ddof=1),
    median=score_col.median(),
    q1=score_col.quantile(0.25, interpolation="linear"),
    q3=score_col.quantile(0.75, interpolation="linear"),
).sort("scale")
participants.unpivot(
    index="participant",
    on=["short_duration", "attention_failed", "straightlining"],
    variable_name="flag",
    value_name="value",
).group_by("flag").agg(
    participants=pl.len(),
    defined=pl.col("value").count(),
    raised=pl.col("value").sum(),
).sort("flag")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
shape: (2, 8)
┌───────┬──────────────┬────────────┬──────────┬──────────┬────────┬─────┬──────────┐
│ scale ┆ participants ┆ n_observed ┆ mean     ┆ sd       ┆ median ┆ q1  ┆ q3       │
│ ---   ┆ ---          ┆ ---        ┆ ---      ┆ ---      ┆ ---    ┆ --- ┆ ---      │
│ str   ┆ u32          ┆ u32        ┆ f64      ┆ f64      ┆ f64    ┆ f64 ┆ f64      │
╞═══════╪══════════════╪════════════╪══════════╪══════════╪════════╪═════╪══════════╡
│ SAT   ┆ 500          ┆ 489        ┆ 3.01018  ┆ 0.932429 ┆ 3.0    ┆ 2.3 ┆ 3.777778 │
│ STR   ┆ 500          ┆ 491        ┆ 3.060647 ┆ 0.988796 ┆ 3.0    ┆ 2.3 ┆ 3.8      │
└───────┴──────────────┴────────────┴──────────┴──────────┴────────┴─────┴──────────┘
shape: (3, 4)
┌──────────────────┬──────────────┬─────────┬────────┐
│ flag             ┆ participants ┆ defined ┆ raised │
│ ---              ┆ ---          ┆ ---     ┆ ---    │
│ str              ┆ u32          ┆ u32     ┆ u32    │
╞══════════════════╪══════════════╪═════════╪════════╡
│ attention_failed ┆ 500          ┆ 500     ┆ 5      │
│ short_duration   ┆ 500          ┆ 500     ┆ 4      │
│ straightlining   ┆ 500          ┆ 310     ┆ 3      │
└──────────────────┴──────────────┴─────────┴────────┘

Of the 491 submissions with SAT scores, two were later forms from people whose earlier forms were selected. The SAT mean of about 3.01 therefore describes 489 of the 500 participants.

For straightlining, 3 of the 310 participants with complete item sets show the pattern, about 1 percent. Across all 500 participants, 3 have a confirmed pattern and 190 could not be assessed. These are different descriptions of the same flags, with the assessed group providing the denominator for the pattern rate.

Activities of the selected responses

The same submission selection determines whose activity answers enter a summary. A participant who selects three ways of relieving stress contributes three choices but only one answer to the activity question. The denominator for each percentage is the number of selected participants who answered, including those who chose None of the above.

In R, that count comes from Q_MULTI before separate_longer_delim() splits the choices on the selected forms. A left join from option_labels includes every listed option, with zero for an unchosen one. If nobody answered, the percentages are unavailable.

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
option_labels <- tibble(
  option = c("1", "2", "3", "4", "5", "6", "7", "8"),
  label = c(
    "Exercise", "Listening to music", "Enough sleep", "Talking with someone",
    "Games", "Good food", "Other", "None of the above"
  )
)
selected_activity <- selected_keys |>
  left_join(
    select(responses, ResponseId, Q_MULTI),
    by = join_by(ResponseId),
    relationship = "one-to-one"
  )
answered <- sum(!is.na(selected_activity$Q_MULTI))
activity_options <- selected_activity |>
  mutate(option = Q_MULTI) |>
  separate_longer_delim(option, delim = ";")
option_labels |>
  left_join(
    count(filter(activity_options, !is.na(option)), option),
    by = join_by(option),
    relationship = "one-to-one"
  ) |>
  mutate(
    n = coalesce(n, 0L),
    percent = if (answered > 0) 100 * n / answered else NA_real_
  )
c(
  option_rows = nrow(activity_options),
  responses = n_distinct(activity_options$ResponseId),
  answered = answered,
  participant_rows = nrow(participants)
)
1
2
3
4
5
6
7
8
9
10
11
12
13
# A tibble: 8 × 4
  option label                    n percent
  <chr>  <chr>                <int>   <dbl>
1 1      Exercise               176   35.9 
2 2      Listening to music     223   45.5 
3 3      Enough sleep           200   40.8 
4 4      Talking with someone   202   41.2 
5 5      Games                  106   21.6 
6 6      Good food              146   29.8 
7 7      Other                   31    6.33
8 8      None of the above       10    2.04
     option_rows        responses         answered participant_rows 
            1104              500              490              500 

In Polars, one row represents one selected response before str.split(";") and explode(). Counting nonnull Q_MULTI answers at that point gives the denominator for every option. With keep_nulls=True, explode() gives an unanswered response a row. Only nonnull options enter the counts.

Joining the counts to the labels includes every option, and fill_null(0) gives an unchosen option a count of zero. Percentages are unavailable if nobody answered. The activity table is separate from the participant table, so expanding several choices does not duplicate a person’s scale scores.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
option_labels = pl.DataFrame(
    {
        "option": ["1", "2", "3", "4", "5", "6", "7", "8"],
        "label": [
            "Exercise",
            "Listening to music",
            "Enough sleep",
            "Talking with someone",
            "Games",
            "Good food",
            "Other",
            "None of the above",
        ],
    }
)
selected_activity = selected_keys.join(
    responses.select("ResponseId", "Q_MULTI"),
    on="ResponseId",
    how="left",
    validate="1:1",
)
answered = selected_activity["Q_MULTI"].drop_nulls().len()
activity_options = selected_activity.with_columns(
    option=pl.col("Q_MULTI").str.split(";")
).explode("option", keep_nulls=True)
selection_counts = (
    activity_options.drop_nulls("option").group_by("option").agg(n=pl.len())
)
option_labels.join(
    selection_counts, on="option", how="left", validate="1:1"
).with_columns(pl.col("n").fill_null(0)).with_columns(
    percent=pl.when(pl.lit(answered) > 0).then(100 * pl.col("n") / answered)
).sort("option")
{
    "option_rows": activity_options.height,
    "responses": activity_options["ResponseId"].n_unique(),
    "answered": answered,
    "participant_rows": participants.height,
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
shape: (8, 4)
┌────────┬──────────────────────┬─────┬───────────┐
│ option ┆ label                ┆ n   ┆ percent   │
│ ---    ┆ ---                  ┆ --- ┆ ---       │
│ str    ┆ str                  ┆ u32 ┆ f64       │
╞════════╪══════════════════════╪═════╪═══════════╡
│ 1      ┆ Exercise             ┆ 176 ┆ 35.918367 │
│ 2      ┆ Listening to music   ┆ 223 ┆ 45.510204 │
│ 3      ┆ Enough sleep         ┆ 200 ┆ 40.816327 │
│ 4      ┆ Talking with someone ┆ 202 ┆ 41.22449  │
│ 5      ┆ Games                ┆ 106 ┆ 21.632653 │
│ 6      ┆ Good food            ┆ 146 ┆ 29.795918 │
│ 7      ┆ Other                ┆ 31  ┆ 6.326531  │
│ 8      ┆ None of the above    ┆ 10  ┆ 2.040816  │
└────────┴──────────────────────┴─────┴───────────┘
{'option_rows': 1104, 'responses': 500, 'answered': 490, 'participant_rows': 500}

Of the 490 people who answered, 223 chose listening to music, or 45.5 percent. The 490 include ten people who chose None of the above. In all, those respondents made 1,094 selections. Ten other people left the question blank, bringing the expanded table to 1,104 rows.

One participant, two submissions

The summaries use the chosen submission’s answers, so the selection must remain traceable from each participant row. Participant 0449 completed two forms and gave different answers on each. Which form accounts for this person’s satisfaction and stress scores? ResponseId connects the participant row to the scores, item answers, and selection decision for that submission.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
trace_ids <- filter(audit, participant == "0449")$ResponseId
audit |>
  filter(participant == "0449") |>
  select(participant, ResponseId, selection_reason) |>
  left_join(scale_scores, by = join_by(ResponseId), relationship = "one-to-many") |>
  arrange(selection_reason, scale)
count(filter(item_table, ResponseId %in% trace_ids), ResponseId, item_status)
select(filter(participants, participant == "0449"), ResponseId, score_SAT, score_STR)
c(
  participants = nrow(participants),
  submissions = nrow(audit),
  scale_rows = nrow(scale_scores),
  item_rows = nrow(item_table)
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# A tibble: 4 × 7
  participant ResponseId     selection_reason   scale n_valid score_sum score
  <chr>       <chr>          <chr>              <chr>   <int>     <int> <dbl>
1 0449        R_EY0X7OFCR5OJ earliest completed SAT        10        29   2.9
2 0449        R_EY0X7OFCR5OJ earliest completed STR        10        22   2.2
3 0449        R_D0utZ1mh1tHG later completed    SAT        10        33   3.3
4 0449        R_D0utZ1mh1tHG later completed    STR        10        25   2.5
# A tibble: 2 × 3
  ResponseId     item_status     n
  <chr>          <chr>       <int>
1 R_D0utZ1mh1tHG observed       20
2 R_EY0X7OFCR5OJ observed       20
# A tibble: 1 × 3
  ResponseId     score_SAT score_STR
  <chr>              <dbl>     <dbl>
1 R_EY0X7OFCR5OJ       2.9       2.2
participants  submissions   scale_rows    item_rows 
         500          503         1006        10060 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
trace = audit.filter(pl.col("participant") == "0449").select(
    "participant", "ResponseId", "selection_reason"
)
trace.join(scale_scores, on="ResponseId", how="left", validate="1:m").sort(
    "selection_reason", "scale"
)
trace_ids = trace["ResponseId"].to_list()
item_table.filter(pl.col("ResponseId").is_in(trace_ids)).group_by(
    "ResponseId", "item_status"
).agg(n=pl.len()).sort("ResponseId")
participants.filter(pl.col("participant") == "0449").select(
    "ResponseId", "score_SAT", "score_STR"
)
{
    "participants": participants.height,
    "submissions": audit.height,
    "scale_rows": scale_scores.height,
    "item_rows": item_table.height,
}
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
shape: (4, 7)
┌─────────────┬────────────────┬────────────────────┬───────┬─────────┬───────────┬───────┐
│ participant ┆ ResponseId     ┆ selection_reason   ┆ scale ┆ n_valid ┆ score_sum ┆ score │
│ ---         ┆ ---            ┆ ---                ┆ ---   ┆ ---     ┆ ---       ┆ ---   │
│ str         ┆ str            ┆ str                ┆ str   ┆ u32     ┆ i64       ┆ f64   │
╞═════════════╪════════════════╪════════════════════╪═══════╪═════════╪═══════════╪═══════╡
│ 0449        ┆ R_EY0X7OFCR5OJ ┆ earliest completed ┆ SAT   ┆ 10      ┆ 29        ┆ 2.9   │
│ 0449        ┆ R_EY0X7OFCR5OJ ┆ earliest completed ┆ STR   ┆ 10      ┆ 22        ┆ 2.2   │
│ 0449        ┆ R_D0utZ1mh1tHG ┆ later completed    ┆ SAT   ┆ 10      ┆ 33        ┆ 3.3   │
│ 0449        ┆ R_D0utZ1mh1tHG ┆ later completed    ┆ STR   ┆ 10      ┆ 25        ┆ 2.5   │
└─────────────┴────────────────┴────────────────────┴───────┴─────────┴───────────┴───────┘
shape: (2, 3)
┌────────────────┬─────────────┬─────┐
│ ResponseId     ┆ item_status ┆ n   │
│ ---            ┆ ---         ┆ --- │
│ str            ┆ str         ┆ u32 │
╞════════════════╪═════════════╪═════╡
│ R_D0utZ1mh1tHG ┆ observed    ┆ 20  │
│ R_EY0X7OFCR5OJ ┆ observed    ┆ 20  │
└────────────────┴─────────────┴─────┘
shape: (1, 3)
┌────────────────┬───────────┬───────────┐
│ ResponseId     ┆ score_SAT ┆ score_STR │
│ ---            ┆ ---       ┆ ---       │
│ str            ┆ f64       ┆ f64       │
╞════════════════╪═══════════╪═══════════╡
│ R_EY0X7OFCR5OJ ┆ 2.9       ┆ 2.2       │
└────────────────┴───────────┴───────────┘
{'participants': 500, 'submissions': 503, 'scale_rows': 1006, 'item_rows': 10060}

Both submissions from 0449 have 20 scorable answers. The participant row uses the earlier form, R_EY0X7OFCR5OJ, so this person’s satisfaction score is 2.9 and their stress score is 2.2. Using the later form would give 3.3 and 2.5.

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