
clinical_obesity <- read.csv("clinical_obesity.csv")
library(tidyverse)

# --- 1. Education_Level 
cat("=== Education_Level 分布情况 (未加权) ===\n")

edu_dist <- merged_df %>%
  count(Education_Level) %>%
  mutate(
    Percentage = round(n / sum(n) * 100, 2) 
  ) %>%
  arrange(desc(Percentage)) 

print(edu_dist)

# --- 2. 
vars_to_check <- c("PIR", "Cancer", "Alcohol", "Smoking")

cat("\n=== 指定变量的缺失值统计 ===\n")

missing_stats <- merged_df %>%
  select(all_of(vars_to_check)) %>%
  summarise_all(list(
    Missing_Count = ~sum(is.na(.)),
    Missing_Rate_Percent = ~round(mean(is.na(.)) * 100, 2)
  )) %>%
  pivot_longer(cols = everything(), 
               names_to = c("Variable", ".value"), 
               names_pattern = "(.*)_(.*)")

print(missing_stats)

# --- 3. 
# library(naniar)
# gg_miss_var(merged_df %>% select(all_of(c("Education_Level", vars_to_check))))
write_csv(merged_df, "merged_df.csv")  



library(mice)
vars_for_mice <- c("SEQN_new", 
                   "Education_Level", "PIR", "Cancer", "Alcohol", "Smoking", 
                   "Age", "Gender", "BMXBMI", "Races")                     

df_subset <- merged_df %>% select(all_of(vars_for_mice))

df_subset <- df_subset %>%
  mutate(
    Education_Level = as.factor(Education_Level),
    Cancer = as.factor(Cancer),
    Alcohol = as.factor(Alcohol),
    Smoking = as.factor(Smoking),
    Gender = as.factor(Gender),
    Races = as.factor(Races)
  )
cat("正在运行 MICE 多重插补，请稍候...\n")
mice_mod <- mice(df_subset, m = 5, maxit = 5, seed = 123, printFlag = FALSE)


completed_subset <- complete(mice_mod, action = 1)


df_imputed_final <- merged_df


match_idx <- match(df_imputed_final$SEQN_new, completed_subset$SEQN_new)
df_imputed_final$PIR             <- completed_subset$PIR[match_idx]
df_imputed_final$Education_Level <- completed_subset$Education_Level[match_idx]
df_imputed_final$Cancer          <- completed_subset$Cancer[match_idx]
df_imputed_final$Alcohol         <- completed_subset$Alcohol[match_idx]
df_imputed_final$Smoking         <- completed_subset$Smoking[match_idx]

#6. 

check_vars <- c("Education_Level", "PIR", "Cancer", "Alcohol", "Smoking")
missing_counts <- colSums(is.na(df_imputed_final[, check_vars]))

cat("\n=== 插补后缺失值检查 (应全为 0) ===\n")
print(missing_counts)

write_csv(df_imputed_final, "imputed_clinical_obesity.csv")

df_imputed_final <- df_imputed_final %>%
  mutate(
    1. 新增 Clinical_Obesity3---
    Clinical_Obesity3 = case_when(   
      is.na(Obesity_Simple) ~ NA_real_,
      Obesity_Simple == 1 & (
        as.character(diabetes.x) %in% c("diabetes", "prediabetes", "Diabetes", "Prediabetes") |
          
          as.character(Fatty_Liver_Fibrosis) == "1" |
          as.character(Renal) == "1" |
          as.character(Hypertension) == "1" |
          as.character(Dyslipidemia) == "1" |
          as.character(Urinary_incontinence2) == "1" |
          as.character(Musculoskeletal2) == "1" |
          as.character(Limitations_of_daily_activities2) == "1" |
          as.character(Respiratory) == "1" |
          
       3
          as.character(if("heart_failure.1" %in% names(.)) heart_failure.1 else heart_failure) == "1"
      ) ~ 1,
      TRUE ~ 0
    )
  )

df_imputed_final <- df_imputed_final %>%
  mutate(
    Obesity_level3 = case_when(
      Clinical_Obesity3 == 1 ~ "Clinical_obesity",
      Clinical_Obesity3 == 0 & Obesity_Simple== 1 ~ "Preobesity",
      TRUE ~ "Normal"
    ),
    Obesity_level3 = factor(
      Obesity_level3,
      levels = c("Normal", "Preobesity", "Clinical_obesity")
    )
  )  




library(survey)

# 1. 
df_trend <- df_imputed_final %>%
  mutate(
 
    WTMEC2YR = as.numeric(as.character(WTMEC2YR)),
    SDMVPSU  = as.numeric(as.character(SDMVPSU)),
    SDMVSTRA = as.numeric(as.character(SDMVSTRA)),
   
    Survey_Year = as.factor(Survey_Year),
    Obesity_level3 = as.factor(Obesity_level3)
  ) %>%
  filter(!is.na(WTMEC2YR))

cat("WTMEC2YR 类型:", class(df_trend$WTMEC2YR), "\n")

# 2. 
design_trend <- svydesign(
  id = ~SDMVPSU,
  strata = ~SDMVSTRA,
  weights = ~WTMEC2YR,
  data = df_trend,
  nest = TRUE
)


#  3. 
results_raw <- svyby(
  formula = ~Obesity_level3, 
  by = ~Survey_Year, 
  design = design_trend, 
  FUN = svymean, 
  vartype = "ci"
)

# 4. 
results_clean <- results_raw %>%
  pivot_longer(
    cols = -Survey_Year, 
    names_to = c("Type", "Group"),
    names_pattern = "(Obesity_level3|ci_l|ci_u)(.*)" 
  ) %>%
  mutate(
    Group = str_remove(Group, "^Obesity_level3"), 
    Measure = case_when(
      Type == "Obesity_level3" ~ "Prevalence",
      Type == "ci_l" ~ "CI_Lower",
      Type == "ci_u" ~ "CI_Upper"
    )
  ) %>%
  select(-Type) %>%
  pivot_wider(
    names_from = Measure,
    values_from = value
  ) %>%
  mutate(
    Prevalence = round(Prevalence * 100, 2),
    CI_Lower = round(CI_Lower * 100, 2),
    CI_Upper = round(CI_Upper * 100, 2),
    Output_Format = paste0(Prevalence, "% (", CI_Lower, "-", CI_Upper, ")") 
  )
library(writexl)
write_xlsx(results_clean, "Obesity_level3.xlsx")


# 1.
raw_data <- tibble(
  Survey_Year = c("1999_2000", "1999_2000", "2001_2002", "2001_2002", 
                  "2003_2004", "2003_2004", "2005_2006", "2005_2006", 
                  "2007_2008", "2007_2008", "2009_2010", "2009_2010", 
                  "2011_2012", "2011_2012", "2013_2014", "2013_2014", 
                  "2015_2016", "2015_2016", "2017_2018", "2017_2018"),
  Group = rep(c("Clinical_obesity", "Preclinical obesity"), 10),
  
  Prevalence = c(34.63, 12.02, # 1999-2000
                 35.47, 12.78, # 2001-2002
                 37.21, 14.90, # 2003-2004
                 37.95, 14.47, # 2005-2006
                 39.62, 12.13, # 2007-2008
                 40.69, 12.55, # 2009-2010
                 41.26, 14.42, # 2011-2012
                 42.64, 15.34, # 2013-2014
                 43.98, 16.23, # 2015-2016
                 46.60, 15.11) # 2017-2018
)


# 2. 
bar_data <- raw_data %>%
  mutate(Survey_Year = str_replace(Survey_Year, "_", "-")) %>% 
  mutate(
    Group = case_when(
      Group == "Preclinical obesity" ~ "Preclinical obesity",
      Group == "Clinical_obesity"    ~ "Clinical Obesity",
      TRUE ~ Group
    )
  ) %>%
  mutate(
    Group = factor(Group, levels = c("Clinical Obesity", "Preclinical obesity"))
  )
total_trend_data <- bar_data %>%
  group_by(Survey_Year) %>%
  summarise(
    Total_Prev = sum(Prevalence)
  ) %>%
  ungroup()


# 3.
npg_colors <- c("Clinical Obesity" = "#E64B35", "Preclinical obesity" = "#4DBBD5")

p <- ggplot() +
  
  geom_bar(data = bar_data, 
           aes(x = Survey_Year, y = Prevalence, fill = Group), 
           stat = "identity", 
           position = "stack", 
           width = 0.65, 
           alpha = 0.95) +
 
  geom_text(data = bar_data,
            aes(x = Survey_Year, y = Prevalence, group = Group, 
                label = sprintf("%.1f", Prevalence)),
            position = position_stack(vjust = 0.5), 
            color = "white",
            size = 3.2,
            fontface = "bold") +
  
  geom_line(data = total_trend_data,
            aes(x = Survey_Year, y = Total_Prev, group = 1), 
            color = "gray30", 
            size = 0.8,
            linetype = "dashed") +
  
  geom_point(data = total_trend_data,
             aes(x = Survey_Year, y = Total_Prev),
             color = "gray30",
             fill = "white",
             shape = 21,
             size = 2.5,
             stroke = 1.2) +
  
  geom_text(data = total_trend_data,
            aes(x = Survey_Year, y = Total_Prev, label = sprintf("%.1f", Total_Prev)),
            vjust = -0.8, 
            color = "gray20",
            size = 3.5,
            fontface = "bold") +
  
  scale_fill_manual(values = npg_colors) +
  
  scale_y_continuous(
    limits = c(0, max(total_trend_data$Total_Prev) * 1.15), 
    expand = c(0, 0),
    name = "Weighted Prevalence (%)"
  ) +
  
  labs(
    title = "Trends in Prevalence of Preobesity and Clinical Obesity",
    subtitle = "NHANES 1999-2018 (Weighted)",
    x = "Survey Cycle",
    fill = "" 
  ) +
  
  theme_classic(base_size = 14) +
  theme(
    plot.title = element_text(face = "bold", hjust = 0.5, size = 16, margin = margin(b = 10)),
    plot.subtitle = element_text(hjust = 0.5, color = "gray40", size = 12, margin = margin(b = 20)),
    axis.text.x = element_text(angle = 45, hjust = 1, color = "black", size = 11),
    axis.text.y = element_text(color = "black", size = 11),
    axis.line = element_line(size = 0.8, color = "black"),
    axis.title = element_text(face = "bold"),
    legend.position = "top",
    legend.text = element_text(size = 11, face = "bold"),
    legend.margin = margin(b = -5),
    plot.margin = margin(20, 20, 20, 20)
  )

# 4. 

print(p)

ggsave("Stacked_Bar_Trend_Updated.pdf", p, width = 10, height = 7)




df_compare <- df_imputed_final %>%
  mutate(
    WTMEC2YR = as.numeric(as.character(WTMEC2YR)),
    SDMVPSU  = as.numeric(as.character(SDMVPSU)),
    SDMVSTRA = as.numeric(as.character(SDMVSTRA)),
    Age = as.numeric(Age),
    PIR = as.numeric(PIR),
    Gender = as.factor(Gender),
    Races = as.factor(Races),
    Education_Level = as.factor(Education_Level),
    Alcohol = as.factor(Alcohol),
    Cancer = factor(case_when(as.numeric(as.character(Cancer)) == 9 ~ 2, TRUE ~ as.numeric(as.character(Cancer)))),
    Smoking = factor(case_when(as.numeric(as.character(Smoking)) %in% c(7,9) ~ 2, TRUE ~ as.numeric(as.character(Smoking)))),
    
    Status_AllCause = case_when(Survival_state %in% c("Dead", 1) ~ 1, TRUE ~ 0),
    Status_CVD = case_when(as.character(UCOD_LEADING) %in% c("1", "001") ~ 1, TRUE ~ 0),
    
    Obesity_level3 = as.character(Obesity_level3),
    Obesity_level3 = case_when(
      Obesity_level3 == "Clinical_obesity" ~ "Clinical obesity", 
      Obesity_level3 == "Preclinical_obesity" ~ "Preclinical obesity"
      Obesity_level3 == "Preobesity" ~ "Preclinical obesity",
      TRUE ~ Obesity_level3 
    ),
    Obesity_level3 = factor(Obesity_level3, levels = c("Normal", "Preclinical obesity", "Clinical obesity"))
  ) %>%
  filter(!is.na(WTMEC2YR)) %>%
  filter(!is.na(Obesity_level3))

cat("=== 检查 Obesity_level3 组名 (应无下划线) ===\n")
print(unique(df_compare$Obesity_level3))

# 2. Obesity_level3

analyze_risk_vs_ref <- function(ref_group_name) {
  
  cat(paste0("\n正在分析: 参照组设为 [", ref_group_name, "] ...\n"))
  
  df_run <- df_compare
  tryCatch({
    df_run$Obesity_level3 <- relevel(df_run$Obesity_level3, ref = ref_group_name)
  }, error = function(e) {
    stop(paste0("错误：在 Obesity_level3 中找不到 '", ref_group_name, "'。"))
  })
  
  design_run <- svydesign(id=~SDMVPSU, strata=~SDMVSTRA, weights=~WTMEC2YR, data=df_run, nest=TRUE)
  
  # C. 
  
  # 1. 全因死亡
  m1_all <- svycoxph(Surv(Follow_months, Status_AllCause) ~ Obesity_level3, design=design_run)
  m2_all <- svycoxph(Surv(Follow_months, Status_AllCause) ~ Obesity_level3 + Age + Gender + Races, design=design_run)
  m3_all <- svycoxph(Surv(Follow_months, Status_AllCause) ~ Obesity_level3 + Age + Gender + Races + PIR + Education_Level + Smoking + Alcohol + Cancer, design=design_run)
  
  # 2. 心血管死亡
  m1_cvd <- svycoxph(Surv(Follow_months, Status_CVD) ~ Obesity_level3, design=design_run)
  m2_cvd <- svycoxph(Surv(Follow_months, Status_CVD) ~ Obesity_level3 + Age + Gender + Races, design=design_run)
  m3_cvd <- svycoxph(Surv(Follow_months, Status_CVD) ~ Obesity_level3 + Age + Gender + Races + PIR + Education_Level + Smoking + Alcohol + Cancer, design=design_run)
  
  # D. 提取结果
  extract_hr <- function(model, mod_name, outcome) {
    tidy(model, exponentiate = TRUE, conf.int = TRUE) %>%
      # 筛选 "Clinical obesity" (带空格，与 Step 1 对应)
      filter(str_detect(term, "Clinical obesity")) %>% 
      mutate(
        Comparison = paste0("Clinical Obesity vs. ", ref_group_name), 
        Outcome = outcome,
        Model = mod_name,
        HR_95CI = paste0(sprintf("%.2f", estimate), " (", sprintf("%.2f", conf.low), "-", sprintf("%.2f", conf.high), ")"),
        P_Value = ifelse(p.value < 0.001, "<0.001", sprintf("%.3f", p.value)),
        Result_Interpretation = case_when(
          p.value < 0.05 & estimate > 1 ~ "Risk Significantly HIGHER",
          p.value < 0.05 & estimate < 1 ~ "Risk Significantly LOWER",
          TRUE ~ "No Significant Difference"
        )
      ) %>%
      select(Comparison, Outcome, Model, HR_95CI, P_Value, Result_Interpretation)
  }
  
  bind_rows(
    extract_hr(m1_all, "Model 1 (Unadj)", "All-cause Mortality"),
    extract_hr(m2_all, "Model 2 (Min adj)", "All-cause Mortality"),
    extract_hr(m3_all, "Model 3 (Fully adj)", "All-cause Mortality"),
    extract_hr(m1_cvd, "Model 1 (Unadj)", "CVD Mortality"),
    extract_hr(m2_cvd, "Model 2 (Min adj)", "CVD Mortality"),
    extract_hr(m3_cvd, "Model 3 (Fully adj)", "CVD Mortality")
  )
}

# 3. 
result_A <- analyze_risk_vs_ref("Normal")
result_B <- analyze_risk_vs_ref("Preclinical obesity")
# 4. 汇总与展示


final_comparison <- bind_rows(result_A, result_B)

cat("\n=== Clinical Obesity 风险比较结果 (最终修正版) ===\n")
print(final_comparison)
write_csv(final_comparison, "Comparisons_Obesity_Level3_Final.csv")



# 1. 
df_tab1 <- df_imputed_final %>%
  mutate(
    Cancer = case_when(as.numeric(as.character(Cancer)) == 9 ~ 2, TRUE ~ as.numeric(as.character(Cancer))),
    Smoking = case_when(as.numeric(as.character(Smoking)) %in% c(7, 9) ~ 2, TRUE ~ as.numeric(as.character(Smoking))),
    Group_Classification = as.character(Obesity_level2),
    Group_Classification = case_when(
      Group_Classification == "Clinical_obesity" ~ "Clinical obesity",
      Group_Classification == "Preclinical_obesity" ~ "Preclinical obesity",
      TRUE ~ Group_Classification
    )
    Group_Classification = factor(Group_Classification, levels = c(
      "Normal",
      "Preclinical obesity", 
      "Clinical obesity"
    ))
  )


# 2.
label(df_tab1$Age)                    <- "Age (years)"
label(df_tab1$Gender)                 <- "Gender"
label(df_tab1$Races)                  <- "Race/Ethnicity"
label(df_tab1$Education_Level)        <- "Education Level"
label(df_tab1$PIR)                    <- "Poverty Income Ratio (PIR)"
label(df_tab1$BMXBMI)                 <- "BMI (kg/m²)"
label(df_tab1$Follow_months)          <- "Follow-up Duration (months)"

label(df_tab1$diabetes.x)             <- "Hyperglycemia"
hf_col <- if("heart_failure.1" %in% names(df_tab1)) "heart_failure.1" else "heart_failure"
if(hf_col %in% names(df_tab1)) label(df_tab1[[hf_col]]) <- "Heart failure"

label(df_tab1$Cancer)                 <- "History of Cancer"
label(df_tab1$Hypertension)           <- "Hypertension" 

label(df_tab1$Dyslipidemia)           <- "Dyslipidemia"
label(df_tab1$Renal)                  <- "Chronic Kidney Disease"
label(df_tab1$Fatty_Liver_Fibrosis)   <- "Fatty Liver / Fibrosis"

label(df_tab1$Respiratory)                 <- "Respiratory"
label(df_tab1$Musculoskeletal2)                 <- "Musculoskeletal Disease"
label(df_tab1$Urinary_incontinence2)            <- "Urinary Incontinence"
label(df_tab1$Limitations_of_daily_activities2) <- "Limitations of Daily Activities"
label(df_tab1$Respiratory) <- "Respiratory"
label(df_tab1$Alcohol)                <- "Alcohol Consumption"
label(df_tab1$Smoking)                <- "Smoking Status"
label(df_tab1$Survival_state)         <- "All-cause Mortality"
label(df_tab1$Premature_death_70)     <- "Premature Death (<70 years)"
label(df_tab1$Cardiovascular_Mortality) <- "Cardiovascular Mortality"

cat_vars <- c("Gender", "Races", "Education_Level", 
              "diabetes.x", "ASCVD.x", "Cancer", hf_col,
              "Alcohol", "Smoking", 
              "Hypertension", # 【修改处】
              "Dyslipidemia", "Renal", "Fatty_Liver_Fibrosis", "Respiratory",
              "Musculoskeletal2", "Urinary_incontinence2", "Limitations_of_daily_activities2","Respiratory == 1",
              "Survival_state", "Premature_death_70", "Cardiovascular_Mortality")

for (v in cat_vars) {
  if (v %in% names(df_tab1)) {
    df_tab1[[v]] <- as.factor(df_tab1[[v]])
  }
}

# 3. 
my_formula <- paste0(
  "~ Education_Level + PIR + Gender + Age + Races + ",
  "diabetes.x + ", hf_col, " + Cancer + BMXBMI + ",
  "Survival_state + Follow_months + Premature_death_70 + Cardiovascular_Mortality + ",
  "Alcohol + Smoking + Hypertension + Dyslipidemia + ",
  "Renal + Fatty_Liver_Fibrosis + Musculoskeletal2 + Urinary_incontinence2 + Limitations_of_daily_activities2+Respiratory",
  "| Group_Classification"
)
table1_final <- table1(as.formula(my_formula), 
                       data = df_tab1,
                       overall = "Total",
                       extra.col = list(`P-value`=pvalue),
                       render.continuous = c(.="Mean (SD)"))
print(table1_final)

ft_object <- t1flex(table1_final)
save_as_docx(ft_object, path = "Baseline_Table1.docx")

###Multimorbidity Count##
# 1. 
df_counts_full <- df_imputed_final %>%
  filter(Clinical_Obesity2 == 1) %>%
  mutate(
    Score_Diabetes = case_when(
      as.character(diabetes.x) %in% c("diabetes", "prediabetes", "Diabetes", "Prediabetes") ~ 1,
      TRUE ~ 0
    ),
    Score_HF    = coalesce(ifelse(as.character(heart_failure.1) == "1", 1, 0), 0),
    Score_HTN   = coalesce(ifelse(as.character(Hypertension) == "1", 1, 0), 0),
    Score_Dys   = coalesce(ifelse(as.character(Dyslipidemia) == "1", 1, 0), 0),
    Score_Renal = coalesce(ifelse(as.character(Renal) == "1", 1, 0), 0),
    Score_Liver = coalesce(ifelse(as.character(Fatty_Liver_Fibrosis) == "1", 1, 0), 0),
    Score_Musc  = coalesce(ifelse(as.character(Musculoskeletal2) == "1", 1, 0), 0),
    Score_Uri   = coalesce(ifelse(as.character(Urinary_incontinence2) == "1", 1, 0), 0),
    Score_Limit = coalesce(ifelse(as.character(Limitations_of_daily_activities2) == "1", 1, 0), 0),
    Score_Res =coalesce(ifelse(as.character(Respiratory) == "1", 1, 0), 0),
    Comorbidity_Count = Score_Diabetes + Score_HF + Score_HTN + Score_Dys + 
      Score_Renal + Score_Liver + Score_Musc + Score_Uri + Score_Limit +Score_Res
  )

# 2. 
summary_full <- df_counts_full %>%
  count(Comorbidity_Count) %>%
  mutate(
    Total_N = sum(n),
    Percentage = round(n / Total_N * 100, 2),
    Label = paste0(n, " (", Percentage, "%)")
  ) %>%
  arrange(Comorbidity_Count)
# 3. 
print(summary_full)


df_mortality_analysis <- df_counts_full %>%
  mutate(
    Status_AllCause = case_when(Survival_state %in% c("Dead", 1) ~ 1, TRUE ~ 0),
    Status_CVD = case_when(as.character(UCOD_LEADING) %in% c("1", "001") ~ 1, TRUE ~ 0),
    
    Comorbidity_Group = case_when(
      Comorbidity_Count == 1 ~ "1 Disease",
      Comorbidity_Count == 2 ~ "2 Diseases",
      Comorbidity_Count == 3 ~ "3 Diseases",
      Comorbidity_Count == 4 ~ "4 Diseases",
      Comorbidity_Count >= 5 ~ "≥5 Diseases"
    )
  )

# 2.
mortality_stats <- df_mortality_analysis %>%
  group_by(Comorbidity_Group) %>%
  summarise(
    Total_N = n(),
    AllCause_Deaths = sum(Status_AllCause == 1, na.rm = TRUE),
    AllCause_Rate = round(AllCause_Deaths / Total_N * 100, 2),
    AllCause_Label = paste0(AllCause_Deaths, " (", AllCause_Rate, "%)"),
    CVD_Deaths = sum(Status_CVD == 1, na.rm = TRUE),
    CVD_Rate = round(CVD_Deaths / Total_N * 100, 2),
    CVD_Label = paste0(CVD_Deaths, " (", CVD_Rate, "%)")
  ) %>%
  arrange(factor(Comorbidity_Group, levels = c("1 Disease", "2 Diseases", "3 Diseases", "4 Diseases", "≥5 Diseases")))

# 3. 
print(mortality_stats)



# 1. 
df_forest <- tibble(
  Outcome = c(rep("All-cause Mortality", 6), rep("CVD Mortality", 6))
  Comparison = rep(c(
    rep("Clinical Obesity vs. Normal", 3),
    rep("Clinical Obesity vs. Preclinical obesity", 3)
  ), 2),
  
  Model = rep(c("Model 1 (Unadjusted)", "Model 2 (Minimally adj)", "Model 3 (Fully adj)"), 4),
    # All-cause (vs Normal)
    "1.64 (1.54-1.75)", "0.99 (0.94-1.04)", "0.95 (0.90-1.00)", 
    # All-cause (vs Preclinical)
    "2.87 (2.54-3.25)", "1.58 (1.40-1.78)", "1.45 (1.28-1.64)", 
    
    # CVD (vs Normal)
    "1.97 (1.76-2.21)", "1.17 (1.06-1.30)", "1.12 (1.01-1.24)", 
    # CVD (vs Preclinical)
    "3.45 (2.72-4.38)", "1.77 (1.41-2.21)", "1.60 (1.27-2.02)"  
  ),
  
  P_Value = c(
    # All-cause
    "<0.001", "0.676",  "0.052",
    "<0.001", "<0.001", "<0.001",
    
    # CVD
    "<0.001", "0.003",  "0.025",
    "<0.001", "<0.001", "<0.001"
  )
)
# 2. 
df_plot <- df_forest %>%
  extract(HR_String, into = c("HR", "Lower", "Upper"), 
          regex = "([0-9\\.]+) \\(([0-9\\.]+)-([0-9\\.]+)\\)", 
          remove = FALSE, convert = TRUE) %>%
   mutate(
    Outcome = factor(Outcome, levels = c("All-cause Mortality", "CVD Mortality")),
    Model = factor(Model, levels = c("Model 1 (Unadjusted)", "Model 2 (Minimally adj)", "Model 3 (Fully adj)")),
    Comparison = factor(Comparison, levels = c("Clinical Obesity vs. Normal", "Clinical Obesity vs. Preclinical obesity")),
    y_base = as.numeric(Comparison), 
    y_offset = case_when(
      Model == "Model 1 (Unadjusted)"    ~ 0.25,
      Model == "Model 2 (Minimally adj)" ~ 0,
      Model == "Model 3 (Fully adj)"     ~ -0.25
    ),
    
    y_final = y_base + y_offset
  )
# 3.
my_colors <- c(
  "Model 1 (Unadjusted)"    = "#00A087", # 绿
  "Model 2 (Minimally adj)" = "#4DBBD5", # 蓝
  "Model 3 (Fully adj)"     = "#E64B35"  # 红
)

p <- ggplot(df_plot, aes(x = HR, y = y_final, color = Model)) +
  geom_vline(xintercept = 1, linetype = "dashed", color = "gray50") +
  geom_errorbarh(aes(xmin = Lower, xmax = Upper), height = 0.2, size = 0.7) +
  geom_point(size = 3, shape = 15) + 
  geom_text(aes(x = 12, label = HR_String), 
            hjust = 0, size = 3.5, show.legend = FALSE, color = "black") +
  geom_text(aes(x = 60, label = P_Value), 
            hjust = 0, size = 3.5, show.legend = FALSE, color = "black") +
  facet_grid(Outcome ~ ., scales = "free_y", space = "free_y") +
  
  scale_x_log10(
    breaks = c(0.5, 1, 2, 5),
    limits = c(0.5, 120), 
    expand = c(0, 0)
  ) +
  scale_y_continuous(
    breaks = 1:2
    labels = c("vs. Preclinical", "vs. Normal")
  ) +
  
  scale_color_manual(values = my_colors) +
  
  # (8) 标签
  labs(
    title = "Hazard Ratios for Mortality: Clinical Obesity vs. Reference Groups",
    subtitle = "Comparison across three adjustment models",
    x = "Hazard Ratio (log scale)",
    y = "",
    color = "Model Adjustment"
  ) +
  
  # (9) 主题
  theme_classic(base_size = 15) +
  theme(
    panel.border = element_rect(color = "black", fill = NA, size = 1),
    strip.background = element_rect(fill = "gray95", color = "black"),
    strip.text = element_text(face = "bold", size = 13),
    
    axis.text.y = element_text(face = "bold", color = "black"),
    axis.text.x = element_text(color = "black"),
    axis.line.y = element_blank(),
    axis.ticks.y = element_blank(),
    
    legend.position = "top",
    legend.margin = margin(b = -5),
    
    plot.margin = margin(20, 20, 20, 20)
  )

# 4. 
print(p)
ggsave("Forest_Plot_Updated_Data.pdf", p, width = 12, height = 8)





library(poLCA)
library(tidyverse)
library(survival)
library(survminer)
library(reshape2)

# 1. 
lca_vars <- c("diabetes.x", "heart_failure.1", "Hypertension", "Dyslipidemia", 
              "Renal", "Fatty_Liver_Fibrosis", "Musculoskeletal2", 
              "Urinary_incontinence2", "Limitations_of_daily_activities2", "Respiratory")

df_lca <- df_imputed_final %>%
  filter(Clinical_Obesity3 == 1) %>% 
  dplyr::select(SEQN_new, Follow_months, Survival_state, all_of(lca_vars)) %>%
  na.omit()
df_lca <- df_lca %>%
  mutate(
    # 定义 Status: 1=死亡, 0=存活
    Status_LCA = case_when(
      Survival_state %in% c("Dead", 1, "1") ~ 1,
      TRUE ~ 0
    )
  )

df_lca_input <- df_lca %>%
  mutate(
    diabetes.x = ifelse(diabetes.x %in% c("diabetes", "prediabetes", "Diabetes", "Prediabetes"), 2, 1),
    heart_failure.1 = as.numeric(as.character(heart_failure.1)) + 1,
    Hypertension    = as.numeric(as.character(Hypertension)) + 1,
    Dyslipidemia    = as.numeric(as.character(Dyslipidemia)) + 1,
    Renal           = as.numeric(as.character(Renal)) + 1,
    Fatty_Liver_Fibrosis = as.numeric(as.character(Fatty_Liver_Fibrosis)) + 1,
    Musculoskeletal2     = as.numeric(as.character(Musculoskeletal2)) + 1,
    Urinary_incontinence2 = as.numeric(as.character(Urinary_incontinence2)) + 1,
    Limitations_of_daily_activities2 = as.numeric(as.character(Limitations_of_daily_activities2)) + 1,
    Respiratory = as.numeric(as.character(Respiratory)) + 1
  ) %>%
  dplyr::select(all_of(lca_vars))

# 2. 
f <- as.formula(paste("cbind(", paste(lca_vars, collapse = ","), ") ~ 1"))

set.seed(123)
best_model <- poLCA(f, df_lca_input, nclass = 3, maxiter = 1000, graphs = FALSE, tol = 1e-5, verbose = FALSE)
# 3. 结果提取 (【核心修改】使用手动循环提取，放弃 melt)
plot_data_list <- list()
for (var_name in names(best_model$probs)) {
  prob_matrix <- best_model$probs[[var_name]]
  if (ncol(prob_matrix) >= 2) {
    prob_values <- prob_matrix[, 2] 
  } else {
    prob_values <- rep(0, nrow(prob_matrix)) 
  }
  tmp_df <- data.frame(
    Class = paste("Class", 1:length(prob_values)), # Class 1, Class 2...
    Disease = var_name,
    value = prob_values
  )
  
  plot_data_list[[var_name]] <- tmp_df
}
plot_data <- bind_rows(plot_data_list)

cat("=== 检查绘图数据行数 (应大于0) ===\n")
print(nrow(plot_data))
print(head(plot_data))

# 4. 

p_profile <- ggplot(plot_data, aes(x = Disease, y = value, fill = Class)) +
  geom_bar(stat = "identity", position = "dodge", width = 0.7) +
  facet_wrap(~Class) +
  coord_flip() +
  scale_y_continuous(limits = c(0, 1), labels = scales::percent) +
  scale_fill_manual(values = c("#E64B35", "#4DBBD5", "#00A087")) +
  
  labs(
    title = "Comorbidity Profile by Latent Class",
    subtitle = "Probability of having each condition (Value = 2)",
    y = "Prevalence Probability",
    x = ""
  ) +
  
  theme_bw(base_size = 14) +
  theme(
    strip.background = element_rect(fill = "gray95"),
    strip.text = element_text(face = "bold"),
    legend.position = "none" # 分面已有标题，无需图例
  )

print(p_profile)

ggsave("LCA_Profile_Plot.pdf", p_profile, width = 10, height = 8)

library(survival)
library(survminer)
library(tidyverse)


fit_lca <- survfit(Surv(Follow_months, Status_LCA) ~ LCA_Label, data = df_lca)


p <- ggsurvplot(
  fit_lca, 
  data = df_lca,
  
  conf.int = TRUE,        
  pval = TRUE,             
  pval.method = TRUE,      
  risk.table = TRUE,      
  title = "Survival Analysis by Comorbidity Clusters",
  xlab = "Follow-up Time (Months)",
  ylab = "Survival Probability",
  
  palette = c("#00A087", "#4DBBD5", "#E64B35"), 
  
  ggtheme = theme_classic(),
  legend.title = "Cluster",
  
  conf.int.alpha = 0.2,
  
  risk.table.height = 0.25,
  risk.table.y.text.col = TRUE
)

print(p)

pdf("LCA_Survival_Curve_Shadow.pdf", width = 8, height = 7)
print(p, newpage = FALSE)
dev.off()
