library(readxl)
df_final <- read_excel("C:/Users/pc/Documents/my_thesis/research_data/r_EDA/final_EDA.xlsx")
df <- read_excel("C:/Users/pc/Documents/my_thesis/research_data/r_EDA/final_LOS_EDA.xlsx")
# Keep the first occurrence of each MRN
df_final <- df_final[!duplicated(df_final$MRN), ]

# Display duplicate removal results
cat("Remaining records:", nrow(df_final), "\n")
## Remaining records: 5515
cat("Removed records:", 6309 - nrow(df_final), "\n")
## Removed records: 794
cat("Remaining duplicated MRNs:", sum(duplicated(df_final$MRN)), "\n")
## Remaining duplicated MRNs: 0
clinical_limits <- list(
  hr = c(30, 250),
  sbp = c(30, 300),
  dbp = c(20, 180),
  rr = c(5, 80),
  temp = c(30, 45),
  spo2 = c(0, 101),
  rbs = c(20, 700),
  Pain_score = c(0, 10),
  sodium = c(100, 180),
  potassium = c(1.5, 10),
  wbc = c(0.1, 100),
  rbc = c(0.5, 10),
  basophil = c(0, 20),
  eosinophil = c(0, 40),
  monocyte = c(0, 30),
  neutrophil = c(0, 100),
  lymphocyte = c(0, 100),
  hemoglobin = c(2, 25),
  hematocrit = c(5, 80),
  mcv = c(50, 150),
  mch = c(10, 50),
  mchc = c(20, 45),
  mpv = c(5, 20),
  plt = c(5, 2000),
  ast_sgot = c(0, 5000),
  alt_sgpt = c(0, 5000),
  creatinine = c(0.1, 20),
  oxy_use = c(0, 100),
  Age_years = c(13, 120)
)
df_original <- df_final
cat("Replacing values outside clinical limits...\n")
## Replacing values outside clinical limits...
for (col in names(clinical_limits)) {
  
  low <- clinical_limits[[col]][1]
  high <- clinical_limits[[col]][2]
  
  outliers <- !is.na(df_final[[col]]) &
    (df_final[[col]] < low | df_final[[col]] > high)
  
  n_outliers <- sum(outliers)
  
  df_final[[col]][outliers] <- NA
  
  cat(col, ":", n_outliers, "values replaced with NA\n")
}
## hr : 3 values replaced with NA
## sbp : 23 values replaced with NA
## dbp : 23 values replaced with NA
## rr : 2 values replaced with NA
## temp : 73 values replaced with NA
## spo2 : 183 values replaced with NA
## rbs : 5 values replaced with NA
## Pain_score : 0 values replaced with NA
## sodium : 33 values replaced with NA
## potassium : 14 values replaced with NA
## wbc : 2 values replaced with NA
## rbc : 15 values replaced with NA
## basophil : 0 values replaced with NA
## eosinophil : 1 values replaced with NA
## monocyte : 15 values replaced with NA
## neutrophil : 7 values replaced with NA
## lymphocyte : 1 values replaced with NA
## hemoglobin : 5 values replaced with NA
## hematocrit : 7 values replaced with NA
## mcv : 21 values replaced with NA
## mch : 29 values replaced with NA
## mchc : 15 values replaced with NA
## mpv : 82 values replaced with NA
## plt : 4 values replaced with NA
## ast_sgot : 6 values replaced with NA
## alt_sgpt : 0 values replaced with NA
## creatinine : 11 values replaced with NA
## oxy_use : 0 values replaced with NA
## Age_years : 0 values replaced with NA
library(dplyr)
library(DT)
## Warning: package 'DT' was built under R version 4.4.3
numeric_cols <- c(
  "hr", "sbp", "dbp", "rr", "temp", "spo2",
  "rbs", "Pain_score", "sodium", "potassium",
  "wbc", "rbc", "basophil", "eosinophil",
  "monocyte", "neutrophil", "lymphocyte",
  "hemoglobin", "hematocrit", "mcv", "mch",
  "mchc", "mpv", "plt", "ast_sgot", "alt_sgpt",
  "creatinine", "oxy_use", "Age_years"
)
calculate_skewness <- function(x) {
  
  x <- x[!is.na(x)]
  n <- length(x)
  
  if (n < 3) return(NA)
  
  m <- mean(x)
  s <- sd(x)
  
  if (s == 0) return(0)
  
  skew <- (n / ((n - 1) * (n - 2))) *
    sum(((x - m) / s)^3)
  
  return(skew)
}
summary <- data.frame(
  Variable = numeric_cols,
  
  Count = sapply(
    df_final[numeric_cols],
    function(x) sum(!is.na(x))
  ),
  
  Missing = sapply(
    df_final[numeric_cols],
    function(x) sum(is.na(x))
  ),
  
  `Missing (%)` = sapply(
    df_final[numeric_cols],
    function(x) mean(is.na(x)) * 100
  ),
  
  Mean = sapply(
    df_final[numeric_cols],
    function(x) mean(x, na.rm = TRUE)
  ),
  
  Std = sapply(
    df_final[numeric_cols],
    function(x) sd(x, na.rm = TRUE)
  ),
  
  Min = sapply(
    df_final[numeric_cols],
    function(x) min(x, na.rm = TRUE)
  ),
  
  `25%` = sapply(
    df_final[numeric_cols],
    function(x) quantile(x, 0.25, na.rm = TRUE)
  ),
  
  Median = sapply(
    df_final[numeric_cols],
    function(x) median(x, na.rm = TRUE)
  ),
  
  `75%` = sapply(
    df_final[numeric_cols],
    function(x) quantile(x, 0.75, na.rm = TRUE)
  ),
  
  Max = sapply(
    df_final[numeric_cols],
    function(x) max(x, na.rm = TRUE)
  ),
  
  Skewness = sapply(
    df_final[numeric_cols],
    calculate_skewness
  )
)

summary[-1] <- round(summary[-1], 2)

summary
# ============================================================
# AGE CATEGORIZATION
# ============================================================

df <- df %>%
  mutate(
    Age_group = case_when(
      Age_years <= 24 ~ "≤24",
      Age_years >= 25 & Age_years <= 29 ~ "25–29",
      Age_years >= 30 & Age_years <= 40 ~ "30–40",
      Age_years >= 41 & Age_years <= 50 ~ "41–50",
      Age_years > 51 ~ ">51",
      TRUE ~ NA_character_
    )
  )


df_final <- df_final %>%
  mutate(
    Age_group = case_when(
      Age_years <= 24 ~ "≤24",
      Age_years >= 25 & Age_years <= 29 ~ "25–29",
      Age_years >= 30 & Age_years <= 40 ~ "30–40",
      Age_years >= 41 & Age_years <= 50 ~ "41–50",
      Age_years > 51 ~ ">51",
      TRUE ~ NA_character_
    )
  )


# ============================================================
# SET ORDER OF AGE CATEGORIES
# ============================================================

df$Age_group <- factor(
  df$Age_group,
  levels = c("≤24", "25–29", "30–40", "41–50", ">51")
)

df_final$Age_group <- factor(
  df_final$Age_group,
  levels = c("≤24", "25–29", "30–40", "41–50", ">51")
)

table(df$Age_group, useNA = "ifany")
## 
##   ≤24 25–29 30–40 41–50   >51  <NA> 
##   198   199   405   427  2198    55
table(df_final$Age_group, useNA = "ifany")
## 
##   ≤24 25–29 30–40 41–50   >51  <NA> 
##   286   247   556   680  3663    83
datatable(
  summary,
  options = list(
    pageLength = 10,
    scrollX = TRUE,
    searching = TRUE,
    ordering = TRUE
  ),
  rownames = FALSE
)
selected_vars <- c(
  "Age_years",
  "hr",
  "sbp",
  "rr",
  "temp",
  "spo2",
  "rbs",
  "hemoglobin",
  "wbc"
)
library(tidyr)
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.4.3
hist_data <- df_final %>%
  select(all_of(selected_vars)) %>%
  pivot_longer(
    cols = everything(),
    names_to = "Variable",
    values_to = "Value"
  )
hist_data$Variable <- factor(
  hist_data$Variable,
  levels = selected_vars,
  labels = c(
    "Age (years)",
    "Heart rate (bpm)",
    "Systolic BP (mmHg)",
    "Respiratory rate (breaths/min)",
    "Temperature (\u00B0C)",
    "SpO\u2082 (%)",
    "Random blood sugar",
    "Hemoglobin (g/dL)",
    "White blood cell count"
  )
)
p <- ggplot(
  hist_data,
  aes(x = Value)
) +
  geom_histogram(
    aes(y = after_stat(density)),
    bins = 30,
    fill = "steelblue",
    color = "white",
    alpha = 0.85
  ) +
  geom_density(
    linewidth = 0.9,
    color = "black",
    na.rm = TRUE
  ) +
  facet_wrap(
    ~ Variable,
    scales = "free",
    ncol = 2
  ) +
  labs(
    x = NULL,
    y = "Density"
  ) +
  theme_classic(base_size = 11) +
  theme(
    strip.background = element_rect(
      fill = "grey95",
      color = "grey50",
      linewidth = 0.5
    ),
    strip.text = element_text(
      face = "bold",
      size = 10
    ),
    axis.text = element_text(
      color = "black"
    ),
    axis.title.y = element_text(
      face = "bold"
    ),
    panel.spacing = unit(1.1, "lines"),
    plot.margin = margin(10, 10, 10, 10)
  )

p
## Warning: Removed 4377 rows containing non-finite outside the scale range
## (`stat_bin()`).

    corrilation analysis
numeric_var <- c(
  "hr",
  "sbp",
  "dbp",
  "rr",
  "temp",
  "spo2",
  "rbs",
  "Pain_score",
  "sodium",
  "potassium",
  "wbc",
  "rbc",
  "basophil",
  "eosinophil",
  "monocyte",
  "neutrophil",
  "lymphocyte",
  "hemoglobin",
  "hematocrit",
  "mcv",
  "mch",
  "mchc",
  "mpv",
  "plt",
  "ast_sgot",
  "alt_sgpt",
  "creatinine",
  "Age_years"
)

numeric_var <- numeric_var[
  numeric_var %in% names(df_final)
]

corr <- cor(
  df_final[, numeric_var, drop = FALSE],
  use = "pairwise.complete.obs",
  method = "pearson"
)

corr_check <- corr
diag(corr_check) <- NA

keep <- apply(
  abs(corr_check) >= 0.40,
  1,
  function(x) any(x, na.rm = TRUE)
)

corr_selected <- corr[
  keep,
  keep,
  drop = FALSE
]

if (nrow(corr_selected) >= 2) {
  
  library(corrplot)
  
  corrplot(
    corr_selected,
    method = "color",
    type = "upper",
    order = "hclust",
    diag = FALSE,
    addCoef.col = "black",
    number.cex = 0.65,
    tl.col = "black",
    tl.cex = 0.95,
    tl.srt = 90,
    col = colorRampPalette(
      c("blue", "white", "red")
    )(200)
  )
  
} else {
  
  message(
    "Fewer than two variables met the |r| >= 0.40 criterion."
  )
}
## Warning: package 'corrplot' was built under R version 4.4.3
## corrplot 0.95 loaded

# 1. Gender
gender_map <- c(
  "0" = "Female",
  "1" = "Male"
)

df$Gender <- unname(
  gender_map[as.character(df$Gender)]
)


# 2. Admission Source
admission_map <- c(
  "1" = "Emergency",
  "2" = "Medical Ward",
  "3" = "Surgical Ward",
  "4" = "Pediatrics Ward",
  "5" = "Maternity Ward",
  "6" = "Orthopedic Ward",
  "7" = "HDU",
  "8" = "Other"
)

df$Admission_source <- unname(
  admission_map[as.character(df$Admission_source)]
)


# 3. Diagnosis Superclass
diag_map <- c(
  "1" = "Cardiovascular Disease",
  "2" = "Respiratory Disease",
  "3" = "Neurological Disease",
  "4" = "Sepsis / Infection",
  "5" = "Gastrointestinal / Hepatic Disease",
  "6" = "Trauma / Toxicology",
  "7" = "Endocrine / Metabolic Disease",
  "8" = "Renal Disease",
  "9" = "Thromboembolism",
  "10" = "Malignancy",
  "11" = "Multi-organ Failure",
  "12" = "Obstetric / Gynecology",
  "13" = "Autoimmune / Systemic Disease",
  "14" = "Other"
)

df$diag_superclass <- unname(
  diag_map[as.character(df$diag_superclass)]
)
Q1 <- quantile(df$LOS_days, 0.25, na.rm = TRUE)
Q3 <- quantile(df$LOS_days, 0.75, na.rm = TRUE)

IQR_value <- Q3 - Q1
upper_bound <- Q3 + 1.5 * IQR_value

df <- df[
  !is.na(df$LOS_days) &
    df$LOS_days >= 1 &
    df$LOS_days <= upper_bound,
]
df$LOS_binary <- factor(
  ifelse(
    df$LOS_days <= 7,
    "<=7_days",
    ">7_days"
  ),
  levels = c("<=7_days", ">7_days")
)

table(df$LOS_binary, useNA = "ifany")
## 
## <=7_days  >7_days 
##     1383     1870
# ============================================================
# LOS DESCRIPTIVE TABLE
# Gender + Admission source + Diagnosis
# ============================================================

library(dplyr)
library(tidyr)
library(gt)


# ============================================================
# 1. Restore / convert Gender safely
# ============================================================

df$Gender <- case_when(
  as.character(df$Gender) == "0" ~ "Female",
  as.character(df$Gender) == "1" ~ "Male",
  as.character(df$Gender) == "Female" ~ "Female",
  as.character(df$Gender) == "Male" ~ "Male",
  TRUE ~ NA_character_
)


# ============================================================
# 2. Restore / convert Admission source safely
# ============================================================

df$Admission_source <- case_when(
  as.character(df$Admission_source) == "1" ~ "Emergency",
  as.character(df$Admission_source) == "2" ~ "Medical Ward",
  as.character(df$Admission_source) == "3" ~ "Surgical Ward",
  as.character(df$Admission_source) == "4" ~ "Pediatrics Ward",
  as.character(df$Admission_source) == "5" ~ "Maternity Ward",
  as.character(df$Admission_source) == "6" ~ "Orthopedic Ward",
  as.character(df$Admission_source) == "7" ~ "HDU",
  as.character(df$Admission_source) == "8" ~ "Other",
  as.character(df$Admission_source) == "Emergency" ~ "Emergency",
  as.character(df$Admission_source) == "Medical Ward" ~ "Medical Ward",
  as.character(df$Admission_source) == "Surgical Ward" ~ "Surgical Ward",
  as.character(df$Admission_source) == "Pediatrics Ward" ~ "Pediatrics Ward",
  as.character(df$Admission_source) == "Maternity Ward" ~ "Maternity Ward",
  as.character(df$Admission_source) == "Orthopedic Ward" ~ "Orthopedic Ward",
  as.character(df$Admission_source) == "HDU" ~ "HDU",
  as.character(df$Admission_source) == "Other" ~ "Other",
  as.character(df$Admission_source) == "Other Specialty Wards" ~ "Other",
  TRUE ~ NA_character_
)


# ============================================================
# 3. Restore / convert Diagnosis safely
# ============================================================

df$diag_superclass <- case_when(
  as.character(df$diag_superclass) == "1" ~ "Cardiovascular Disease",
  as.character(df$diag_superclass) == "2" ~ "Respiratory Disease",
  as.character(df$diag_superclass) == "3" ~ "Neurological Disease",
  as.character(df$diag_superclass) == "4" ~ "Sepsis / Infection",
  as.character(df$diag_superclass) == "5" ~ "Gastrointestinal / Hepatic Disease",
  as.character(df$diag_superclass) == "6" ~ "Trauma / Toxicology",
  as.character(df$diag_superclass) == "7" ~ "Endocrine / Metabolic Disease",
  as.character(df$diag_superclass) == "8" ~ "Renal Disease",
  as.character(df$diag_superclass) == "9" ~ "Thromboembolism",
  as.character(df$diag_superclass) == "10" ~ "Malignancy",
  as.character(df$diag_superclass) == "11" ~ "Multi-organ Failure",
  as.character(df$diag_superclass) == "12" ~ "Obstetric / Gynecology",
  as.character(df$diag_superclass) == "13" ~ "Autoimmune / Systemic Disease",
  as.character(df$diag_superclass) == "14" ~ "Other",
  
  as.character(df$diag_superclass) == "Cardiovascular Disease" ~ "Cardiovascular Disease",
  as.character(df$diag_superclass) == "Respiratory Disease" ~ "Respiratory Disease",
  as.character(df$diag_superclass) == "Neurological Disease" ~ "Neurological Disease",
  as.character(df$diag_superclass) == "Sepsis / Infection" ~ "Sepsis / Infection",
  as.character(df$diag_superclass) == "Gastrointestinal / Hepatic Disease" ~ "Gastrointestinal / Hepatic Disease",
  as.character(df$diag_superclass) == "Trauma / Toxicology" ~ "Trauma / Toxicology",
  as.character(df$diag_superclass) == "Endocrine / Metabolic Disease" ~ "Endocrine / Metabolic Disease",
  as.character(df$diag_superclass) == "Renal Disease" ~ "Renal Disease",
  as.character(df$diag_superclass) == "Thromboembolism" ~ "Thromboembolism",
  as.character(df$diag_superclass) == "Malignancy" ~ "Malignancy",
  as.character(df$diag_superclass) == "Multi-organ Failure" ~ "Multi-organ Failure",
  as.character(df$diag_superclass) == "Obstetric / Gynecology" ~ "Obstetric / Gynecology",
  as.character(df$diag_superclass) == "Autoimmune / Systemic Disease" ~ "Autoimmune / Systemic Disease",
  as.character(df$diag_superclass) == "Other" ~ "Other",
  
  TRUE ~ NA_character_
)


# ============================================================
# 4. Make sure LOS_binary exists correctly
# ============================================================

df$LOS_binary <- factor(
  ifelse(
    is.na(df$LOS_days),
    NA_character_,
    ifelse(
      df$LOS_days <= 7,
      "<=7_days",
      ">7_days"
    )
  ),
  levels = c("<=7_days", ">7_days")
)


# ============================================================
# 5. Create clean analysis datasets
# ============================================================

gender_data <- df %>%
  filter(
    !is.na(Gender),
    !is.na(LOS_binary)
  )

admission_data <- df %>%
  filter(
    !is.na(Admission_source),
    !is.na(LOS_binary)
  )

diagnosis_data <- df %>%
  filter(
    !is.na(diag_superclass),
    !is.na(LOS_binary)
  )


# ============================================================
# 6. Safe p-value function
# ============================================================

get_pvalue <- function(x, y) {
  
  keep <- !is.na(x) & !is.na(y)
  
  x <- x[keep]
  y <- y[keep]
  
  tab <- table(x, y)
  
  if (nrow(tab) < 2 || ncol(tab) < 2) {
    return(NA_real_)
  }
  
  chi <- suppressWarnings(
    chisq.test(tab)
  )
  
  if (any(chi$expected < 5)) {
    suppressWarnings(
      chisq.test(
        tab,
        simulate.p.value = TRUE,
        B = 10000
      )$p.value
    )
  } else {
    chi$p.value
  }
}


# ============================================================
# 7. P-values
# ============================================================

gender_p <- get_pvalue(
  gender_data$Gender,
  gender_data$LOS_binary
)

admission_p <- get_pvalue(
  admission_data$Admission_source,
  admission_data$LOS_binary
)

diagnosis_p <- get_pvalue(
  diagnosis_data$diag_superclass,
  diagnosis_data$LOS_binary
)


# ============================================================
# 8. Total LOS groups
# ============================================================

short_total <- sum(
  df$LOS_binary == "<=7_days",
  na.rm = TRUE
)

long_total <- sum(
  df$LOS_binary == ">7_days",
  na.rm = TRUE
)


# ============================================================
# 9. Function to create each variable table
# ============================================================

make_los_table <- function(data, variable, variable_label, p_value) {
  
  data %>%
    count(
      .data[[variable]],
      LOS_binary
    ) %>%
    
    pivot_wider(
      names_from = LOS_binary,
      values_from = n,
      values_fill = 0
    ) %>%
    
    rename(
      Category = all_of(variable)
    ) %>%
    
    mutate(
      Variable = variable_label,
      Total = `<=7_days` + `>7_days`,
      
      `<=7_pct` = ifelse(
        short_total > 0,
        `<=7_days` / short_total * 100,
        0
      ),
      
      `>7_pct` = ifelse(
        long_total > 0,
        `>7_days` / long_total * 100,
        0
      ),
      
      p_value = p_value
    )
}


# ============================================================
# 10. Create the three tables
# ============================================================

gender_result <- make_los_table(
  gender_data,
  "Gender",
  "Gender",
  gender_p
)

admission_result <- make_los_table(
  admission_data,
  "Admission_source",
  "Admission source",
  admission_p
)

diagnosis_result <- make_los_table(
  diagnosis_data,
  "diag_superclass",
  "Diagnosis",
  diagnosis_p
)


# ============================================================
# 11. Combine
# ============================================================

result_los <- bind_rows(
  gender_result,
  admission_result,
  diagnosis_result
)


# ============================================================
# 12. Format p-values
# ============================================================

result_los <- result_los %>%
  mutate(
    `p-value` = case_when(
      is.na(p_value) ~ "",
      p_value < 0.001 ~ "<0.001",
      TRUE ~ sprintf("%.3f", p_value)
    )
  )


# ============================================================
# 13. Show variable and p-value once
# ============================================================

result_los <- result_los %>%
  group_by(Variable) %>%
  mutate(
    Variable_display = if_else(
      row_number() == 1,
      Variable,
      ""
    ),
    
    p_value_display = if_else(
      row_number() == 1,
      `p-value`,
      ""
    )
  ) %>%
  ungroup()


# ============================================================
# 14. Final data for gt
# ============================================================

result_los <- result_los %>%
  select(
    Variable_display,
    Category,
    Total,
    `<=7_days`,
    `<=7_pct`,
    `>7_days`,
    `>7_pct`,
    p_value_display
  )


# ============================================================
# 15. Publication table
# ============================================================

publication_table_los <- result_los %>%
  
  gt() %>%
  
  cols_label(
    Variable_display = "Variable",
    Category = "Category",
    Total = "Total",
    `<=7_days` = "n",
    `<=7_pct` = "%",
    `>7_days` = "n",
    `>7_pct` = "%",
    p_value_display = "p-value"
  ) %>%
  
  tab_spanner(
    label = "≤7 days",
    columns = c(
      `<=7_days`,
      `<=7_pct`
    )
  ) %>%
  
  tab_spanner(
    label = ">7 days",
    columns = c(
      `>7_days`,
      `>7_pct`
    )
  ) %>%
  
  tab_style(
    style = cell_text(weight = "bold"),
    locations = cells_body(
      columns = Variable_display,
      rows = Variable_display != ""
    )
  ) %>%
  
  tab_style(
    style = cell_text(indent = px(15)),
    locations = cells_body(
      columns = Category
    )
  ) %>%
  
  tab_style(
    style = cell_borders(
      sides = "top",
      color = "black",
      weight = px(1)
    ),
    locations = cells_body(
      rows = Variable_display != ""
    )
  ) %>%
  
  cols_align(
    align = "left",
    columns = c(
      Variable_display,
      Category
    )
  ) %>%
  
  cols_align(
    align = "center",
    columns = c(
      Total,
      `<=7_days`,
      `<=7_pct`,
      `>7_days`,
      `>7_pct`,
      p_value_display
    )
  ) %>%
  
  fmt_number(
    columns = c(
      `<=7_pct`,
      `>7_pct`
    ),
    decimals = 1
  ) %>%
  
  tab_options(
    table.border.top.color = "black",
    table.border.bottom.color = "black",
    table.border.top.width = px(1),
    table.border.bottom.width = px(1),
    column_labels.border.top.width = px(1),
    column_labels.border.bottom.width = px(1),
    table.font.size = px(12),
    data_row.padding = px(5)
  )


publication_table_los
Variable Category Total
≤7 days
>7 days
p-value
n % n %
Gender Female 1386 581 42.0 805 43.0 0.578
Male 1867 802 42.0 1065 43.0
Admission source Emergency 2051 845 61.1 1206 64.5 0.275
HDU 12 5 61.1 7 64.5
Maternity Ward 59 32 61.1 27 64.5
Medical Ward 469 212 61.1 257 64.5
Orthopedic Ward 20 7 61.1 13 64.5
Other 74 28 61.1 46 64.5
Pediatrics Ward 6 2 61.1 4 64.5
Surgical Ward 562 252 61.1 310 64.5
Diagnosis Autoimmune / Systemic Disease 10 7 0.5 3 0.2 <0.001
Cardiovascular Disease 841 404 0.5 437 0.2
Endocrine / Metabolic Disease 140 56 0.5 84 0.2
Gastrointestinal / Hepatic Disease 237 113 0.5 124 0.2
Malignancy 76 30 0.5 46 0.2
Multi-organ Failure 33 17 0.5 16 0.2
Neurological Disease 549 211 0.5 338 0.2
Obstetric / Gynecology 34 18 0.5 16 0.2
Other 134 54 0.5 80 0.2
Renal Disease 101 43 0.5 58 0.2
Respiratory Disease 495 216 0.5 279 0.2
Sepsis / Infection 366 137 0.5 229 0.2
Thromboembolism 68 17 0.5 51 0.2
Trauma / Toxicology 169 60 0.5 109 0.2
# ============================================================
# PUBLICATION TABLE
# MORTALITY + LENGTH OF STAY
# INCLUDING AGE GROUP
# ============================================================

library(dplyr)
library(tidyr)
library(gt)


# ============================================================
# 1. CREATE DISPLAY VERSIONS
# ============================================================


# ------------------------------------------------------------
# MORTALITY DATA — df_final
# ------------------------------------------------------------

df_final_display <- df_final %>%
  mutate(

    # --------------------------------------------------------
    # GENDER
    # --------------------------------------------------------
    Gender_display = case_when(
      as.character(Gender) == "0" ~ "Female",
      as.character(Gender) == "1" ~ "Male",
      as.character(Gender) == "Female" ~ "Female",
      as.character(Gender) == "Male" ~ "Male",
      TRUE ~ NA_character_
    ),

    # --------------------------------------------------------
    # AGE GROUP
    # --------------------------------------------------------
    Age_group = case_when(
      !is.na(Age_years) & Age_years <= 24 ~ "<=24",
      !is.na(Age_years) & Age_years >= 25 & Age_years <= 29 ~ "25-29",
      !is.na(Age_years) & Age_years >= 30 & Age_years <= 40 ~ "30-40",
      !is.na(Age_years) & Age_years >= 41 & Age_years <= 50 ~ "41-50",
      !is.na(Age_years) & Age_years > 50 ~ ">51",
      TRUE ~ NA_character_
    ),

    # --------------------------------------------------------
    # ADMISSION SOURCE
    # --------------------------------------------------------
    Admission_display = case_when(

      as.character(Admission_source) == "1" ~ "Emergency",
      as.character(Admission_source) == "2" ~ "Medical Ward",
      as.character(Admission_source) == "3" ~ "Surgical Ward",
      as.character(Admission_source) == "4" ~ "Pediatrics Ward",
      as.character(Admission_source) == "5" ~ "Maternity Ward",
      as.character(Admission_source) == "6" ~ "Orthopedic Ward",
      as.character(Admission_source) == "7" ~ "HDU",
      as.character(Admission_source) == "8" ~ "Other",

      as.character(Admission_source) == "Emergency" ~ "Emergency",
      as.character(Admission_source) == "Medical Ward" ~ "Medical Ward",
      as.character(Admission_source) == "Surgical Ward" ~ "Surgical Ward",
      as.character(Admission_source) == "Pediatrics Ward" ~ "Pediatrics Ward",
      as.character(Admission_source) == "Maternity Ward" ~ "Maternity Ward",
      as.character(Admission_source) == "Orthopedic Ward" ~ "Orthopedic Ward",
      as.character(Admission_source) == "HDU" ~ "HDU",
      as.character(Admission_source) == "Other" ~ "Other",
      as.character(Admission_source) == "Other Specialty Wards" ~ "Other",

      TRUE ~ NA_character_
    ),

    # --------------------------------------------------------
    # DIAGNOSIS
    # --------------------------------------------------------
    Diagnosis_display = case_when(

      as.character(diag_superclass) == "1" ~
        "Cardiovascular Disease",

      as.character(diag_superclass) == "2" ~
        "Respiratory Disease",

      as.character(diag_superclass) == "3" ~
        "Neurological Disease",

      as.character(diag_superclass) == "4" ~
        "Sepsis / Infection",

      as.character(diag_superclass) == "5" ~
        "Gastrointestinal / Hepatic Disease",

      as.character(diag_superclass) == "6" ~
        "Trauma / Toxicology",

      as.character(diag_superclass) == "7" ~
        "Endocrine / Metabolic Disease",

      as.character(diag_superclass) == "8" ~
        "Renal Disease",

      as.character(diag_superclass) == "9" ~
        "Thromboembolism",

      as.character(diag_superclass) == "10" ~
        "Malignancy",

      as.character(diag_superclass) == "11" ~
        "Multi-organ Failure",

      as.character(diag_superclass) == "12" ~
        "Obstetric / Gynecology",

      as.character(diag_superclass) == "13" ~
        "Autoimmune / Systemic Disease",

      as.character(diag_superclass) == "14" ~
        "Other",

      as.character(diag_superclass) == "Cardiovascular Disease" ~
        "Cardiovascular Disease",

      as.character(diag_superclass) == "Respiratory Disease" ~
        "Respiratory Disease",

      as.character(diag_superclass) == "Neurological Disease" ~
        "Neurological Disease",

      as.character(diag_superclass) == "Sepsis / Infection" ~
        "Sepsis / Infection",

      as.character(diag_superclass) ==
        "Gastrointestinal / Hepatic Disease" ~
        "Gastrointestinal / Hepatic Disease",

      as.character(diag_superclass) == "Trauma / Toxicology" ~
        "Trauma / Toxicology",

      as.character(diag_superclass) ==
        "Endocrine / Metabolic Disease" ~
        "Endocrine / Metabolic Disease",

      as.character(diag_superclass) == "Renal Disease" ~
        "Renal Disease",

      as.character(diag_superclass) == "Thromboembolism" ~
        "Thromboembolism",

      as.character(diag_superclass) == "Malignancy" ~
        "Malignancy",

      as.character(diag_superclass) == "Multi-organ Failure" ~
        "Multi-organ Failure",

      as.character(diag_superclass) ==
        "Obstetric / Gynecology" ~
        "Obstetric / Gynecology",

      as.character(diag_superclass) ==
        "Autoimmune / Systemic Disease" ~
        "Autoimmune / Systemic Disease",

      as.character(diag_superclass) == "Other" ~ "Other",

      TRUE ~ NA_character_
    )
  )


# ------------------------------------------------------------
# LOS DATA — df
# ------------------------------------------------------------

df_display <- df %>%
  mutate(

    # --------------------------------------------------------
    # GENDER
    # --------------------------------------------------------
    Gender_display = case_when(
      as.character(Gender) == "0" ~ "Female",
      as.character(Gender) == "1" ~ "Male",
      as.character(Gender) == "Female" ~ "Female",
      as.character(Gender) == "Male" ~ "Male",
      TRUE ~ NA_character_
    ),

    # --------------------------------------------------------
    # AGE GROUP
    # --------------------------------------------------------
    Age_group = case_when(
      !is.na(Age_years) & Age_years <= 24 ~ "<=24",
      !is.na(Age_years) & Age_years >= 25 & Age_years <= 29 ~ "25-29",
      !is.na(Age_years) & Age_years >= 30 & Age_years <= 40 ~ "30-40",
      !is.na(Age_years) & Age_years >= 41 & Age_years <= 50 ~ "41-50",
      !is.na(Age_years) & Age_years > 50 ~ ">51",
      TRUE ~ NA_character_
    ),

    # --------------------------------------------------------
    # ADMISSION SOURCE
    # --------------------------------------------------------
    Admission_display = case_when(

      as.character(Admission_source) == "1" ~ "Emergency",
      as.character(Admission_source) == "2" ~ "Medical Ward",
      as.character(Admission_source) == "3" ~ "Surgical Ward",
      as.character(Admission_source) == "4" ~ "Pediatrics Ward",
      as.character(Admission_source) == "5" ~ "Maternity Ward",
      as.character(Admission_source) == "6" ~ "Orthopedic Ward",
      as.character(Admission_source) == "7" ~ "HDU",
      as.character(Admission_source) == "8" ~ "Other",

      as.character(Admission_source) == "Emergency" ~ "Emergency",
      as.character(Admission_source) == "Medical Ward" ~ "Medical Ward",
      as.character(Admission_source) == "Surgical Ward" ~ "Surgical Ward",
      as.character(Admission_source) == "Pediatrics Ward" ~ "Pediatrics Ward",
      as.character(Admission_source) == "Maternity Ward" ~ "Maternity Ward",
      as.character(Admission_source) == "Orthopedic Ward" ~ "Orthopedic Ward",
      as.character(Admission_source) == "HDU" ~ "HDU",
      as.character(Admission_source) == "Other" ~ "Other",
      as.character(Admission_source) == "Other Specialty Wards" ~ "Other",

      TRUE ~ NA_character_
    ),

    # --------------------------------------------------------
    # DIAGNOSIS
    # --------------------------------------------------------
    Diagnosis_display = case_when(

      as.character(diag_superclass) == "1" ~
        "Cardiovascular Disease",

      as.character(diag_superclass) == "2" ~
        "Respiratory Disease",

      as.character(diag_superclass) == "3" ~
        "Neurological Disease",

      as.character(diag_superclass) == "4" ~
        "Sepsis / Infection",

      as.character(diag_superclass) == "5" ~
        "Gastrointestinal / Hepatic Disease",

      as.character(diag_superclass) == "6" ~
        "Trauma / Toxicology",

      as.character(diag_superclass) == "7" ~
        "Endocrine / Metabolic Disease",

      as.character(diag_superclass) == "8" ~
        "Renal Disease",

      as.character(diag_superclass) == "9" ~
        "Thromboembolism",

      as.character(diag_superclass) == "10" ~
        "Malignancy",

      as.character(diag_superclass) == "11" ~
        "Multi-organ Failure",

      as.character(diag_superclass) == "12" ~
        "Obstetric / Gynecology",

      as.character(diag_superclass) == "13" ~
        "Autoimmune / Systemic Disease",

      as.character(diag_superclass) == "14" ~
        "Other",

      as.character(diag_superclass) == "Cardiovascular Disease" ~
        "Cardiovascular Disease",

      as.character(diag_superclass) == "Respiratory Disease" ~
        "Respiratory Disease",

      as.character(diag_superclass) == "Neurological Disease" ~
        "Neurological Disease",

      as.character(diag_superclass) == "Sepsis / Infection" ~
        "Sepsis / Infection",

      as.character(diag_superclass) ==
        "Gastrointestinal / Hepatic Disease" ~
        "Gastrointestinal / Hepatic Disease",

      as.character(diag_superclass) == "Trauma / Toxicology" ~
        "Trauma / Toxicology",

      as.character(diag_superclass) ==
        "Endocrine / Metabolic Disease" ~
        "Endocrine / Metabolic Disease",

      as.character(diag_superclass) == "Renal Disease" ~
        "Renal Disease",

      as.character(diag_superclass) == "Thromboembolism" ~
        "Thromboembolism",

      as.character(diag_superclass) == "Malignancy" ~
        "Malignancy",

      as.character(diag_superclass) == "Multi-organ Failure" ~
        "Multi-organ Failure",

      as.character(diag_superclass) ==
        "Obstetric / Gynecology" ~
        "Obstetric / Gynecology",

      as.character(diag_superclass) ==
        "Autoimmune / Systemic Disease" ~
        "Autoimmune / Systemic Disease",

      as.character(diag_superclass) == "Other" ~ "Other",

      TRUE ~ NA_character_
    )
  )


# ============================================================
# 2. OUTCOME ORDER
# ============================================================

df_final_display$stat <- factor(
  df_final_display$stat,
  levels = c("Survived", "Died")
)

df_display$LOS_binary <- factor(
  df_display$LOS_binary,
  levels = c("<=7_days", ">7_days")
)


# ============================================================
# 3. SAFE P-VALUE FUNCTION
# ============================================================

get_pvalue <- function(x, y) {

  keep <- !is.na(x) & !is.na(y)

  x <- x[keep]
  y <- y[keep]

  tab <- table(x, y)

  # No observations or only one level
  if (sum(tab) == 0 ||
      nrow(tab) < 2 ||
      ncol(tab) < 2) {
    return(NA_real_)
  }

  chi <- suppressWarnings(
    chisq.test(tab)
  )

  if (any(chi$expected < 5)) {

    return(
      suppressWarnings(
        chisq.test(
          tab,
          simulate.p.value = TRUE,
          B = 10000
        )$p.value
      )
    )

  } else {

    return(chi$p.value)
  }
}


# ============================================================
# 4. P-VALUES — MORTALITY
# ============================================================

mortality_p_gender <- get_pvalue(
  df_final_display$Gender_display,
  df_final_display$stat
)

mortality_p_age <- get_pvalue(
  df_final_display$Age_group,
  df_final_display$stat
)

mortality_p_admission <- get_pvalue(
  df_final_display$Admission_display,
  df_final_display$stat
)

mortality_p_diagnosis <- get_pvalue(
  df_final_display$Diagnosis_display,
  df_final_display$stat
)


# ============================================================
# 5. P-VALUES — LOS
# ============================================================

los_p_gender <- get_pvalue(
  df_display$Gender_display,
  df_display$LOS_binary
)

los_p_age <- get_pvalue(
  df_display$Age_group,
  df_display$LOS_binary
)

los_p_admission <- get_pvalue(
  df_display$Admission_display,
  df_display$LOS_binary
)

los_p_diagnosis <- get_pvalue(
  df_display$Diagnosis_display,
  df_display$LOS_binary
)


# ============================================================
# 6. FORMAT P-VALUE
# ============================================================

format_p <- function(p) {

  if (is.na(p)) {
    return("")
  }

  if (p < 0.001) {
    return("<0.001")
  }

  sprintf("%.3f", p)
}


# ============================================================
# 7. FUNCTION TO ENSURE MORTALITY COLUMNS EXIST
# ============================================================

complete_mortality_columns <- function(data) {

  if (!"Survived" %in% names(data)) {
    data$Survived <- 0L
  }

  if (!"Died" %in% names(data)) {
    data$Died <- 0L
  }

  data
}


# ============================================================
# 8. FUNCTION TO ENSURE LOS COLUMNS EXIST
# ============================================================

complete_los_columns <- function(data) {

  if (!"<=7_days" %in% names(data)) {
    data[["<=7_days"]] <- 0L
  }

  if (!">7_days" %in% names(data)) {
    data[[">7_days"]] <- 0L
  }

  data
}


# ============================================================
# 9. MORTALITY — GENDER
# ============================================================

mortality_gender <- df_final_display %>%
  filter(
    !is.na(Gender_display),
    !is.na(stat)
  ) %>%
  count(
    Category = Gender_display,
    stat
  ) %>%
  pivot_wider(
    names_from = stat,
    values_from = n,
    values_fill = 0
  ) %>%
  complete_mortality_columns() %>%
  mutate(
    Variable = "Gender",
    Category = as.character(Category)
  )


# ============================================================
# 10. MORTALITY — AGE GROUP
# ============================================================

mortality_age <- df_final_display %>%
  filter(
    !is.na(Age_group),
    !is.na(stat)
  ) %>%
  count(
    Category = Age_group,
    stat
  ) %>%
  pivot_wider(
    names_from = stat,
    values_from = n,
    values_fill = 0
  ) %>%
  complete_mortality_columns() %>%
  mutate(
    Variable = "Age group",
    Category = as.character(Category)
  )


# ============================================================
# 11. MORTALITY — ADMISSION SOURCE
# ============================================================

mortality_admission <- df_final_display %>%
  filter(
    !is.na(Admission_display),
    !is.na(stat)
  ) %>%
  count(
    Category = Admission_display,
    stat
  ) %>%
  pivot_wider(
    names_from = stat,
    values_from = n,
    values_fill = 0
  ) %>%
  complete_mortality_columns() %>%
  mutate(
    Variable = "Admission source",
    Category = as.character(Category)
  )


# ============================================================
# 12. MORTALITY — DIAGNOSIS
# ============================================================

mortality_diagnosis <- df_final_display %>%
  filter(
    !is.na(Diagnosis_display),
    !is.na(stat)
  ) %>%
  count(
    Category = Diagnosis_display,
    stat
  ) %>%
  pivot_wider(
    names_from = stat,
    values_from = n,
    values_fill = 0
  ) %>%
  complete_mortality_columns() %>%
  mutate(
    Variable = "Diagnosis",
    Category = as.character(Category)
  )


# ============================================================
# 13. MORTALITY COUNTS + WITHIN-CATEGORY PERCENTAGES
# ============================================================

mortality_result <- bind_rows(
  mortality_gender,
  mortality_age,
  mortality_admission,
  mortality_diagnosis
) %>%
  mutate(
    Category = as.character(Category),

    Survived = coalesce(Survived, 0L),
    Died = coalesce(Died, 0L),

    Mortality_Total = Survived + Died,

    Survived_pct = if_else(
      Mortality_Total > 0,
      Survived / Mortality_Total * 100,
      NA_real_
    ),

    Died_pct = if_else(
      Mortality_Total > 0,
      Died / Mortality_Total * 100,
      NA_real_
    )
  ) %>%
  select(
    Variable,
    Category,
    Mortality_Total,
    Survived,
    Survived_pct,
    Died,
    Died_pct
  )


# ============================================================
# 14. LOS — GENDER
# ============================================================

los_gender <- df_display %>%
  filter(
    !is.na(Gender_display),
    !is.na(LOS_binary)
  ) %>%
  count(
    Category = Gender_display,
    LOS_binary
  ) %>%
  pivot_wider(
    names_from = LOS_binary,
    values_from = n,
    values_fill = 0
  ) %>%
  complete_los_columns() %>%
  mutate(
    Variable = "Gender",
    Category = as.character(Category)
  )


# ============================================================
# 15. LOS — AGE GROUP
# ============================================================

los_age <- df_display %>%
  filter(
    !is.na(Age_group),
    !is.na(LOS_binary)
  ) %>%
  count(
    Category = Age_group,
    LOS_binary
  ) %>%
  pivot_wider(
    names_from = LOS_binary,
    values_from = n,
    values_fill = 0
  ) %>%
  complete_los_columns() %>%
  mutate(
    Variable = "Age group",
    Category = as.character(Category)
  )


# ============================================================
# 16. LOS — ADMISSION SOURCE
# ============================================================

los_admission <- df_display %>%
  filter(
    !is.na(Admission_display),
    !is.na(LOS_binary)
  ) %>%
  count(
    Category = Admission_display,
    LOS_binary
  ) %>%
  pivot_wider(
    names_from = LOS_binary,
    values_from = n,
    values_fill = 0
  ) %>%
  complete_los_columns() %>%
  mutate(
    Variable = "Admission source",
    Category = as.character(Category)
  )


# ============================================================
# 17. LOS — DIAGNOSIS
# ============================================================

los_diagnosis <- df_display %>%
  filter(
    !is.na(Diagnosis_display),
    !is.na(LOS_binary)
  ) %>%
  count(
    Category = Diagnosis_display,
    LOS_binary
  ) %>%
  pivot_wider(
    names_from = LOS_binary,
    values_from = n,
    values_fill = 0
  ) %>%
  complete_los_columns() %>%
  mutate(
    Variable = "Diagnosis",
    Category = as.character(Category)
  )


# ============================================================
# 18. LOS COUNTS + WITHIN-CATEGORY PERCENTAGES
# ============================================================

los_result <- bind_rows(
  los_gender,
  los_age,
  los_admission,
  los_diagnosis
) %>%
  mutate(
    Category = as.character(Category),

    `<=7_days` = coalesce(`<=7_days`, 0L),
    `>7_days` = coalesce(`>7_days`, 0L),

    LOS_Total = `<=7_days` + `>7_days`,

    `<=7_pct` = if_else(
      LOS_Total > 0,
      `<=7_days` / LOS_Total * 100,
      NA_real_
    ),

    `>7_pct` = if_else(
      LOS_Total > 0,
      `>7_days` / LOS_Total * 100,
      NA_real_
    )
  ) %>%
  select(
    Variable,
    Category,
    LOS_Total,
    `<=7_days`,
    `<=7_pct`,
    `>7_days`,
    `>7_pct`
  )


# ============================================================
# 19. MERGE MORTALITY + LOS
# ============================================================

result_combined <- full_join(
  mortality_result,
  los_result,
  by = c("Variable", "Category")
)


# ============================================================
# 20. ADD P-VALUES
# ============================================================

result_combined <- result_combined %>%
  mutate(

    `Mortality p-value` = case_when(
      Variable == "Gender" ~ format_p(mortality_p_gender),
      Variable == "Age group" ~ format_p(mortality_p_age),
      Variable == "Admission source" ~ format_p(mortality_p_admission),
      Variable == "Diagnosis" ~ format_p(mortality_p_diagnosis),
      TRUE ~ ""
    ),

    `LOS p-value` = case_when(
      Variable == "Gender" ~ format_p(los_p_gender),
      Variable == "Age group" ~ format_p(los_p_age),
      Variable == "Admission source" ~ format_p(los_p_admission),
      Variable == "Diagnosis" ~ format_p(los_p_diagnosis),
      TRUE ~ ""
    )
  )


# ============================================================
# 21. FORCE VARIABLE ORDER
# ============================================================

result_combined$Variable <- factor(
  result_combined$Variable,
  levels = c(
    "Gender",
    "Age group",
    "Admission source",
    "Diagnosis"
  )
)

result_combined <- result_combined %>%
  arrange(Variable)


# ============================================================
# 22. SHOW VARIABLE + P-VALUE ONLY ONCE
# ============================================================

result_combined <- result_combined %>%
  group_by(Variable) %>%
  mutate(

    Variable_display = if_else(
      row_number() == 1,
      as.character(Variable),
      ""
    ),

    Mortality_p_display = if_else(
      row_number() == 1,
      `Mortality p-value`,
      ""
    ),

    LOS_p_display = if_else(
      row_number() == 1,
      `LOS p-value`,
      ""
    )
  ) %>%
  ungroup()


# ============================================================
# 23. FINAL TABLE DATA
# ============================================================

result_combined <- result_combined %>%
  select(

    Variable_display,
    Category,

    Mortality_Total,
    Survived,
    Survived_pct,
    Died,
    Died_pct,
    Mortality_p_display,

    LOS_Total,
    `<=7_days`,
    `<=7_pct`,
    `>7_days`,
    `>7_pct`,
    LOS_p_display
  )


# ============================================================
# 24. PUBLICATION TABLE
# ============================================================

publishable_table_los <- result_combined %>%

  gt() %>%

  # ----------------------------------------------------------
  # COLUMN LABELS
  # ----------------------------------------------------------

  cols_label(

    Variable_display = "Variable",
    Category = "Category",

    # TOTAL COLUMN — BLANK IN FINAL DISPLAY
    Mortality_Total = "",

    # SURVIVED
    Survived = "",
    Survived_pct = "%",

    # DIED
    Died = "",
    Died_pct = "%",

    Mortality_p_display = "p-value",

    # TOTAL COLUMN — BLANK IN FINAL DISPLAY
    LOS_Total = "",

    # ≤7 DAYS
    `<=7_days` = "",
    `<=7_pct` = "%",

    # >7 DAYS
    `>7_days` = "",
    `>7_pct` = "%",

    LOS_p_display = "p-value"
  ) %>%


  # ----------------------------------------------------------
  # SURVIVED
  # ----------------------------------------------------------

  tab_spanner(
    label = "Survived",
    columns = c(
      Survived,
      Survived_pct
    ),
    id = "survived"
  ) %>%


  # ----------------------------------------------------------
  # DIED
  # ----------------------------------------------------------

  tab_spanner(
    label = "Died",
    columns = c(
      Died,
      Died_pct
    ),
    id = "died"
  ) %>%


  # ----------------------------------------------------------
  # ≤7 DAYS
  # ----------------------------------------------------------

  tab_spanner(
    label = "≤7 days",
    columns = c(
      `<=7_days`,
      `<=7_pct`
    ),
    id = "short_los"
  ) %>%


  # ----------------------------------------------------------
  # >7 DAYS
  # ----------------------------------------------------------

  tab_spanner(
    label = ">7 days",
    columns = c(
      `>7_days`,
      `>7_pct`
    ),
    id = "long_los"
  ) %>%


  # ----------------------------------------------------------
  # BOLD VARIABLE
  # ----------------------------------------------------------

  tab_style(
    style = cell_text(
      weight = "bold"
    ),
    locations = cells_body(
      columns = Variable_display,
      rows = Variable_display != ""
    )
  ) %>%


  # ----------------------------------------------------------
  # INDENT CATEGORY
  # ----------------------------------------------------------

  tab_style(
    style = cell_text(
      indent = px(15)
    ),
    locations = cells_body(
      columns = Category
    )
  ) %>%


  # ----------------------------------------------------------
  # LINE BEFORE EACH VARIABLE
  # ----------------------------------------------------------

  tab_style(
    style = cell_borders(
      sides = "top",
      color = "black",
      weight = px(1)
    ),
    locations = cells_body(
      rows = Variable_display != ""
    )
  ) %>%


  # ----------------------------------------------------------
  # LEFT ALIGNMENT
  # ----------------------------------------------------------

  cols_align(
    align = "left",
    columns = c(
      Variable_display,
      Category
    )
  ) %>%


  # ----------------------------------------------------------
  # CENTER NUMERICAL COLUMNS
  # ----------------------------------------------------------

  cols_align(
    align = "center",
    columns = c(

      Mortality_Total,

      Survived,
      Survived_pct,

      Died,
      Died_pct,

      Mortality_p_display,

      LOS_Total,

      `<=7_days`,
      `<=7_pct`,

      `>7_days`,
      `>7_pct`,

      LOS_p_display
    )
  ) %>%


  # ----------------------------------------------------------
  # PERCENTAGES — ONE DECIMAL
  # ----------------------------------------------------------

  fmt_number(
    columns = c(
      Survived_pct,
      Died_pct,
      `<=7_pct`,
      `>7_pct`
    ),
    decimals = 1
  ) %>%


  # ----------------------------------------------------------
  # TABLE STYLE
  # ----------------------------------------------------------

  tab_options(

    table.border.top.color = "black",
    table.border.bottom.color = "black",

    table.border.top.width = px(1),
    table.border.bottom.width = px(1),

    column_labels.border.top.width = px(1),
    column_labels.border.bottom.width = px(1),

    table.font.size = px(12),
    data_row.padding = px(5)
  )


# ============================================================
# 25. DISPLAY FINAL TABLE
# ============================================================

publishable_table_los
Variable Category
Survived
Died
p-value
≤7 days
>7 days
p-value
% % % %
Gender Female NA NA NA NA NA 1386 581 41.9 805 58.1 0.578
Male NA NA NA NA NA 1867 802 43.0 1065 57.0
Age group 25-29 NA NA NA NA NA 184 103 56.0 81 44.0 <0.001
30-40 NA NA NA NA NA 370 175 47.3 195 52.7
41-50 NA NA NA NA NA 408 165 40.4 243 59.6
<=24 NA NA NA NA NA 188 96 51.1 92 48.9
>51 NA NA NA NA NA 2102 844 40.2 1258 59.8
Admission source Emergency NA NA NA NA NA 2051 845 41.2 1206 58.8 0.275
HDU NA NA NA NA NA 12 5 41.7 7 58.3
Maternity Ward NA NA NA NA NA 59 32 54.2 27 45.8
Medical Ward NA NA NA NA NA 469 212 45.2 257 54.8
Orthopedic Ward NA NA NA NA NA 20 7 35.0 13 65.0
Other NA NA NA NA NA 74 28 37.8 46 62.2
Pediatrics Ward NA NA NA NA NA 6 2 33.3 4 66.7
Surgical Ward NA NA NA NA NA 562 252 44.8 310 55.2
Diagnosis Autoimmune / Systemic Disease NA NA NA NA NA 10 7 70.0 3 30.0 <0.001
Cardiovascular Disease NA NA NA NA NA 841 404 48.0 437 52.0
Endocrine / Metabolic Disease NA NA NA NA NA 140 56 40.0 84 60.0
Gastrointestinal / Hepatic Disease NA NA NA NA NA 237 113 47.7 124 52.3
Malignancy NA NA NA NA NA 76 30 39.5 46 60.5
Multi-organ Failure NA NA NA NA NA 33 17 51.5 16 48.5
Neurological Disease NA NA NA NA NA 549 211 38.4 338 61.6
Obstetric / Gynecology NA NA NA NA NA 34 18 52.9 16 47.1
Other NA NA NA NA NA 134 54 40.3 80 59.7
Renal Disease NA NA NA NA NA 101 43 42.6 58 57.4
Respiratory Disease NA NA NA NA NA 495 216 43.6 279 56.4
Sepsis / Infection NA NA NA NA NA 366 137 37.4 229 62.6
Thromboembolism NA NA NA NA NA 68 17 25.0 51 75.0
Trauma / Toxicology NA NA NA NA NA 169 60 35.5 109 64.5
# ============================================================
# PUBLICATION TABLE
# MORTALITY + LENGTH OF STAY
# INCLUDING AGE GROUP
# ============================================================

library(dplyr)
library(tidyr)
library(gt)


# ============================================================
# 1. CREATE DISPLAY VERSIONS
# ============================================================


# ------------------------------------------------------------
# MORTALITY DATA — df_final
# ------------------------------------------------------------

df_final_display <- df_final %>%
  mutate(

    # --------------------------------------------------------
    # GENDER
    # --------------------------------------------------------
    Gender_display = case_when(
      as.character(Gender) == "0" ~ "Female",
      as.character(Gender) == "1" ~ "Male",
      as.character(Gender) == "Female" ~ "Female",
      as.character(Gender) == "Male" ~ "Male",
      TRUE ~ NA_character_
    ),

    # --------------------------------------------------------
    # AGE GROUP
    # --------------------------------------------------------
    Age_group = case_when(
      !is.na(Age_years) & Age_years <= 24 ~ "<=24",
      !is.na(Age_years) & Age_years >= 25 & Age_years <= 29 ~ "25-29",
      !is.na(Age_years) & Age_years >= 30 & Age_years <= 40 ~ "30-40",
      !is.na(Age_years) & Age_years >= 41 & Age_years <= 50 ~ "41-50",
      !is.na(Age_years) & Age_years > 50 ~ ">51",
      TRUE ~ NA_character_
    ),

    # --------------------------------------------------------
    # ADMISSION SOURCE
    # --------------------------------------------------------
    Admission_display = case_when(

      as.character(Admission_source) == "1" ~ "Emergency",
      as.character(Admission_source) == "2" ~ "Medical Ward",
      as.character(Admission_source) == "3" ~ "Surgical Ward",
      as.character(Admission_source) == "4" ~ "Pediatrics Ward",
      as.character(Admission_source) == "5" ~ "Maternity Ward",
      as.character(Admission_source) == "6" ~ "Orthopedic Ward",
      as.character(Admission_source) == "7" ~ "HDU",
      as.character(Admission_source) == "8" ~ "Other",

      as.character(Admission_source) == "Emergency" ~ "Emergency",
      as.character(Admission_source) == "Medical Ward" ~ "Medical Ward",
      as.character(Admission_source) == "Surgical Ward" ~ "Surgical Ward",
      as.character(Admission_source) == "Pediatrics Ward" ~ "Pediatrics Ward",
      as.character(Admission_source) == "Maternity Ward" ~ "Maternity Ward",
      as.character(Admission_source) == "Orthopedic Ward" ~ "Orthopedic Ward",
      as.character(Admission_source) == "HDU" ~ "HDU",
      as.character(Admission_source) == "Other" ~ "Other",
      as.character(Admission_source) == "Other Specialty Wards" ~ "Other",

      TRUE ~ NA_character_
    ),

    # --------------------------------------------------------
    # DIAGNOSIS
    # --------------------------------------------------------
    Diagnosis_display = case_when(

      as.character(diag_superclass) == "1" ~
        "Cardiovascular Disease",

      as.character(diag_superclass) == "2" ~
        "Respiratory Disease",

      as.character(diag_superclass) == "3" ~
        "Neurological Disease",

      as.character(diag_superclass) == "4" ~
        "Sepsis / Infection",

      as.character(diag_superclass) == "5" ~
        "Gastrointestinal / Hepatic Disease",

      as.character(diag_superclass) == "6" ~
        "Trauma / Toxicology",

      as.character(diag_superclass) == "7" ~
        "Endocrine / Metabolic Disease",

      as.character(diag_superclass) == "8" ~
        "Renal Disease",

      as.character(diag_superclass) == "9" ~
        "Thromboembolism",

      as.character(diag_superclass) == "10" ~
        "Malignancy",

      as.character(diag_superclass) == "11" ~
        "Multi-organ Failure",

      as.character(diag_superclass) == "12" ~
        "Obstetric / Gynecology",

      as.character(diag_superclass) == "13" ~
        "Autoimmune / Systemic Disease",

      as.character(diag_superclass) == "14" ~
        "Other",

      as.character(diag_superclass) == "Cardiovascular Disease" ~
        "Cardiovascular Disease",

      as.character(diag_superclass) == "Respiratory Disease" ~
        "Respiratory Disease",

      as.character(diag_superclass) == "Neurological Disease" ~
        "Neurological Disease",

      as.character(diag_superclass) == "Sepsis / Infection" ~
        "Sepsis / Infection",

      as.character(diag_superclass) ==
        "Gastrointestinal / Hepatic Disease" ~
        "Gastrointestinal / Hepatic Disease",

      as.character(diag_superclass) == "Trauma / Toxicology" ~
        "Trauma / Toxicology",

      as.character(diag_superclass) ==
        "Endocrine / Metabolic Disease" ~
        "Endocrine / Metabolic Disease",

      as.character(diag_superclass) == "Renal Disease" ~
        "Renal Disease",

      as.character(diag_superclass) == "Thromboembolism" ~
        "Thromboembolism",

      as.character(diag_superclass) == "Malignancy" ~
        "Malignancy",

      as.character(diag_superclass) == "Multi-organ Failure" ~
        "Multi-organ Failure",

      as.character(diag_superclass) ==
        "Obstetric / Gynecology" ~
        "Obstetric / Gynecology",

      as.character(diag_superclass) ==
        "Autoimmune / Systemic Disease" ~
        "Autoimmune / Systemic Disease",

      as.character(diag_superclass) == "Other" ~
        "Other",

      TRUE ~ NA_character_
    )
  )


# ------------------------------------------------------------
# LOS DATA — df
# ------------------------------------------------------------

df_display <- df %>%
  mutate(

    # --------------------------------------------------------
    # GENDER
    # --------------------------------------------------------
    Gender_display = case_when(
      as.character(Gender) == "0" ~ "Female",
      as.character(Gender) == "1" ~ "Male",
      as.character(Gender) == "Female" ~ "Female",
      as.character(Gender) == "Male" ~ "Male",
      TRUE ~ NA_character_
    ),

    # --------------------------------------------------------
    # AGE GROUP
    # --------------------------------------------------------
    Age_group = case_when(
      !is.na(Age_years) & Age_years <= 24 ~ "<=24",
      !is.na(Age_years) & Age_years >= 25 & Age_years <= 29 ~ "25-29",
      !is.na(Age_years) & Age_years >= 30 & Age_years <= 40 ~ "30-40",
      !is.na(Age_years) & Age_years >= 41 & Age_years <= 50 ~ "41-50",
      !is.na(Age_years) & Age_years > 50 ~ ">51",
      TRUE ~ NA_character_
    ),

    # --------------------------------------------------------
    # ADMISSION SOURCE
    # --------------------------------------------------------
    Admission_display = case_when(

      as.character(Admission_source) == "1" ~ "Emergency",
      as.character(Admission_source) == "2" ~ "Medical Ward",
      as.character(Admission_source) == "3" ~ "Surgical Ward",
      as.character(Admission_source) == "4" ~ "Pediatrics Ward",
      as.character(Admission_source) == "5" ~ "Maternity Ward",
      as.character(Admission_source) == "6" ~ "Orthopedic Ward",
      as.character(Admission_source) == "7" ~ "HDU",
      as.character(Admission_source) == "8" ~ "Other",

      as.character(Admission_source) == "Emergency" ~ "Emergency",
      as.character(Admission_source) == "Medical Ward" ~ "Medical Ward",
      as.character(Admission_source) == "Surgical Ward" ~ "Surgical Ward",
      as.character(Admission_source) == "Pediatrics Ward" ~ "Pediatrics Ward",
      as.character(Admission_source) == "Maternity Ward" ~ "Maternity Ward",
      as.character(Admission_source) == "Orthopedic Ward" ~ "Orthopedic Ward",
      as.character(Admission_source) == "HDU" ~ "HDU",
      as.character(Admission_source) == "Other" ~ "Other",
      as.character(Admission_source) == "Other Specialty Wards" ~ "Other",

      TRUE ~ NA_character_
    ),

    # --------------------------------------------------------
    # DIAGNOSIS
    # --------------------------------------------------------
    Diagnosis_display = case_when(

      as.character(diag_superclass) == "1" ~
        "Cardiovascular Disease",

      as.character(diag_superclass) == "2" ~
        "Respiratory Disease",

      as.character(diag_superclass) == "3" ~
        "Neurological Disease",

      as.character(diag_superclass) == "4" ~
        "Sepsis / Infection",

      as.character(diag_superclass) == "5" ~
        "Gastrointestinal / Hepatic Disease",

      as.character(diag_superclass) == "6" ~
        "Trauma / Toxicology",

      as.character(diag_superclass) == "7" ~
        "Endocrine / Metabolic Disease",

      as.character(diag_superclass) == "8" ~
        "Renal Disease",

      as.character(diag_superclass) == "9" ~
        "Thromboembolism",

      as.character(diag_superclass) == "10" ~
        "Malignancy",

      as.character(diag_superclass) == "11" ~
        "Multi-organ Failure",

      as.character(diag_superclass) == "12" ~
        "Obstetric / Gynecology",

      as.character(diag_superclass) == "13" ~
        "Autoimmune / Systemic Disease",

      as.character(diag_superclass) == "14" ~
        "Other",

      as.character(diag_superclass) == "Cardiovascular Disease" ~
        "Cardiovascular Disease",

      as.character(diag_superclass) == "Respiratory Disease" ~
        "Respiratory Disease",

      as.character(diag_superclass) == "Neurological Disease" ~
        "Neurological Disease",

      as.character(diag_superclass) == "Sepsis / Infection" ~
        "Sepsis / Infection",

      as.character(diag_superclass) ==
        "Gastrointestinal / Hepatic Disease" ~
        "Gastrointestinal / Hepatic Disease",

      as.character(diag_superclass) == "Trauma / Toxicology" ~
        "Trauma / Toxicology",

      as.character(diag_superclass) ==
        "Endocrine / Metabolic Disease" ~
        "Endocrine / Metabolic Disease",

      as.character(diag_superclass) == "Renal Disease" ~
        "Renal Disease",

      as.character(diag_superclass) == "Thromboembolism" ~
        "Thromboembolism",

      as.character(diag_superclass) == "Malignancy" ~
        "Malignancy",

      as.character(diag_superclass) == "Multi-organ Failure" ~
        "Multi-organ Failure",

      as.character(diag_superclass) ==
        "Obstetric / Gynecology" ~
        "Obstetric / Gynecology",

      as.character(diag_superclass) ==
        "Autoimmune / Systemic Disease" ~
        "Autoimmune / Systemic Disease",

      as.character(diag_superclass) == "Other" ~
        "Other",

      TRUE ~ NA_character_
    )
  )


# ============================================================
# 2. CREATE A ROBUST MORTALITY OUTCOME
# ============================================================

# IMPORTANT:
# Do NOT overwrite the original stat variable.
# This safely recognizes the existing Survived/Died coding.

df_final_display <- df_final_display %>%
  mutate(
    Mortality_outcome = case_when(

      as.character(stat) %in%
        c("Survived", "survived", "Alive", "alive", "0") ~
        "Survived",

      as.character(stat) %in%
        c("Died", "died", "Dead", "dead", "1") ~
        "Died",

      TRUE ~ NA_character_
    )
  )


# ============================================================
# 3. LOS OUTCOME ORDER
# ============================================================

df_display <- df_display %>%
  mutate(
    LOS_outcome = case_when(

      as.character(LOS_binary) %in%
        c("<=7_days", "≤7 days", "<=7 days", "0") ~
        "<=7_days",

      as.character(LOS_binary) %in%
        c(">7_days", ">7 days", "1") ~
        ">7_days",

      TRUE ~ NA_character_
    )
  )


# ============================================================
# 4. SAFE P-VALUE FUNCTION
# ============================================================

get_pvalue <- function(x, y) {

  keep <- !is.na(x) & !is.na(y)

  x <- x[keep]
  y <- y[keep]

  tab <- table(x, y)

  if (length(tab) == 0 ||
      sum(tab) == 0 ||
      nrow(tab) < 2 ||
      ncol(tab) < 2) {
    return(NA_real_)
  }

  chi <- suppressWarnings(
    chisq.test(tab)
  )

  if (any(chi$expected < 5)) {

    return(
      suppressWarnings(
        chisq.test(
          tab,
          simulate.p.value = TRUE,
          B = 10000
        )$p.value
      )
    )

  } else {

    return(chi$p.value)
  }
}


# ============================================================
# 5. MORTALITY P-VALUES
# ============================================================

mortality_p_gender <- get_pvalue(
  df_final_display$Gender_display,
  df_final_display$Mortality_outcome
)

mortality_p_age <- get_pvalue(
  df_final_display$Age_group,
  df_final_display$Mortality_outcome
)

mortality_p_admission <- get_pvalue(
  df_final_display$Admission_display,
  df_final_display$Mortality_outcome
)

mortality_p_diagnosis <- get_pvalue(
  df_final_display$Diagnosis_display,
  df_final_display$Mortality_outcome
)


# ============================================================
# 6. LOS P-VALUES
# ============================================================

los_p_gender <- get_pvalue(
  df_display$Gender_display,
  df_display$LOS_outcome
)

los_p_age <- get_pvalue(
  df_display$Age_group,
  df_display$LOS_outcome
)

los_p_admission <- get_pvalue(
  df_display$Admission_display,
  df_display$LOS_outcome
)

los_p_diagnosis <- get_pvalue(
  df_display$Diagnosis_display,
  df_display$LOS_outcome
)


# ============================================================
# 7. FORMAT P-VALUE
# ============================================================

format_p <- function(p) {

  if (is.na(p)) {
    return("")
  }

  if (p < 0.001) {
    return("<0.001")
  }

  sprintf("%.3f", p)
}


# ============================================================
# 8. MORTALITY — GENDER
# ============================================================

mortality_gender <- df_final_display %>%
  filter(
    !is.na(Gender_display),
    !is.na(Mortality_outcome)
  ) %>%
  count(
    Category = Gender_display,
    Mortality_outcome
  ) %>%
  pivot_wider(
    names_from = Mortality_outcome,
    values_from = n,
    values_fill = 0
  ) %>%
  mutate(
    Category = as.character(Category)
  )

if (!"Survived" %in% names(mortality_gender)) {
  mortality_gender$Survived <- 0L
}

if (!"Died" %in% names(mortality_gender)) {
  mortality_gender$Died <- 0L
}

mortality_gender <- mortality_gender %>%
  mutate(
    Variable = "Gender"
  )


# ============================================================
# 9. MORTALITY — AGE GROUP
# ============================================================

mortality_age <- df_final_display %>%
  filter(
    !is.na(Age_group),
    !is.na(Mortality_outcome)
  ) %>%
  count(
    Category = Age_group,
    Mortality_outcome
  ) %>%
  pivot_wider(
    names_from = Mortality_outcome,
    values_from = n,
    values_fill = 0
  ) %>%
  mutate(
    Category = as.character(Category)
  )

if (!"Survived" %in% names(mortality_age)) {
  mortality_age$Survived <- 0L
}

if (!"Died" %in% names(mortality_age)) {
  mortality_age$Died <- 0L
}

mortality_age <- mortality_age %>%
  mutate(
    Variable = "Age group"
  )


# ============================================================
# 10. MORTALITY — ADMISSION SOURCE
# ============================================================

mortality_admission <- df_final_display %>%
  filter(
    !is.na(Admission_display),
    !is.na(Mortality_outcome)
  ) %>%
  count(
    Category = Admission_display,
    Mortality_outcome
  ) %>%
  pivot_wider(
    names_from = Mortality_outcome,
    values_from = n,
    values_fill = 0
  ) %>%
  mutate(
    Category = as.character(Category)
  )

if (!"Survived" %in% names(mortality_admission)) {
  mortality_admission$Survived <- 0L
}

if (!"Died" %in% names(mortality_admission)) {
  mortality_admission$Died <- 0L
}

mortality_admission <- mortality_admission %>%
  mutate(
    Variable = "Admission source"
  )


# ============================================================
# 11. MORTALITY — DIAGNOSIS
# ============================================================

mortality_diagnosis <- df_final_display %>%
  filter(
    !is.na(Diagnosis_display),
    !is.na(Mortality_outcome)
  ) %>%
  count(
    Category = Diagnosis_display,
    Mortality_outcome
  ) %>%
  pivot_wider(
    names_from = Mortality_outcome,
    values_from = n,
    values_fill = 0
  ) %>%
  mutate(
    Category = as.character(Category)
  )

if (!"Survived" %in% names(mortality_diagnosis)) {
  mortality_diagnosis$Survived <- 0L
}

if (!"Died" %in% names(mortality_diagnosis)) {
  mortality_diagnosis$Died <- 0L
}

mortality_diagnosis <- mortality_diagnosis %>%
  mutate(
    Variable = "Diagnosis"
  )


# ============================================================
# 12. MORTALITY RESULT
# ============================================================

mortality_result <- bind_rows(
  mortality_gender,
  mortality_age,
  mortality_admission,
  mortality_diagnosis
) %>%
  mutate(

    Category = as.character(Category),

    Survived = coalesce(Survived, 0L),
    Died = coalesce(Died, 0L),

    Mortality_Total = Survived + Died,

    # --------------------------------------------------------
    # WITHIN-CATEGORY PERCENTAGES
    # --------------------------------------------------------

    Survived_pct = if_else(
      Mortality_Total > 0,
      Survived / Mortality_Total * 100,
      NA_real_
    ),

    Died_pct = if_else(
      Mortality_Total > 0,
      Died / Mortality_Total * 100,
      NA_real_
    )
  ) %>%
  select(
    Variable,
    Category,
    Mortality_Total,
    Survived,
    Survived_pct,
    Died,
    Died_pct
  )


# ============================================================
# 13. LOS — GENDER
# ============================================================

los_gender <- df_display %>%
  filter(
    !is.na(Gender_display),
    !is.na(LOS_outcome)
  ) %>%
  count(
    Category = Gender_display,
    LOS_outcome
  ) %>%
  pivot_wider(
    names_from = LOS_outcome,
    values_from = n,
    values_fill = 0
  ) %>%
  mutate(
    Category = as.character(Category)
  )

if (!"<=7_days" %in% names(los_gender)) {
  los_gender[["<=7_days"]] <- 0L
}

if (!">7_days" %in% names(los_gender)) {
  los_gender[[">7_days"]] <- 0L
}

los_gender <- los_gender %>%
  mutate(
    Variable = "Gender"
  )


# ============================================================
# 14. LOS — AGE GROUP
# ============================================================

los_age <- df_display %>%
  filter(
    !is.na(Age_group),
    !is.na(LOS_outcome)
  ) %>%
  count(
    Category = Age_group,
    LOS_outcome
  ) %>%
  pivot_wider(
    names_from = LOS_outcome,
    values_from = n,
    values_fill = 0
  ) %>%
  mutate(
    Category = as.character(Category)
  )

if (!"<=7_days" %in% names(los_age)) {
  los_age[["<=7_days"]] <- 0L
}

if (!">7_days" %in% names(los_age)) {
  los_age[[">7_days"]] <- 0L
}

los_age <- los_age %>%
  mutate(
    Variable = "Age group"
  )


# ============================================================
# 15. LOS — ADMISSION SOURCE
# ============================================================

los_admission <- df_display %>%
  filter(
    !is.na(Admission_display),
    !is.na(LOS_outcome)
  ) %>%
  count(
    Category = Admission_display,
    LOS_outcome
  ) %>%
  pivot_wider(
    names_from = LOS_outcome,
    values_from = n,
    values_fill = 0
  ) %>%
  mutate(
    Category = as.character(Category)
  )

if (!"<=7_days" %in% names(los_admission)) {
  los_admission[["<=7_days"]] <- 0L
}

if (!">7_days" %in% names(los_admission)) {
  los_admission[[">7_days"]] <- 0L
}

los_admission <- los_admission %>%
  mutate(
    Variable = "Admission source"
  )


# ============================================================
# 16. LOS — DIAGNOSIS
# ============================================================

los_diagnosis <- df_display %>%
  filter(
    !is.na(Diagnosis_display),
    !is.na(LOS_outcome)
  ) %>%
  count(
    Category = Diagnosis_display,
    LOS_outcome
  ) %>%
  pivot_wider(
    names_from = LOS_outcome,
    values_from = n,
    values_fill = 0
  ) %>%
  mutate(
    Category = as.character(Category)
  )

if (!"<=7_days" %in% names(los_diagnosis)) {
  los_diagnosis[["<=7_days"]] <- 0L
}

if (!">7_days" %in% names(los_diagnosis)) {
  los_diagnosis[[">7_days"]] <- 0L
}

los_diagnosis <- los_diagnosis %>%
  mutate(
    Variable = "Diagnosis"
  )


# ============================================================
# 17. LOS RESULT
# ============================================================

los_result <- bind_rows(
  los_gender,
  los_age,
  los_admission,
  los_diagnosis
) %>%
  mutate(

    Category = as.character(Category),

    `<=7_days` = coalesce(`<=7_days`, 0L),
    `>7_days` = coalesce(`>7_days`, 0L),

    LOS_Total = `<=7_days` + `>7_days`,

    # --------------------------------------------------------
    # WITHIN-CATEGORY PERCENTAGES
    # --------------------------------------------------------

    `<=7_pct` = if_else(
      LOS_Total > 0,
      `<=7_days` / LOS_Total * 100,
      NA_real_
    ),

    `>7_pct` = if_else(
      LOS_Total > 0,
      `>7_days` / LOS_Total * 100,
      NA_real_
    )
  ) %>%
  select(
    Variable,
    Category,
    LOS_Total,
    `<=7_days`,
    `<=7_pct`,
    `>7_days`,
    `>7_pct`
  )


# ============================================================
# 18. MERGE MORTALITY + LOS
# ============================================================

result_combined <- full_join(
  mortality_result,
  los_result,
  by = c("Variable", "Category")
)


# ============================================================
# 19. ADD P-VALUES
# ============================================================

result_combined <- result_combined %>%
  mutate(

    `Mortality p-value` = case_when(
      Variable == "Gender" ~ format_p(mortality_p_gender),
      Variable == "Age group" ~ format_p(mortality_p_age),
      Variable == "Admission source" ~ format_p(mortality_p_admission),
      Variable == "Diagnosis" ~ format_p(mortality_p_diagnosis),
      TRUE ~ ""
    ),

    `LOS p-value` = case_when(
      Variable == "Gender" ~ format_p(los_p_gender),
      Variable == "Age group" ~ format_p(los_p_age),
      Variable == "Admission source" ~ format_p(los_p_admission),
      Variable == "Diagnosis" ~ format_p(los_p_diagnosis),
      TRUE ~ ""
    )
  )


# ============================================================
# 20. VARIABLE ORDER
# ============================================================

result_combined$Variable <- factor(
  result_combined$Variable,
  levels = c(
    "Gender",
    "Age group",
    "Admission source",
    "Diagnosis"
  )
)

result_combined <- result_combined %>%
  arrange(Variable)


# ============================================================
# 21. SHOW VARIABLE + P-VALUE ONLY ONCE
# ============================================================

result_combined <- result_combined %>%
  group_by(Variable) %>%
  mutate(

    Variable_display = if_else(
      row_number() == 1,
      as.character(Variable),
      ""
    ),

    Mortality_p_display = if_else(
      row_number() == 1,
      `Mortality p-value`,
      ""
    ),

    LOS_p_display = if_else(
      row_number() == 1,
      `LOS p-value`,
      ""
    )
  ) %>%
  ungroup()


# ============================================================
# 22. FINAL TABLE DATA
# ============================================================

result_combined <- result_combined %>%
  select(

    Variable_display,
    Category,

    Mortality_Total,
    Survived,
    Survived_pct,
    Died,
    Died_pct,
    Mortality_p_display,

    LOS_Total,
    `<=7_days`,
    `<=7_pct`,
    `>7_days`,
    `>7_pct`,
    LOS_p_display
  )


# ============================================================
# 23. PUBLICATION TABLE
# ============================================================

publishable_table_los <- result_combined %>%

  gt() %>%

  # ----------------------------------------------------------
  # COLUMN LABELS
  # ----------------------------------------------------------

  cols_label(

    Variable_display = "Variable",
    Category = "Category",

    # Total values are intentionally NOT displayed
    Mortality_Total = "",

    # Survived
    Survived = "",
    Survived_pct = "%",

    # Died
    Died = "",
    Died_pct = "%",

    Mortality_p_display = "p-value",

    # Total values are intentionally NOT displayed
    LOS_Total = "",

    # ≤7 days
    `<=7_days` = "",
    `<=7_pct` = "%",

    # >7 days
    `>7_days` = "",
    `>7_pct` = "%",

    LOS_p_display = "p-value"
  ) %>%


  # ----------------------------------------------------------
  # SURVIVED
  # ----------------------------------------------------------

  tab_spanner(
    label = "Survived",
    columns = c(
      Survived,
      Survived_pct
    ),
    id = "survived"
  ) %>%


  # ----------------------------------------------------------
  # DIED
  # ----------------------------------------------------------

  tab_spanner(
    label = "Died",
    columns = c(
      Died,
      Died_pct
    ),
    id = "died"
  ) %>%


  # ----------------------------------------------------------
  # ≤7 DAYS
  # ----------------------------------------------------------

  tab_spanner(
    label = "≤7 days",
    columns = c(
      `<=7_days`,
      `<=7_pct`
    ),
    id = "short_los"
  ) %>%


  # ----------------------------------------------------------
  # >7 DAYS
  # ----------------------------------------------------------

  tab_spanner(
    label = ">7 days",
    columns = c(
      `>7_days`,
      `>7_pct`
    ),
    id = "long_los"
  ) %>%


  # ----------------------------------------------------------
  # BOLD VARIABLE
  # ----------------------------------------------------------

  tab_style(
    style = cell_text(
      weight = "bold"
    ),
    locations = cells_body(
      columns = Variable_display,
      rows = Variable_display != ""
    )
  ) %>%


  # ----------------------------------------------------------
  # INDENT CATEGORY
  # ----------------------------------------------------------

  tab_style(
    style = cell_text(
      indent = px(15)
    ),
    locations = cells_body(
      columns = Category
    )
  ) %>%


  # ----------------------------------------------------------
  # LINE BEFORE EACH VARIABLE
  # ----------------------------------------------------------

  tab_style(
    style = cell_borders(
      sides = "top",
      color = "black",
      weight = px(1)
    ),
    locations = cells_body(
      rows = Variable_display != ""
    )
  ) %>%


  # ----------------------------------------------------------
  # LEFT ALIGNMENT
  # ----------------------------------------------------------

  cols_align(
    align = "left",
    columns = c(
      Variable_display,
      Category
    )
  ) %>%


  # ----------------------------------------------------------
  # CENTER NUMERICAL COLUMNS
  # ----------------------------------------------------------

  cols_align(
    align = "center",
    columns = c(

      Mortality_Total,

      Survived,
      Survived_pct,

      Died,
      Died_pct,

      Mortality_p_display,

      LOS_Total,

      `<=7_days`,
      `<=7_pct`,

      `>7_days`,
      `>7_pct`,

      LOS_p_display
    )
  ) %>%


  # ----------------------------------------------------------
  # PERCENTAGES — ONE DECIMAL
  # ----------------------------------------------------------

  fmt_number(
    columns = c(
      Survived_pct,
      Died_pct,
      `<=7_pct`,
      `>7_pct`
    ),
    decimals = 1
  ) %>%


  # ----------------------------------------------------------
  # TABLE STYLE
  # ----------------------------------------------------------

  tab_options(

    table.border.top.color = "black",
    table.border.bottom.color = "black",

    table.border.top.width = px(1),
    table.border.bottom.width = px(1),

    column_labels.border.top.width = px(1),
    column_labels.border.bottom.width = px(1),

    table.font.size = px(12),
    data_row.padding = px(5)
  )


# ============================================================
# 24. DISPLAY FINAL TABLE
# ============================================================

publishable_table_los
Variable Category
Survived
Died
p-value
≤7 days
>7 days
p-value
% % % %
Gender Female 2342 1467 62.6 875 37.4 0.043 1386 581 41.9 805 58.1 0.578
Male 3173 1901 59.9 1272 40.1 1867 802 43.0 1065 57.0
Age group 25-29 247 72 29.1 175 70.9 <0.001 184 103 56.0 81 44.0 <0.001
30-40 556 206 37.1 350 62.9 370 175 47.3 195 52.7
41-50 680 396 58.2 284 41.8 408 165 40.4 243 59.6
<=24 286 114 39.9 172 60.1 188 96 51.1 92 48.9
>51 3742 2580 68.9 1162 31.1 2102 844 40.2 1258 59.8
Admission source Emergency 3491 2177 62.4 1314 37.6 <0.001 2051 845 41.2 1206 58.8 0.272
HDU 15 12 80.0 3 20.0 12 5 41.7 7 58.3
Maternity Ward 111 87 78.4 24 21.6 59 32 54.2 27 45.8
Medical Ward 839 389 46.4 450 53.6 469 212 45.2 257 54.8
Orthopedic Ward 32 17 53.1 15 46.9 20 7 35.0 13 65.0
Other 150 59 39.3 91 60.7 74 28 37.8 46 62.2
Pediatrics Ward 13 11 84.6 2 15.4 6 2 33.3 4 66.7
Surgical Ward 864 616 71.3 248 28.7 562 252 44.8 310 55.2
Diagnosis Autoimmune / Systemic Disease 18 9 50.0 9 50.0 <0.001 10 7 70.0 3 30.0 <0.001
Cardiovascular Disease 1385 655 47.3 730 52.7 841 404 48.0 437 52.0
Endocrine / Metabolic Disease 226 190 84.1 36 15.9 140 56 40.0 84 60.0
Gastrointestinal / Hepatic Disease 440 339 77.0 101 23.0 237 113 47.7 124 52.3
Malignancy 126 102 81.0 24 19.0 76 30 39.5 46 60.5
Multi-organ Failure 76 0 0.0 76 100.0 33 17 51.5 16 48.5
Neurological Disease 923 576 62.4 347 37.6 549 211 38.4 338 61.6
Obstetric / Gynecology 51 36 70.6 15 29.4 34 18 52.9 16 47.1
Other 239 164 68.6 75 31.4 134 54 40.3 80 59.7
Renal Disease 151 81 53.6 70 46.4 101 43 42.6 58 57.4
Respiratory Disease 873 489 56.0 384 44.0 495 216 43.6 279 56.4
Sepsis / Infection 626 456 72.8 170 27.2 366 137 37.4 229 62.6
Thromboembolism 133 88 66.2 45 33.8 68 17 25.0 51 75.0
Trauma / Toxicology 248 183 73.8 65 26.2 169 60 35.5 109 64.5