---
title: "Procedural exclusions"
author: Pablo Rogers
execute:
  echo: true
---

```{r}
#| label: setup-01
#| include: false
#| warning: false

# Load required packages for data manipulation and table formatting
suppressPackageStartupMessages({
  library(tidyverse)
  library(gt)
})
```

## Data reading and preparation

The `data.csv` file contains the raw survey responses (separator `;`).
In this step, dropout records are removed, variables for the analytical 
flow are selected, and the total response time (`TIME`) is derived.

```{r}
#| label: data-reading
#| message: false
#| warning: false

# Read raw dataset
raw_data <- suppressMessages(
    read_csv2(
        here::here("Data", "InputData", "data.csv"),
        show_col_types = FALSE
    )
)

# Identify respondents who dropped out (no basic ID or zero valid answers)
prepared_data <- raw_data |>
    mutate(
        dropout = is.na(ID) | rowSums(across(Q1:Q26, \(x) !is.na(x))) == 0
    )

# Filter dropouts, convert scale items to numeric, and calculate total response time in seconds
imported_data <- prepared_data |>
    filter(!dropout) |>
    select(ID, CREATED, MODIFIED, CQ1, CQ2, CQ3, Q1:Q26) |>
    mutate(
        across(c(CQ1, CQ2, CQ3, Q1:Q26), as.numeric),
        CREATED_dt = as.POSIXct(CREATED, format = "%d/%m/%Y %H:%M", tz = "UTC"),
        MODIFIED_dt = as.POSIXct(MODIFIED, format = "%d/%m/%Y %H:%M", tz = "UTC"),
        TIME = as.numeric(difftime(MODIFIED_dt, CREATED_dt, units = "secs"))
    ) |>
    select(-CREATED_dt, -MODIFIED_dt)

dataset_structure <- tibble::tibble(
  `Group` = c("Identification", "Timing", "Attention Checks", "WHOQOL-Bref Scale"),
  `Variables` = c("ID", "CREATED, MODIFIED, TIME", "CQ1, CQ2, CQ3", "Q1 to Q26 (26 items)"),
  `Class / Type` = c("Numeric (Double)", "Date-time / Numeric (s)", "Binary (0/1)", "Ordinal (1 to 5)"),
  `Description` = c(
    "Unique respondent identifier",
    "Survey timestamps and total response duration in seconds",
    "Quality control check items (1 = passed, 0 = failed)",
    "Self-reported quality of life items"
  )
)

dataset_structure |>
  knitr::kable(
    caption = "Structure and variable dictionary of the prepared survey dataset (`imported_data`)"
  )
```

## Procedural exclusions (Level 1)

- `CQ == 1`: the respondent passed the quality control item.
- `CQ == 0`: the respondent failed the quality control item.

```{r}
#| label: level-1

# Evaluate procedural exclusion criteria (time, quality control fails, and missing values)
level1_data <- imported_data |>
    mutate(
        qc_fails = rowSums(across(CQ1:CQ3, \(x) x != 1), na.rm = TRUE),
        na_count = rowSums(across(Q1:Q26, is.na)),
        excl_time = TIME < 208,
        excl_qc = qc_fails >= 2,
        excl_na = na_count > 5,
        level1_excluded = excl_time | excl_qc | excl_na
    )

# Build a log of all excluded respondents and their specific exclusion criterion
exclusion_log <- bind_rows(
    prepared_data |>
        filter(dropout) |>
        transmute(
            ID,
            criterion = "dropout",
            value     = NA_real_,
            detail    = "No valid responses in Q1-Q26"
        ),
    level1_data |>
        filter(excl_time) |>
        transmute(
            ID,
            criterion = "fast_time",
            value     = TIME,
            detail    = paste0("TIME = ", TIME, " s")
        ),
    level1_data |>
        filter(excl_qc) |>
        transmute(
            ID,
            criterion = "qc_fails",
            value     = qc_fails,
            detail    = paste0("QC fails = ", qc_fails)
        ),
    level1_data |>
        filter(excl_na) |>
        transmute(
            ID,
            criterion = "excessive_missings",
            value     = as.numeric(na_count),
            detail    = paste0("Missings in Q1-Q26 = ", na_count)
        )
) |>
    distinct(ID, criterion, .keep_all = TRUE)

# Export the exclusion log
write_csv2(
  exclusion_log,
  here::here(
    "Output", "DataAppendixOutput", "Tables", "exclusion_log.csv"
  )
)

# Keep original item responses for the Level 2 response-pattern indicators
eligible_data <- level1_data |>
    filter(!level1_excluded) |>
    select(ID, CQ1, CQ2, CQ3, TIME, Q1:Q26)
```

### Level 1 Summary

```{r}
#| label: tbl-level-1-summary
#| tbl-cap: "Procedural exclusions summary"

# Generate a summary table of procedural exclusions during Level 1
table_level1 <- tibble(
    Step = c(
        "Raw data",
        "Dropouts removed",
        "Excluded by time (< 208 s)",
        "Excluded by QC (≥ 2 fails)",
        "Excluded by missings (> 5 in Q1-Q26)",
        "Eligible for Level 2",
        "Remaining NAs in Q1-Q26"
    ),
    N = c(
        nrow(raw_data),
        sum(prepared_data$dropout, na.rm = TRUE),
        sum(level1_data$excl_time, na.rm = TRUE),
        sum(level1_data$excl_qc, na.rm = TRUE),
        sum(level1_data$excl_na, na.rm = TRUE),
        nrow(eligible_data),
        sum(is.na(eligible_data |> select(Q1:Q26)))
    )
)

# Save table
write_csv2(
  table_level1,
  here::here("Output", "Results", "Tables", "tbl-level-1-summary.csv")
)

# Print table
table_level1 |>
    knitr::kable()
```

```{r}
#| label: level-1-export
#| include: false

# Save eligible respondents data for Level 2 post-hoc indicators analysis
write_csv2(
  eligible_data,
  here::here("Data", "IntermediateData", "whoqol_imported.csv")
)
```
