# Table A-5: Linearity test with double bootstrap for estimated P (description1.tex)
library(here)
library(tidyverse)
library(gt)
source(here("04-topics/rep-chv2011/Rcode/chv2011-data-prep.R"))
source(here("04-topics/rep-chv2011/Rcode/chv2011-table4a-core.R"))
source(here("04-topics/rep-chv2011/Rcode/chv2011-gt-quarto.R"))

data_path <- chv2011_table4a_data_path()
if (!file.exists(data_path)) {
  export_chv2011_table4a_data(data_path)
}

env <- new.env()
load(data_path, envir = env)
data <- env$data

res <- chv2011_table4a_run_a5(data)

table_data <- tibble(
  polynomial_order = res$degrees,
  p_value_boot = res$p_boot,
  reject = if_else(res$p_boot < res$critical_rw, "Reject", "Fail to reject")
) |>
  mutate(cell = chv2011_fmt_num(p_value_boot)) |>
  select(polynomial_order, cell, reject)

gt_tbl <- table_data |>
  chv2011_quarto_blank_df() |>
  gt() |>
  tab_header(
    title = "Table A-5",
    subtitle = sprintf(
      "Linearity of E(Y|X,P) — double bootstrap for estimated P; RW critical (10%%) = %.4f; joint: %s",
      res$critical_rw,
      if (res$reject_rw) "Reject" else "Fail to reject"
    )
  ) |>
  cols_label(
    polynomial_order = "Degree of polynomial",
    cell = "Bootstrap p-value",
    reject = "Decision (RW)"
  )

save(table_data, gt_tbl, res, file = here("04-topics/rep-chv2011/Rcode/Table_A5.RData"))
