#install.packages("conflicted")
#install.packages("dplyr")
#install.packages("FSA")
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.5.1     ✔ tibble    3.2.1
## ✔ lubridate 1.9.4     ✔ tidyr     1.3.1
## ✔ purrr     1.0.4     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(gtsummary)
library(gt)
library(readxl)
library(conflicted)
library(dplyr)
library(FSA)
## ## FSA v0.9.6. See citation('FSA') if used in publication.
## ## Run fishR() for related website and fishR('IFAR') for related book.
setwd(dir = "/Users/lorandacalderonzamora/Downloads/")
data <- read_excel("Copia_de_Base_de_datos_Angel-laura.xlsx")
knitr::opts_knit$set(root.dir = "/Users/lorandacalderonzamora/Downloads")
class(data)
## [1] "tbl_df"     "tbl"        "data.frame"
names(data)
##  [1] "Registro"                "Nombre"                 
##  [3] "GRUPO"                   "Sexo"                   
##  [5] "Edad"                    "Peso"                   
##  [7] "Talla"                   "IMC"                    
##  [9] "Cintura"                 "Cadera"                 
## [11] "ICC"                     "Glucosa"                
## [13] "HBA1c"                   "Colesterol_total"       
## [15] "VLDL"                    "LDL"                    
## [17] "HDL"                     "Trigliceridos"          
## [19] "Creatinina"              "Urea"                   
## [21] "BUN"                     "TFGe"                   
## [23] "DISFUNCIÓN_RENAL"        "RIESGO_CARDIO-VASCULAR" 
## [25] "RIESGO_CV_Dx_Framingham" "Fuma"                   
## [27] "Consume_alcohol"         "HTA"                    
## [29] "TX_HTA"                  "Diabetes_Mellitus"      
## [31] "Dislipidemia"            "Tratamiento_Lipemiante" 
## [33] "IL-6"                    "ApoE"                   
## [35] "Riesgo_ApoE"
data <- as.data.frame(data)

data <- data %>%
  mutate(
    Grupos_de_estudio = dplyr::recode(GRUPO, `0` = "Control", `1` = "DM2", `2` = "ND"),
    Disfunción_renal = dplyr::recode(DISFUNCIÓN_RENAL, `0` = "Sin disfunción renal", `1` = "Con disfunción renal"),
    Sexo = dplyr::recode(Sexo, `0` = "Hombre", `1` = "Mujer"),
    Consumo_de_alcohol = dplyr::recode(Consume_alcohol, `0` = "No", `1` = "Sí"),
    Dislipidemia = dplyr::recode(Dislipidemia, `0` = "No", `1` = "Sí"),
    Hipertensión = dplyr::recode(HTA, `0` = "No", `1` = "Sí"),
    Diabetes_mellitus = dplyr::recode(Diabetes_Mellitus, `0` = "No", `1` = "Sí"),
    Tratamiento_antihipertensivo = dplyr::recode(TX_HTA, `0` = "No", `1` = "Sí"),
    Tratamiento_antilipemiante = dplyr::recode(Tratamiento_Lipemiante, `0` = "No", `1` = "Sí"),
    Fuma = dplyr::recode(Fuma, `0`= "No", `1` = "Sí"),
    Edad = as.numeric(Edad)  # Crear o convertir Age a numérico
  )
class(data)
## [1] "data.frame"
view(data)
str(data)
## 'data.frame':    323 obs. of  42 variables:
##  $ Registro                    : chr  "MIDE001" "MIDE002" "MIDE006" "MIDE009" ...
##  $ Nombre                      : chr  "OSUNA GONZÁLEZ LAURA ALICIA" "CASTILLO GONZÁLEZ MARTHA ALICIA" "SÁNCHEZ MORALES JAVIER" "AYÓN ALVARADO JOSÉ LUIS" ...
##  $ GRUPO                       : num  2 2 2 1 2 1 1 2 2 1 ...
##  $ Sexo                        : chr  "F" "F" "M" "M" ...
##  $ Edad                        : num  65 57 68 62 62 59 66 68 71 76 ...
##  $ Peso                        : num  94.2 84.5 82.3 88.8 65.4 89.7 75.4 98.2 54.7 55.2 ...
##  $ Talla                       : num  1.59 1.62 1.6 1.67 1.68 1.67 1.52 1.63 1.59 1.63 ...
##  $ IMC                         : num  37.3 32.2 32.1 31.8 23.2 ...
##  $ Cintura                     : num  113 105 109 103 87 ...
##  $ Cadera                      : num  123 115 107 100 94 ...
##  $ ICC                         : num  0.919 0.913 1.019 1.025 0.926 ...
##  $ Glucosa                     : num  118.5 188 94.8 115.1 134.4 ...
##  $ HBA1c                       : num  9.1 7.9 5.7 7.4 5.8 9.5 8 7.9 6.5 8.1 ...
##  $ Colesterol_total            : num  158 129 912 237 220 ...
##  $ VLDL                        : num  26.7 29.5 15.9 35.1 18 ...
##  $ LDL                         : chr  "94.23" "77.540000000000006" "863.52" "205.39" ...
##  $ HDL                         : num  36.7 22.4 32.3 24.8 24.9 ...
##  $ Trigliceridos               : num  133.5 147.4 79.6 171.8 90.2 ...
##  $ Creatinina                  : num  1.2 1.2 2.5 1.2 1.5 1 0.9 1.2 1.4 0.8 ...
##  $ Urea                        : num  70.9 28.7 143.2 46.7 62.1 ...
##  $ BUN                         : num  33.1 13.4 66.9 21.8 29 ...
##  $ TFGe                        : num  47.4 50.1 25.4 64 49.2 61.6 66.6 46.4 37.7 86.8 ...
##  $ DISFUNCIÓN_RENAL            : num  1 1 1 0 1 0 0 1 1 0 ...
##  $ RIESGO_CARDIO-VASCULAR      : chr  "21.5" "10" "30" "24.8" ...
##  $ RIESGO_CV_Dx_Framingham     : chr  "ALTO" "MODERADO" "ALTO" "ALTO" ...
##  $ Fuma                        : chr  "No" "No" "No" "No" ...
##  $ Consume_alcohol             : num  0 0 0 0 0 0 1 1 1 0 ...
##  $ HTA                         : num  1 1 1 0 1 1 1 1 1 1 ...
##  $ TX_HTA                      : num  1 1 1 0 0 1 1 0 1 0 ...
##  $ Diabetes_Mellitus           : num  1 1 1 1 1 1 1 1 1 1 ...
##  $ Dislipidemia                : chr  "No" "No" "Sí" "No" ...
##  $ Tratamiento_Lipemiante      : num  0 0 0 0 0 0 0 0 0 0 ...
##  $ IL-6                        : chr  "G/G" "G/G" "G/G" "G/C" ...
##  $ ApoE                        : chr  "E3/E3" "E3/E4" "E3/E3" "E3/E4" ...
##  $ Riesgo_ApoE                 : num  0 2 0 2 3 0 0 2 0 0 ...
##  $ Grupos_de_estudio           : chr  "ND" "ND" "ND" "DM2" ...
##  $ Disfunción_renal            : chr  "Con disfunción renal" "Con disfunción renal" "Con disfunción renal" "Sin disfunción renal" ...
##  $ Consumo_de_alcohol          : chr  "No" "No" "No" "No" ...
##  $ Hipertensión                : chr  "Sí" "Sí" "Sí" "No" ...
##  $ Diabetes_mellitus           : chr  "Sí" "Sí" "Sí" "Sí" ...
##  $ Tratamiento_antihipertensivo: chr  "Sí" "Sí" "Sí" "No" ...
##  $ Tratamiento_antilipemiante  : chr  "No" "No" "No" "No" ...
data <- as.data.frame(data)

selected_data <- data %>%
  dplyr::select(
    Grupos_de_estudio, Sexo, Edad, Disfunción_renal, Fuma, Consumo_de_alcohol, Hipertensión, Diabetes_mellitus, Dislipidemia, Tratamiento_antihipertensivo, Tratamiento_antilipemiante
  )
summary_table <- selected_data %>%
  tbl_summary(
    by = Grupos_de_estudio,  
    missing = "no",  
    type = list(       
      Edad ~ "continuous",        
      Sexo ~ "categorical", 
      Disfunción_renal ~ "categorical",
      Fuma ~ "categorical",
      Consumo_de_alcohol ~ "categorical",
      Hipertensión ~ "categorical",
      Diabetes_mellitus ~ "categorical",
      Dislipidemia ~ "categorical",
      Tratamiento_antihipertensivo ~ "categorical",
      Tratamiento_antilipemiante ~ "categorical"
    ),
    statistic = list(    
      Edad ~ "{median} ({p25} - {p75})",  
      all_categorical() ~ "{n} ({p}%)"  
    )
  ) %>%
  add_overall() %>%  
  add_p( 
    test = list(
      Edad ~ "kruskal.test",  # Prueba de Kruskal-Wallis para Edad
      all_categorical() ~ "chisq.test"  # Prueba de Chi-cuadrado para variables categóricas
    ),
    test.args = list(
      all_categorical() ~ list(simulate.p.value = TRUE)  # Activar simulación para Chi-cuadrado
    )
  ) %>%
  modify_header(label = "**Variable**") %>%  
  modify_caption("**Table 1. Características sociodemográficas y estilo de vida en la población de estudio**") %>%
  as_gt() %>%  
  gt::tab_style(
    style = gt::cell_text(weight = "bold"),
    locations = gt::cells_column_labels()
  )

summary_table
Table 1. Características sociodemográficas y estilo de vida en la población de estudio
Variable Overall
N = 323
1
Control
N = 69
1
DM2
N = 201
1
ND
N = 53
1
p-value2
Sexo



0.001
    F 204 (63%) 49 (71%) 133 (66%) 22 (42%)
    M 119 (37%) 20 (29%) 68 (34%) 31 (58%)
Edad 60 (52 - 66) 59 (46 - 65) 60 (52 - 66) 63 (60 - 68) <0.001
Disfunción_renal



<0.001
    Con disfunción renal 53 (16%) 0 (0%) 0 (0%) 53 (100%)
    Sin disfunción renal 270 (84%) 69 (100%) 201 (100%) 0 (0%)
Fuma



0.054
    No 295 (91%) 68 (99%) 180 (90%) 47 (89%)
    Sí 28 (8.7%) 1 (1.4%) 21 (10%) 6 (11%)
Consumo_de_alcohol



0.022
    No 196 (61%) 35 (51%) 121 (60%) 40 (75%)
    Sí 127 (39%) 34 (49%) 80 (40%) 13 (25%)
Hipertensión



<0.001
    No 153 (47%) 50 (72%) 90 (45%) 13 (25%)
    Sí 170 (53%) 19 (28%) 111 (55%) 40 (75%)
Diabetes_mellitus



<0.001
    No 76 (24%) 69 (100%) 7 (3.5%) 0 (0%)
    Sí 247 (76%) 0 (0%) 194 (97%) 53 (100%)
Dislipidemia



>0.9
    No 215 (67%) 46 (67%) 134 (67%) 35 (66%)
    Sí 108 (33%) 23 (33%) 67 (33%) 18 (34%)
Tratamiento_antihipertensivo



<0.001
    No 184 (57%) 51 (74%) 114 (57%) 19 (36%)
    Sí 139 (43%) 18 (26%) 87 (43%) 34 (64%)
Tratamiento_antilipemiante



0.4
    No 267 (83%) 56 (81%) 170 (85%) 41 (77%)
    Sí 56 (17%) 13 (19%) 31 (15%) 12 (23%)
1 n (%); Median (Q1 - Q3)
2 Pearson’s Chi-squared test with simulated p-value (based on 2000 replicates); Kruskal-Wallis rank sum test
selected_data <- data %>%
  mutate(
    Peso = as.numeric(Peso),
    IMC = as.numeric(IMC),
    Cintura = as.numeric(Cintura),
    Cadera = as.numeric(Cadera),
    ICC = as.numeric(ICC),
    Glucosa = as.numeric(Glucosa),
    HBA1c = as.numeric(HBA1c),
    Colesterol_total = as.numeric(Colesterol_total),
    VLDL = as.numeric(VLDL),
    LDL = as.numeric(LDL),
    HDL = as.numeric(HDL),
    Trigliceridos = as.numeric(Trigliceridos),
    Creatinina = as.numeric(Creatinina),
    Urea = as.numeric(Urea),
    BUN = as.numeric(BUN),
    TFGe = as.numeric(TFGe)
  ) %>%
  dplyr::select(Peso, IMC, Cintura, Cadera, ICC, Glucosa, HBA1c, Colesterol_total, VLDL, LDL, HDL, Trigliceridos,   Creatinina, Urea, BUN, TFGe,  Grupos_de_estudio)
## Warning: There was 1 warning in `mutate()`.
## ℹ In argument: `LDL = as.numeric(LDL)`.
## Caused by warning:
## ! NAs introduced by coercion
# 1. Análisis de normalidad
# Prueba de Shapiro-Wilk para cada variable dentro de los grupos
normality_tests <- selected_data %>%
  group_by(Grupos_de_estudio) %>%
  summarise(
    Peso_p = shapiro.test(Peso)$p.value,
    IMC_p = shapiro.test(IMC)$p.value,
    Cintura_p = shapiro.test(Cintura)$p.value,
    Cadera_p = shapiro.test(Cadera)$p.value,
    ICC_p = shapiro.test(ICC)$p.value,
    Glucosa_p = shapiro.test(Glucosa)$p.value,
    HBA1c_p = shapiro.test(HBA1c)$p.value,
    Colesterol_total_p = shapiro.test(Colesterol_total)$p.value,
    VLDL_p = shapiro.test(VLDL)$p.value,
    LDL_p = shapiro.test(LDL)$p.value,
    HDL_p = shapiro.test(HDL)$p.value,
    Trigliceridos_p = shapiro.test(Trigliceridos)$p.value,
    Creatinina_p = shapiro.test(Creatinina)$p.value,
    Urea_p = shapiro.test(Urea)$p.value,
    BUN_p = shapiro.test(BUN)$p.value,
    TFGe_p = shapiro.test(TFGe)$p.value,
    .groups = "drop"
  )

print(normality_tests)
## # A tibble: 3 × 17
##   Grupos_de_estudio  Peso_p   IMC_p Cintura_p Cadera_p   ICC_p Glucosa_p HBA1c_p
##   <chr>               <dbl>   <dbl>     <dbl>    <dbl>   <dbl>     <dbl>   <dbl>
## 1 Control           4.37e-1 0.186       0.196  0.705   0.704    1.48e- 6 4.62e-7
## 2 DM2               5.85e-4 0.00347     0.544  0.00119 0.00193  4.23e-13 1.04e-8
## 3 ND                3.48e-1 0.993       0.541  0.187   0.608    1.65e- 3 7.58e-1
## # ℹ 9 more variables: Colesterol_total_p <dbl>, VLDL_p <dbl>, LDL_p <dbl>,
## #   HDL_p <dbl>, Trigliceridos_p <dbl>, Creatinina_p <dbl>, Urea_p <dbl>,
## #   BUN_p <dbl>, TFGe_p <dbl>
# 2. Análisis de homocedasticidad
# Prueba de Levene para cada variable 
library(car) 
## Loading required package: carData
## Registered S3 methods overwritten by 'car':
##   method       from
##   hist.boot    FSA 
##   confint.boot FSA
homocedasticity_tests <- list(
  Peso = leveneTest(Peso ~ Grupos_de_estudio, data = selected_data)$`Pr(>F)`[1],
  IMC = leveneTest(IMC ~ Grupos_de_estudio, data = selected_data)$`Pr(>F)`[1],
  Cintura = leveneTest(Cintura ~ Grupos_de_estudio, data = selected_data)$`Pr(>F)`[1],
  Cadera = leveneTest(Cadera ~ Grupos_de_estudio, data = selected_data)$`Pr(>F)`[1],
  ICC = leveneTest(ICC ~ Grupos_de_estudio, data = selected_data)$`Pr(>F)`[1],
  Glucosa = leveneTest(Glucosa ~ Grupos_de_estudio, data = selected_data)$`Pr(>F)`[1],
  HBA1c = leveneTest(HBA1c ~ Grupos_de_estudio, data = selected_data)$`Pr(>F)`[1],
  Colesterol_total = leveneTest(Colesterol_total ~ Grupos_de_estudio, data = selected_data)$`Pr(>F)`[1],
  VLDL = leveneTest(VLDL ~ Grupos_de_estudio, data = selected_data)$`Pr(>F)`[1],
  LDL = leveneTest(LDL ~ Grupos_de_estudio, data = selected_data)$`Pr(>F)`[1],
  HDL = leveneTest(HDL ~ Grupos_de_estudio, data = selected_data)$`Pr(>F)`[1],
  Trigliceridos = leveneTest(Trigliceridos ~ Grupos_de_estudio, data = selected_data)$`Pr(>F)`[1],
  Creatinina = leveneTest(Creatinina ~ Grupos_de_estudio, data = selected_data)$`Pr(>F)`[1],
  Urea = leveneTest(Urea ~ Grupos_de_estudio, data = selected_data)$`Pr(>F)`[1],
  BUN = leveneTest(BUN ~ Grupos_de_estudio, data = selected_data)$`Pr(>F)`[1],
  TFGe = leveneTest(TFGe ~ Grupos_de_estudio, data = selected_data)$`Pr(>F)`[1]
)
## Warning in leveneTest.default(y = y, group = group, ...): group coerced to
## factor.
## Warning in leveneTest.default(y = y, group = group, ...): group coerced to
## factor.
## Warning in leveneTest.default(y = y, group = group, ...): group coerced to
## factor.
## Warning in leveneTest.default(y = y, group = group, ...): group coerced to
## factor.
## Warning in leveneTest.default(y = y, group = group, ...): group coerced to
## factor.
## Warning in leveneTest.default(y = y, group = group, ...): group coerced to
## factor.
## Warning in leveneTest.default(y = y, group = group, ...): group coerced to
## factor.
## Warning in leveneTest.default(y = y, group = group, ...): group coerced to
## factor.
## Warning in leveneTest.default(y = y, group = group, ...): group coerced to
## factor.
## Warning in leveneTest.default(y = y, group = group, ...): group coerced to
## factor.
## Warning in leveneTest.default(y = y, group = group, ...): group coerced to
## factor.
## Warning in leveneTest.default(y = y, group = group, ...): group coerced to
## factor.
## Warning in leveneTest.default(y = y, group = group, ...): group coerced to
## factor.
## Warning in leveneTest.default(y = y, group = group, ...): group coerced to
## factor.
## Warning in leveneTest.default(y = y, group = group, ...): group coerced to
## factor.
## Warning in leveneTest.default(y = y, group = group, ...): group coerced to
## factor.
homocedasticity_results <- data.frame(
  Variable = names(homocedasticity_tests),
  p_value = unlist(homocedasticity_tests)
)

print(homocedasticity_results)
##                          Variable      p_value
## Peso                         Peso 3.401467e-01
## IMC                           IMC 2.148653e-02
## Cintura                   Cintura 9.938146e-01
## Cadera                     Cadera 1.435644e-02
## ICC                           ICC 4.443850e-01
## Glucosa                   Glucosa 7.311333e-12
## HBA1c                       HBA1c 1.525227e-06
## Colesterol_total Colesterol_total 1.314301e-01
## VLDL                         VLDL 7.158737e-01
## LDL                           LDL 1.105762e-01
## HDL                           HDL 4.171676e-02
## Trigliceridos       Trigliceridos 8.390450e-01
## Creatinina             Creatinina 2.848371e-31
## Urea                         Urea 1.831490e-36
## BUN                           BUN 5.296303e-24
## TFGe                         TFGe 1.033284e-12
### Casi todas las variables son no parametricas a excepción de peso, cintura y HDL. 
selected_data <- data %>%
  mutate(
    IMC = as.numeric(IMC),
    Cadera = as.numeric(Cadera),
    ICC = as.numeric(ICC),
    Grupos_de_estudio = as.factor(Grupos_de_estudio) 
  ) %>%
  dplyr::select(IMC, Cadera, ICC, Grupos_de_estudio)

# 2. Crear la tabla de resumen con Kruskal-Wallis
summary_table <- selected_data %>%
  tbl_summary(
    by = Grupos_de_estudio, 
    missing = "no", 
    type = all_continuous() ~ "continuous", 
    statistic = all_continuous() ~ "{median} ({p25}, {p75})"
  ) %>%
  add_overall() %>% 
  add_p(
    test = all_continuous() ~ "kruskal.test", 
    pvalue_fun = function(x) style_pvalue(x, digits = 3)
  ) %>%
  modify_header(label = "**Variable**") %>%
  as_gt() %>%
  gt::tab_header(
    title = gt::md("**Tabla 2. Parámetros antropométricos**")
  )

# Mostrar la tabla
print(summary_table)
## <div id="cmytocarud" style="padding-left:0px;padding-right:0px;padding-top:10px;padding-bottom:10px;overflow-x:auto;overflow-y:auto;width:auto;height:auto;">
##   <style>#cmytocarud table {
##   font-family: system-ui, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
##   -webkit-font-smoothing: antialiased;
##   -moz-osx-font-smoothing: grayscale;
## }
## 
## #cmytocarud thead, #cmytocarud tbody, #cmytocarud tfoot, #cmytocarud tr, #cmytocarud td, #cmytocarud th {
##   border-style: none;
## }
## 
## #cmytocarud p {
##   margin: 0;
##   padding: 0;
## }
## 
## #cmytocarud .gt_table {
##   display: table;
##   border-collapse: collapse;
##   line-height: normal;
##   margin-left: auto;
##   margin-right: auto;
##   color: #333333;
##   font-size: 16px;
##   font-weight: normal;
##   font-style: normal;
##   background-color: #FFFFFF;
##   width: auto;
##   border-top-style: solid;
##   border-top-width: 2px;
##   border-top-color: #A8A8A8;
##   border-right-style: none;
##   border-right-width: 2px;
##   border-right-color: #D3D3D3;
##   border-bottom-style: solid;
##   border-bottom-width: 2px;
##   border-bottom-color: #A8A8A8;
##   border-left-style: none;
##   border-left-width: 2px;
##   border-left-color: #D3D3D3;
## }
## 
## #cmytocarud .gt_caption {
##   padding-top: 4px;
##   padding-bottom: 4px;
## }
## 
## #cmytocarud .gt_title {
##   color: #333333;
##   font-size: 125%;
##   font-weight: initial;
##   padding-top: 4px;
##   padding-bottom: 4px;
##   padding-left: 5px;
##   padding-right: 5px;
##   border-bottom-color: #FFFFFF;
##   border-bottom-width: 0;
## }
## 
## #cmytocarud .gt_subtitle {
##   color: #333333;
##   font-size: 85%;
##   font-weight: initial;
##   padding-top: 3px;
##   padding-bottom: 5px;
##   padding-left: 5px;
##   padding-right: 5px;
##   border-top-color: #FFFFFF;
##   border-top-width: 0;
## }
## 
## #cmytocarud .gt_heading {
##   background-color: #FFFFFF;
##   text-align: center;
##   border-bottom-color: #FFFFFF;
##   border-left-style: none;
##   border-left-width: 1px;
##   border-left-color: #D3D3D3;
##   border-right-style: none;
##   border-right-width: 1px;
##   border-right-color: #D3D3D3;
## }
## 
## #cmytocarud .gt_bottom_border {
##   border-bottom-style: solid;
##   border-bottom-width: 2px;
##   border-bottom-color: #D3D3D3;
## }
## 
## #cmytocarud .gt_col_headings {
##   border-top-style: solid;
##   border-top-width: 2px;
##   border-top-color: #D3D3D3;
##   border-bottom-style: solid;
##   border-bottom-width: 2px;
##   border-bottom-color: #D3D3D3;
##   border-left-style: none;
##   border-left-width: 1px;
##   border-left-color: #D3D3D3;
##   border-right-style: none;
##   border-right-width: 1px;
##   border-right-color: #D3D3D3;
## }
## 
## #cmytocarud .gt_col_heading {
##   color: #333333;
##   background-color: #FFFFFF;
##   font-size: 100%;
##   font-weight: normal;
##   text-transform: inherit;
##   border-left-style: none;
##   border-left-width: 1px;
##   border-left-color: #D3D3D3;
##   border-right-style: none;
##   border-right-width: 1px;
##   border-right-color: #D3D3D3;
##   vertical-align: bottom;
##   padding-top: 5px;
##   padding-bottom: 6px;
##   padding-left: 5px;
##   padding-right: 5px;
##   overflow-x: hidden;
## }
## 
## #cmytocarud .gt_column_spanner_outer {
##   color: #333333;
##   background-color: #FFFFFF;
##   font-size: 100%;
##   font-weight: normal;
##   text-transform: inherit;
##   padding-top: 0;
##   padding-bottom: 0;
##   padding-left: 4px;
##   padding-right: 4px;
## }
## 
## #cmytocarud .gt_column_spanner_outer:first-child {
##   padding-left: 0;
## }
## 
## #cmytocarud .gt_column_spanner_outer:last-child {
##   padding-right: 0;
## }
## 
## #cmytocarud .gt_column_spanner {
##   border-bottom-style: solid;
##   border-bottom-width: 2px;
##   border-bottom-color: #D3D3D3;
##   vertical-align: bottom;
##   padding-top: 5px;
##   padding-bottom: 5px;
##   overflow-x: hidden;
##   display: inline-block;
##   width: 100%;
## }
## 
## #cmytocarud .gt_spanner_row {
##   border-bottom-style: hidden;
## }
## 
## #cmytocarud .gt_group_heading {
##   padding-top: 8px;
##   padding-bottom: 8px;
##   padding-left: 5px;
##   padding-right: 5px;
##   color: #333333;
##   background-color: #FFFFFF;
##   font-size: 100%;
##   font-weight: initial;
##   text-transform: inherit;
##   border-top-style: solid;
##   border-top-width: 2px;
##   border-top-color: #D3D3D3;
##   border-bottom-style: solid;
##   border-bottom-width: 2px;
##   border-bottom-color: #D3D3D3;
##   border-left-style: none;
##   border-left-width: 1px;
##   border-left-color: #D3D3D3;
##   border-right-style: none;
##   border-right-width: 1px;
##   border-right-color: #D3D3D3;
##   vertical-align: middle;
##   text-align: left;
## }
## 
## #cmytocarud .gt_empty_group_heading {
##   padding: 0.5px;
##   color: #333333;
##   background-color: #FFFFFF;
##   font-size: 100%;
##   font-weight: initial;
##   border-top-style: solid;
##   border-top-width: 2px;
##   border-top-color: #D3D3D3;
##   border-bottom-style: solid;
##   border-bottom-width: 2px;
##   border-bottom-color: #D3D3D3;
##   vertical-align: middle;
## }
## 
## #cmytocarud .gt_from_md > :first-child {
##   margin-top: 0;
## }
## 
## #cmytocarud .gt_from_md > :last-child {
##   margin-bottom: 0;
## }
## 
## #cmytocarud .gt_row {
##   padding-top: 8px;
##   padding-bottom: 8px;
##   padding-left: 5px;
##   padding-right: 5px;
##   margin: 10px;
##   border-top-style: solid;
##   border-top-width: 1px;
##   border-top-color: #D3D3D3;
##   border-left-style: none;
##   border-left-width: 1px;
##   border-left-color: #D3D3D3;
##   border-right-style: none;
##   border-right-width: 1px;
##   border-right-color: #D3D3D3;
##   vertical-align: middle;
##   overflow-x: hidden;
## }
## 
## #cmytocarud .gt_stub {
##   color: #333333;
##   background-color: #FFFFFF;
##   font-size: 100%;
##   font-weight: initial;
##   text-transform: inherit;
##   border-right-style: solid;
##   border-right-width: 2px;
##   border-right-color: #D3D3D3;
##   padding-left: 5px;
##   padding-right: 5px;
## }
## 
## #cmytocarud .gt_stub_row_group {
##   color: #333333;
##   background-color: #FFFFFF;
##   font-size: 100%;
##   font-weight: initial;
##   text-transform: inherit;
##   border-right-style: solid;
##   border-right-width: 2px;
##   border-right-color: #D3D3D3;
##   padding-left: 5px;
##   padding-right: 5px;
##   vertical-align: top;
## }
## 
## #cmytocarud .gt_row_group_first td {
##   border-top-width: 2px;
## }
## 
## #cmytocarud .gt_row_group_first th {
##   border-top-width: 2px;
## }
## 
## #cmytocarud .gt_summary_row {
##   color: #333333;
##   background-color: #FFFFFF;
##   text-transform: inherit;
##   padding-top: 8px;
##   padding-bottom: 8px;
##   padding-left: 5px;
##   padding-right: 5px;
## }
## 
## #cmytocarud .gt_first_summary_row {
##   border-top-style: solid;
##   border-top-color: #D3D3D3;
## }
## 
## #cmytocarud .gt_first_summary_row.thick {
##   border-top-width: 2px;
## }
## 
## #cmytocarud .gt_last_summary_row {
##   padding-top: 8px;
##   padding-bottom: 8px;
##   padding-left: 5px;
##   padding-right: 5px;
##   border-bottom-style: solid;
##   border-bottom-width: 2px;
##   border-bottom-color: #D3D3D3;
## }
## 
## #cmytocarud .gt_grand_summary_row {
##   color: #333333;
##   background-color: #FFFFFF;
##   text-transform: inherit;
##   padding-top: 8px;
##   padding-bottom: 8px;
##   padding-left: 5px;
##   padding-right: 5px;
## }
## 
## #cmytocarud .gt_first_grand_summary_row {
##   padding-top: 8px;
##   padding-bottom: 8px;
##   padding-left: 5px;
##   padding-right: 5px;
##   border-top-style: double;
##   border-top-width: 6px;
##   border-top-color: #D3D3D3;
## }
## 
## #cmytocarud .gt_last_grand_summary_row_top {
##   padding-top: 8px;
##   padding-bottom: 8px;
##   padding-left: 5px;
##   padding-right: 5px;
##   border-bottom-style: double;
##   border-bottom-width: 6px;
##   border-bottom-color: #D3D3D3;
## }
## 
## #cmytocarud .gt_striped {
##   background-color: rgba(128, 128, 128, 0.05);
## }
## 
## #cmytocarud .gt_table_body {
##   border-top-style: solid;
##   border-top-width: 2px;
##   border-top-color: #D3D3D3;
##   border-bottom-style: solid;
##   border-bottom-width: 2px;
##   border-bottom-color: #D3D3D3;
## }
## 
## #cmytocarud .gt_footnotes {
##   color: #333333;
##   background-color: #FFFFFF;
##   border-bottom-style: none;
##   border-bottom-width: 2px;
##   border-bottom-color: #D3D3D3;
##   border-left-style: none;
##   border-left-width: 2px;
##   border-left-color: #D3D3D3;
##   border-right-style: none;
##   border-right-width: 2px;
##   border-right-color: #D3D3D3;
## }
## 
## #cmytocarud .gt_footnote {
##   margin: 0px;
##   font-size: 90%;
##   padding-top: 4px;
##   padding-bottom: 4px;
##   padding-left: 5px;
##   padding-right: 5px;
## }
## 
## #cmytocarud .gt_sourcenotes {
##   color: #333333;
##   background-color: #FFFFFF;
##   border-bottom-style: none;
##   border-bottom-width: 2px;
##   border-bottom-color: #D3D3D3;
##   border-left-style: none;
##   border-left-width: 2px;
##   border-left-color: #D3D3D3;
##   border-right-style: none;
##   border-right-width: 2px;
##   border-right-color: #D3D3D3;
## }
## 
## #cmytocarud .gt_sourcenote {
##   font-size: 90%;
##   padding-top: 4px;
##   padding-bottom: 4px;
##   padding-left: 5px;
##   padding-right: 5px;
## }
## 
## #cmytocarud .gt_left {
##   text-align: left;
## }
## 
## #cmytocarud .gt_center {
##   text-align: center;
## }
## 
## #cmytocarud .gt_right {
##   text-align: right;
##   font-variant-numeric: tabular-nums;
## }
## 
## #cmytocarud .gt_font_normal {
##   font-weight: normal;
## }
## 
## #cmytocarud .gt_font_bold {
##   font-weight: bold;
## }
## 
## #cmytocarud .gt_font_italic {
##   font-style: italic;
## }
## 
## #cmytocarud .gt_super {
##   font-size: 65%;
## }
## 
## #cmytocarud .gt_footnote_marks {
##   font-size: 75%;
##   vertical-align: 0.4em;
##   position: initial;
## }
## 
## #cmytocarud .gt_asterisk {
##   font-size: 100%;
##   vertical-align: 0;
## }
## 
## #cmytocarud .gt_indent_1 {
##   text-indent: 5px;
## }
## 
## #cmytocarud .gt_indent_2 {
##   text-indent: 10px;
## }
## 
## #cmytocarud .gt_indent_3 {
##   text-indent: 15px;
## }
## 
## #cmytocarud .gt_indent_4 {
##   text-indent: 20px;
## }
## 
## #cmytocarud .gt_indent_5 {
##   text-indent: 25px;
## }
## 
## #cmytocarud .katex-display {
##   display: inline-flex !important;
##   margin-bottom: 0.75em !important;
## }
## 
## #cmytocarud div.Reactable > div.rt-table > div.rt-thead > div.rt-tr.rt-tr-group-header > div.rt-th-group:after {
##   height: 0px !important;
## }
## </style>
##   <table class="gt_table" data-quarto-disable-processing="false" data-quarto-bootstrap="false">
##   <thead>
##     <tr class="gt_heading">
##       <td colspan="6" class="gt_heading gt_title gt_font_normal gt_bottom_border" style><span class='gt_from_md'><strong>Tabla 2. Parámetros antropométricos</strong></span></td>
##     </tr>
##     
##     <tr class="gt_col_headings">
##       <th class="gt_col_heading gt_columns_bottom_border gt_left" rowspan="1" colspan="1" scope="col" id="label"><span class='gt_from_md'><strong>Variable</strong></span></th>
##       <th class="gt_col_heading gt_columns_bottom_border gt_center" rowspan="1" colspan="1" scope="col" id="stat_0"><span class='gt_from_md'><strong>Overall</strong><br />
## N = 323</span><span class="gt_footnote_marks" style="white-space:nowrap;font-style:italic;font-weight:normal;line-height:0;"><sup>1</sup></span></th>
##       <th class="gt_col_heading gt_columns_bottom_border gt_center" rowspan="1" colspan="1" scope="col" id="stat_1"><span class='gt_from_md'><strong>Control</strong><br />
## N = 69</span><span class="gt_footnote_marks" style="white-space:nowrap;font-style:italic;font-weight:normal;line-height:0;"><sup>1</sup></span></th>
##       <th class="gt_col_heading gt_columns_bottom_border gt_center" rowspan="1" colspan="1" scope="col" id="stat_2"><span class='gt_from_md'><strong>DM2</strong><br />
## N = 201</span><span class="gt_footnote_marks" style="white-space:nowrap;font-style:italic;font-weight:normal;line-height:0;"><sup>1</sup></span></th>
##       <th class="gt_col_heading gt_columns_bottom_border gt_center" rowspan="1" colspan="1" scope="col" id="stat_3"><span class='gt_from_md'><strong>ND</strong><br />
## N = 53</span><span class="gt_footnote_marks" style="white-space:nowrap;font-style:italic;font-weight:normal;line-height:0;"><sup>1</sup></span></th>
##       <th class="gt_col_heading gt_columns_bottom_border gt_center" rowspan="1" colspan="1" scope="col" id="p.value"><span class='gt_from_md'><strong>p-value</strong></span><span class="gt_footnote_marks" style="white-space:nowrap;font-style:italic;font-weight:normal;line-height:0;"><sup>2</sup></span></th>
##     </tr>
##   </thead>
##   <tbody class="gt_table_body">
##     <tr><td headers="label" class="gt_row gt_left">IMC</td>
## <td headers="stat_0" class="gt_row gt_center">29.8 (25.9, 33.7)</td>
## <td headers="stat_1" class="gt_row gt_center">27.6 (25.3, 31.3)</td>
## <td headers="stat_2" class="gt_row gt_center">30.4 (26.7, 34.9)</td>
## <td headers="stat_3" class="gt_row gt_center">29.2 (25.3, 32.2)</td>
## <td headers="p.value" class="gt_row gt_center">0.004</td></tr>
##     <tr><td headers="label" class="gt_row gt_left">Cadera</td>
## <td headers="stat_0" class="gt_row gt_center">105 (99, 111)</td>
## <td headers="stat_1" class="gt_row gt_center">106 (99, 111)</td>
## <td headers="stat_2" class="gt_row gt_center">106 (99, 113)</td>
## <td headers="stat_3" class="gt_row gt_center">102 (95, 108)</td>
## <td headers="p.value" class="gt_row gt_center">0.035</td></tr>
##     <tr><td headers="label" class="gt_row gt_left">ICC</td>
## <td headers="stat_0" class="gt_row gt_center">0.93 (0.87, 1.00)</td>
## <td headers="stat_1" class="gt_row gt_center">0.87 (0.79, 0.91)</td>
## <td headers="stat_2" class="gt_row gt_center">0.94 (0.89, 1.01)</td>
## <td headers="stat_3" class="gt_row gt_center">1.00 (0.92, 1.04)</td>
## <td headers="p.value" class="gt_row gt_center"><0.001</td></tr>
##   </tbody>
##   
##   <tfoot class="gt_footnotes">
##     <tr>
##       <td class="gt_footnote" colspan="6"><span class="gt_footnote_marks" style="white-space:nowrap;font-style:italic;font-weight:normal;line-height:0;"><sup>1</sup></span> <span class='gt_from_md'>Median (Q1, Q3)</span></td>
##     </tr>
##     <tr>
##       <td class="gt_footnote" colspan="6"><span class="gt_footnote_marks" style="white-space:nowrap;font-style:italic;font-weight:normal;line-height:0;"><sup>2</sup></span> <span class='gt_from_md'>Kruskal-Wallis rank sum test</span></td>
##     </tr>
##   </tfoot>
## </table>
## </div>
# 3. Realizar prueba post hoc 
dunnTest(IMC ~ Grupos_de_estudio, data = selected_data, method = "bonferroni")
## Dunn (1964) Kruskal-Wallis multiple comparison
##   p-values adjusted with the Bonferroni method.
##      Comparison          Z    P.unadj      P.adj
## 1 Control - DM2 -3.1703813 0.00152239 0.00456717
## 2  Control - ND -0.8918574 0.37246937 1.00000000
## 3      DM2 - ND  1.8098208 0.07032358 0.21097073
dunnTest(Cadera ~ Grupos_de_estudio, data = selected_data, method = "bonferroni")
## Warning: Some rows deleted from 'x' and 'g' because missing data.
## Dunn (1964) Kruskal-Wallis multiple comparison
##   p-values adjusted with the Bonferroni method.
##      Comparison         Z     P.unadj      P.adj
## 1 Control - DM2 -0.386659 0.699008694 1.00000000
## 2  Control - ND  1.897204 0.057801025 0.17340308
## 3      DM2 - ND  2.584991 0.009738146 0.02921444
dunnTest(ICC ~ Grupos_de_estudio, data = selected_data, method = "bonferroni")
## Warning: Some rows deleted from 'x' and 'g' because missing data.
## Dunn (1964) Kruskal-Wallis multiple comparison
##   p-values adjusted with the Bonferroni method.
##      Comparison         Z      P.unadj        P.adj
## 1 Control - DM2 -6.160043 7.272536e-10 2.181761e-09
## 2  Control - ND -7.427849 1.103779e-13 3.311337e-13
## 3      DM2 - ND -3.237805 1.204532e-03 3.613596e-03
#install.packages(c("ggpubr", "cowplot"))
library(ggpubr)
library(cowplot)
library(ggplot2)
data <- data %>%
  mutate(
    Peso = as.numeric(Peso),
    Cintura = as.numeric(Cintura),
    HDL = as.numeric(HDL),
    Grupos_de_estudio = as.factor(Grupos_de_estudio) # Convertir en factor
  )

custom_colors <- c("Control" = "#1f77b4", "DM2" = "#ff7f0e", "ND" = "red")

theme_custom <- theme_pubr() + 
  theme(
    axis.title.x = element_blank(), 
    axis.text = element_text(size = 10), 
    legend.position = "none"
  )

create_boxplot_with_error <- function(data, variable, y_label, y_lim) {
  summary_stats <- data %>%
    group_by(Grupos_de_estudio) %>%
    summarise(
      mean = mean(!!sym(variable), na.rm = TRUE),
      sd = sd(!!sym(variable), na.rm = TRUE),
      .groups = "drop"
    )
  
  ggplot(data, aes(x = Grupos_de_estudio, y = !!sym(variable), fill = Grupos_de_estudio)) +
    geom_boxplot(outlier.shape = NA) +
    geom_jitter(width = 0.2, alpha = 0.5, color = "black") +
    stat_summary(fun = mean, geom = "point", shape = 18, size = 3, color = "black") +
    geom_errorbar(
      data = summary_stats,
      aes(x = Grupos_de_estudio, ymin = mean - sd, ymax = mean + sd),
      width = 0.2, inherit.aes = FALSE, color = "black"
    ) +
    labs(
      title = paste(variable, ""),
      y = y_label,
      fill = "Grupos"
    ) +
    scale_fill_manual(values = custom_colors) +
    ylim(0, y_lim) +
    theme_custom
}

peso_plot <- create_boxplot_with_error(data, "Peso", "Peso (kg)", 120)
cintura_plot <- create_boxplot_with_error(data, "Cintura", "Cintura (cm)", 150)
HDL_plot <- create_boxplot_with_error(data, "HDL", "HDL (mg/dL)", 150)

print(peso_plot)
## Warning: Removed 4 rows containing non-finite outside the scale range
## (`stat_boxplot()`).
## Warning: Removed 4 rows containing non-finite outside the scale range
## (`stat_summary()`).
## Warning: Removed 4 rows containing missing values or values outside the scale range
## (`geom_point()`).

print(cintura_plot)
## Warning: Removed 2 rows containing non-finite outside the scale range
## (`stat_boxplot()`).
## Warning: Removed 2 rows containing non-finite outside the scale range
## (`stat_summary()`).
## Warning: Removed 2 rows containing missing values or values outside the scale range
## (`geom_point()`).

print(HDL_plot)

run_anova_tukey <- function(data, variable) {
  formula <- as.formula(paste(variable, "~ Grupos_de_estudio"))
  anova_result <- aov(formula, data = data)
  print(summary(anova_result)) 
  
  tukey_result <- TukeyHSD(anova_result)
  print(tukey_result)
}

run_anova_tukey(data, "Peso")
##                    Df Sum Sq Mean Sq F value Pr(>F)  
## Grupos_de_estudio   2   2487  1243.4    4.64 0.0103 *
## Residuals         320  85743   267.9                 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##   Tukey multiple comparisons of means
##     95% family-wise confidence level
## 
## Fit: aov(formula = formula, data = data)
## 
## $Grupos_de_estudio
##                  diff       lwr       upr     p adj
## DM2-Control  6.669100  1.291175 12.047025 0.0104482
## ND-Control   2.828698 -4.211305  9.868702 0.6115058
## ND-DM2      -3.840402 -9.792037  2.111234 0.2831524
run_anova_tukey(data, "Cintura")
##                    Df Sum Sq Mean Sq F value   Pr(>F)    
## Grupos_de_estudio   2   5865  2932.7   16.92 1.04e-07 ***
## Residuals         318  55105   173.3                     
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 2 observations deleted due to missingness
##   Tukey multiple comparisons of means
##     95% family-wise confidence level
## 
## Fit: aov(formula = formula, data = data)
## 
## $Grupos_de_estudio
##                   diff       lwr       upr     p adj
## DM2-Control 10.2644493  5.936693 14.592206 0.0000002
## ND-Control  10.8822185  5.189854 16.574583 0.0000282
## ND-DM2       0.6177692 -4.207370  5.442908 0.9511409
run_anova_tukey(data, "HDL")
##                    Df Sum Sq Mean Sq F value Pr(>F)
## Grupos_de_estudio   2    923   461.7   2.314    0.1
## Residuals         320  63843   199.5               
##   Tukey multiple comparisons of means
##     95% family-wise confidence level
## 
## Fit: aov(formula = formula, data = data)
## 
## $Grupos_de_estudio
##                   diff        lwr      upr     p adj
## DM2-Control -4.0770798  -8.717659 0.563499 0.0980206
## ND-Control  -4.2887066 -10.363483 1.786070 0.2213772
## ND-DM2      -0.2116268  -5.347257 4.924003 0.9948229
selected_data <- data %>%
  mutate(
    Glucosa = as.numeric(Glucosa),
    HBA1c = as.numeric(HBA1c),
    Colesterol_total = as.numeric(Colesterol_total),
    VLDL = as.numeric(VLDL),
    LDL = as.numeric(LDL),
    HDL = as.numeric(HDL),
    Trigliceridos = as.numeric(Trigliceridos),
    Creatinina = as.numeric(Creatinina),
    Urea = as.numeric(Urea),
    BUN = as.numeric(BUN),
    TFGe = as.numeric(TFGe),
    Grupos_de_estudio = as.factor(Grupos_de_estudio) 
  ) %>%
  dplyr::select(Glucosa, HBA1c, Colesterol_total, VLDL, LDL, HDL, Trigliceridos, Creatinina, Urea, BUN, TFGe, Grupos_de_estudio
  )
## Warning: There was 1 warning in `mutate()`.
## ℹ In argument: `LDL = as.numeric(LDL)`.
## Caused by warning:
## ! NAs introduced by coercion
summary_table <- selected_data %>%
  tbl_summary(
    by = Grupos_de_estudio, 
    missing = "no", 
    type = all_continuous() ~ "continuous", 
    statistic = all_continuous() ~ "{median} ({p25}, {p75})"
  ) %>%
  add_overall() %>% 
  add_p(
    test = all_continuous() ~ "kruskal.test", 
    pvalue_fun = function(x) style_pvalue(x, digits = 3)
  ) %>%
  modify_header(label = "**Variable**") %>%
  as_gt() %>%
  gt::tab_header(
    title = gt::md("**Tabla 3. Parámetros bioquímicos**")
  )

summary_table
Tabla 3. Parámetros bioquímicos
Variable Overall
N = 323
1
Control
N = 69
1
DM2
N = 201
1
ND
N = 53
1
p-value2
Glucosa 125 (94, 185) 88 (83, 94) 154 (110, 216) 140 (102, 188) <0.001
HBA1c 6.90 (5.90, 8.20) 5.70 (5.20, 6.10) 7.40 (6.50, 8.90) 7.01 (5.82, 7.90) <0.001
Colesterol_total 186 (151, 222) 185 (162, 214) 190 (159, 226) 151 (124, 204) 0.006
VLDL 28 (19, 35) 23 (17, 33) 30 (20, 36) 26 (17, 36) 0.021
LDL 111 (83, 152) 118 (96, 147) 115 (85, 156) 88 (60, 130) 0.011
HDL 41 (31, 51) 45 (38, 52) 40 (30, 50) 36 (31, 51) 0.024
Trigliceridos 140 (93, 178) 114 (84, 163) 148 (99, 181) 130 (85, 181) 0.020
Creatinina 0.70 (0.60, 0.90) 0.70 (0.60, 0.70) 0.70 (0.60, 0.80) 1.77 (1.20, 5.81) <0.001
Urea 34 (26, 48) 28 (24, 33) 34 (26, 45) 83 (50, 134) <0.001
BUN 16 (12, 23) 13 (11, 15) 16 (13, 21) 39 (23, 63) <0.001
TFGe 95 (74, 104) 99 (94, 106) 98 (86, 105) 38 (7, 54) <0.001
1 Median (Q1, Q3)
2 Kruskal-Wallis rank sum test
dunnTest(Glucosa ~ Grupos_de_estudio, data = selected_data, method = "bonferroni")
## Dunn (1964) Kruskal-Wallis multiple comparison
##   p-values adjusted with the Bonferroni method.
##      Comparison          Z      P.unadj        P.adj
## 1 Control - DM2 -10.225649 1.522055e-24 4.566166e-24
## 2  Control - ND  -6.783889 1.169828e-11 3.509485e-11
## 3      DM2 - ND   1.215492 2.241784e-01 6.725353e-01
dunnTest(HBA1c ~ Grupos_de_estudio, data = selected_data, method = "bonferroni")
## Warning: Some rows deleted from 'x' and 'g' because missing data.
## Dunn (1964) Kruskal-Wallis multiple comparison
##   p-values adjusted with the Bonferroni method.
##      Comparison         Z      P.unadj        P.adj
## 1 Control - DM2 -9.362907 7.757228e-21 2.327168e-20
## 2  Control - ND -4.908771 9.164878e-07 2.749463e-06
## 3      DM2 - ND  2.602713 9.248929e-03 2.774679e-02
dunnTest(Colesterol_total ~ Grupos_de_estudio, data = selected_data, method = "bonferroni")
## Dunn (1964) Kruskal-Wallis multiple comparison
##   p-values adjusted with the Bonferroni method.
##      Comparison          Z     P.unadj      P.adj
## 1 Control - DM2 -0.4315202 0.666090202 1.00000000
## 2  Control - ND  2.3608790 0.018231680 0.05469504
## 3      DM2 - ND  3.1825334 0.001459927 0.00437978
dunnTest(VLDL ~ Grupos_de_estudio, data = selected_data, method = "bonferroni")
## Dunn (1964) Kruskal-Wallis multiple comparison
##   p-values adjusted with the Bonferroni method.
##      Comparison          Z    P.unadj      P.adj
## 1 Control - DM2 -2.4407374 0.01465731 0.04397192
## 2  Control - ND -0.2949572 0.76802657 1.00000000
## 3      DM2 - ND  1.8565658 0.06337295 0.19011885
dunnTest(LDL ~ Grupos_de_estudio, data = selected_data, method = "bonferroni")
## Warning: Some rows deleted from 'x' and 'g' because missing data.
## Dunn (1964) Kruskal-Wallis multiple comparison
##   p-values adjusted with the Bonferroni method.
##      Comparison         Z     P.unadj      P.adj
## 1 Control - DM2 0.2199792 0.825887366 1.00000000
## 2  Control - ND 2.5927483 0.009521242 0.02856373
## 3      DM2 - ND 2.8630372 0.004196013 0.01258804
dunnTest(HDL ~ Grupos_de_estudio, data = selected_data, method = "bonferroni")
## Dunn (1964) Kruskal-Wallis multiple comparison
##   p-values adjusted with the Bonferroni method.
##      Comparison         Z    P.unadj      P.adj
## 1 Control - DM2 2.5514810 0.01072662 0.03217985
## 2  Control - ND 2.2423563 0.02493835 0.07481506
## 3      DM2 - ND 0.3468832 0.72867903 1.00000000
dunnTest(Trigliceridos ~ Grupos_de_estudio, data = selected_data, method = "bonferroni")
## Dunn (1964) Kruskal-Wallis multiple comparison
##   p-values adjusted with the Bonferroni method.
##      Comparison          Z    P.unadj      P.adj
## 1 Control - DM2 -2.4433355 0.01455220 0.04365661
## 2  Control - ND -0.2693067 0.78769371 1.00000000
## 3      DM2 - ND  1.8892547 0.05885771 0.17657313
dunnTest(Creatinina ~ Grupos_de_estudio, data = selected_data, method = "bonferroni")
## Dunn (1964) Kruskal-Wallis multiple comparison
##   p-values adjusted with the Bonferroni method.
##      Comparison           Z      P.unadj        P.adj
## 1 Control - DM2  -0.7585522 4.481205e-01 1.000000e+00
## 2  Control - ND  -9.3628289 7.762984e-21 2.328895e-20
## 3      DM2 - ND -10.3895660 2.766089e-25 8.298266e-25
dunnTest(Urea ~ Grupos_de_estudio, data = selected_data, method = "bonferroni")
## Dunn (1964) Kruskal-Wallis multiple comparison
##   p-values adjusted with the Bonferroni method.
##      Comparison         Z      P.unadj        P.adj
## 1 Control - DM2 -4.187849 2.816113e-05 8.448338e-05
## 2  Control - ND -9.574491 1.023601e-21 3.070802e-21
## 3      DM2 - ND -7.541207 4.656418e-14 1.396925e-13
dunnTest(BUN ~ Grupos_de_estudio, data = selected_data, method = "bonferroni")
## Dunn (1964) Kruskal-Wallis multiple comparison
##   p-values adjusted with the Bonferroni method.
##      Comparison         Z      P.unadj        P.adj
## 1 Control - DM2 -4.587600 4.483714e-06 1.345114e-05
## 2  Control - ND -9.638377 5.505135e-22 1.651540e-21
## 3      DM2 - ND -7.255559 4.000071e-13 1.200021e-12
dunnTest(TFGe ~ Grupos_de_estudio, data = selected_data, method = "bonferroni")
## Dunn (1964) Kruskal-Wallis multiple comparison
##   p-values adjusted with the Bonferroni method.
##      Comparison        Z      P.unadj        P.adj
## 1 Control - DM2  1.83224 6.691565e-02 2.007469e-01
## 2  Control - ND 10.46743 1.219105e-25 3.657315e-25
## 3      DM2 - ND 10.72597 7.687432e-27 2.306230e-26
data$RIESGO_CV_Dx_Framingham <- factor(data$RIESGO_CV_Dx_Framingham, 
                                       levels = c("BAJO", "MODERADO", "ALTO"))
tabla <- table(data$Grupos_de_estudio, data$RIESGO_CV_Dx_Framingham)
tabla_con_totales <- addmargins(tabla)

print(tabla_con_totales)
##          
##           BAJO MODERADO ALTO Sum
##   Control   47       18    4  69
##   DM2       40       81   80 201
##   ND         3       15   35  53
##   Sum       90      114  119 323
frecuencias_relativas <- prop.table(tabla, margin = 1) * 100
print(round(frecuencias_relativas, 1))
##          
##           BAJO MODERADO ALTO
##   Control 68.1     26.1  5.8
##   DM2     19.9     40.3 39.8
##   ND       5.7     28.3 66.0
tabla_df <- as.data.frame(tabla)

# Graficar frecuencias absolutas
ggplot(tabla_df, aes(x = Var1, y = Freq, fill = Var2)) +
  geom_bar(stat = "identity", position = "fill") +
  scale_y_continuous(labels = scales::percent) +
  labs(
    x = "Grupos de Estudio",
    y = "Proporción",
    fill = "Riesgo Cardiovascular",
    title = "Distribución del Riesgo Cardiovascular por Grupo de Estudio"
  ) +
  theme_minimal()

chisq_result <- chisq.test(tabla)
print(chisq_result)
## 
##  Pearson's Chi-squared test
## 
## data:  tabla
## X-squared = 88.682, df = 4, p-value < 2.2e-16
library(DescTools)
v_cramer <- CramerV(tabla)
print(paste("V de Cramer:", v_cramer))
## [1] "V de Cramer: 0.370511636468487"
###Valores de referencia para el V de Cramer:
    # 0.00 - 0.10 Asociación débil o despreciable
    # 0.10 - 0.30 Asociación moderada
    #   0.30 - 0.50 Asociación fuerte
    #   > 0.50 :Asociación muy fuerte
data <- data %>%
  mutate(
    Riesgo_ApoE = factor(
      case_when(
        ApoE %in% c("E2/E2", "E2/E3") ~ "Renal",
        ApoE %in% c("E3/E4", "E4/E4") ~ "Cardiovascular",
        ApoE == "E2/E4" ~ "Renal y Cardiovascular",
        ApoE == "E3/E3" ~ "Referencia"
      ),
      levels = c("Renal", "Cardiovascular", "Renal y Cardiovascular", "Referencia")
    )
  )

tabla <- table(data$Grupos_de_estudio, data$Riesgo_ApoE)

tabla_con_totales <- addmargins(tabla)
print(tabla_con_totales)
##          
##           Renal Cardiovascular Renal y Cardiovascular Referencia Sum
##   Control     5             14                      1         49  69
##   DM2        15             76                      8        102 201
##   ND          4             24                      3         22  53
##   Sum        24            114                     12        173 323
frecuencias_relativas <- prop.table(tabla, margin = 1) * 100
print(round(frecuencias_relativas, 1))
##          
##           Renal Cardiovascular Renal y Cardiovascular Referencia
##   Control   7.2           20.3                    1.4       71.0
##   DM2       7.5           37.8                    4.0       50.7
##   ND        7.5           45.3                    5.7       41.5
tabla_df <- as.data.frame(tabla)

ggplot(tabla_df, aes(x = Var1, y = Freq, fill = Var2)) +
  geom_bar(stat = "identity", position = "fill") +
  scale_y_continuous(labels = scales::percent) +
  labs(
    x = "Grupos de estudio",
    y = "Proporción",
    fill = "Riesgo ApoE",
    title = "Distribución del riesgo ApoE por grupo de estudio"
  ) +
  theme_minimal()

fisher_result <- fisher.test(tabla)
print(fisher_result)
## 
##  Fisher's Exact Test for Count Data
## 
## data:  tabla
## p-value = 0.02522
## alternative hypothesis: two.sided
## Aunque no es estadísticamente significativa, la tabla de frecuencias relativas muestra tendencias ND tiene un porcentaje más alto en la categoría “Cardiovascular” (44.3%) comparado con DM2 (32.2%) y Control (22.8%) esto puede ser relevante clínicamente, incluso si no es estadísticamente significativo
data <- data %>%
  mutate(
    Riesgo_ApoE = factor(
      case_when(
        ApoE %in% c("E2/E2", "E2/E3", "E2/E4") ~ "Renal y Cardiovascular", 
        ApoE %in% c("E3/E4", "E4/E4") ~ "Cardiovascular",
        ApoE == "E3/E3" ~ "Referencia"
      ),
      levels = c("Renal y Cardiovascular", "Cardiovascular", "Referencia") 
    )
  )

tabla <- table(data$Grupos_de_estudio, data$Riesgo_ApoE)

tabla_con_totales <- addmargins(tabla)
print(tabla_con_totales)
##          
##           Renal y Cardiovascular Cardiovascular Referencia Sum
##   Control                      6             14         49  69
##   DM2                         23             76        102 201
##   ND                           7             24         22  53
##   Sum                         36            114        173 323
frecuencias_relativas <- prop.table(tabla, margin = 1) * 100
print(round(frecuencias_relativas, 1))
##          
##           Renal y Cardiovascular Cardiovascular Referencia
##   Control                    8.7           20.3       71.0
##   DM2                       11.4           37.8       50.7
##   ND                        13.2           45.3       41.5
tabla_df <- as.data.frame(tabla)

ggplot(tabla_df, aes(x = Var1, y = Freq, fill = Var2)) +
  geom_bar(stat = "identity", position = "fill") +
  scale_y_continuous(labels = scales::percent) +
  labs(
    x = "Grupos de estudio",
    y = "Proporción",
    fill = "Riesgo ApoE",
    title = "Distribución del riesgo ApoE por grupo de estudio"
  ) +
  theme_minimal()

fisher_result <- fisher.test(tabla)
print(fisher_result)
## 
##  Fisher's Exact Test for Count Data
## 
## data:  tabla
## p-value = 0.01173
## alternative hypothesis: two.sided
### Se utilizo fisher porque no tiene restricciones sobre las frecuencias esperadas en las celdas
colnames(data)[colnames(data) == "IL-6"] <- "IL6"
colnames(data)[colnames(data) == "IL-6"] <- "IL6"

data$IL6 <- factor(data$IL6, levels = c("G/G", "G/C", "C/C"))

tabla_IL6 <- table(data$Grupos_de_estudio, data$IL6)
tabla_IL6_con_totales <- addmargins(tabla_IL6)

print(tabla_IL6_con_totales)
##          
##           G/G G/C C/C Sum
##   Control  44  21   4  69
##   DM2     136  55  10 201
##   ND       33  20   0  53
##   Sum     213  96  14 323
frecuencias_relativas_IL6 <- prop.table(tabla_IL6, margin = 1) * 100
print(round(frecuencias_relativas_IL6, 1))
##          
##            G/G  G/C  C/C
##   Control 63.8 30.4  5.8
##   DM2     67.7 27.4  5.0
##   ND      62.3 37.7  0.0
tabla_IL6_df <- as.data.frame(tabla_IL6)

library(ggplot2)
ggplot(tabla_IL6_df, aes(x = Var1, y = Freq, fill = Var2)) +
  geom_bar(stat = "identity", position = "fill") +
  scale_y_continuous(labels = scales::percent) +
  labs(
    x = "Grupos de Estudio",
    y = "Proporción",
    fill = "Genotipos de IL6",
    title = "Distribución de los Genotipos de IL6 por Grupo de Estudio"
  ) +
  theme_minimal()

fisher_result <- fisher.test(tabla)
print(fisher_result)
## 
##  Fisher's Exact Test for Count Data
## 
## data:  tabla
## p-value = 0.01173
## alternative hypothesis: two.sided
###El genotipo G/C esta más representado en el grupo ND, mientras que el genotipo C/C es raro en todos los grupos, pero más presente en Control
#install.packages("https://cran.r-project.org/bin/macosx/big-sur-arm64/contrib/4.3/rms_6.8-1.tgz", repos = NULL, type = "binary")
library(rms)
## Loading required package: Hmisc
## 
## Attaching package: 'Hmisc'
## The following objects are masked from 'package:DescTools':
## 
##     %nin%, Label, Mean, Quantile
## The following object is masked from 'package:gt':
## 
##     html
## The following objects are masked from 'package:dplyr':
## 
##     src, summarize
## The following objects are masked from 'package:base':
## 
##     format.pval, units
snp_indices <- which(colnames(data) == "IL6")

library(SNPassoc)
## Registered S3 method overwritten by 'SNPassoc':
##   method            from       
##   summary.haplo.glm haplo.stats
SNPs <- setupSNP(data, colSNPs = snp_indices, sep = "/")
plot(SNPs$IL6)

plot(SNPs$IL6, type = pie)

names(SNPs)
##  [1] "Registro"                     "Nombre"                      
##  [3] "GRUPO"                        "Sexo"                        
##  [5] "Edad"                         "Peso"                        
##  [7] "Talla"                        "IMC"                         
##  [9] "Cintura"                      "Cadera"                      
## [11] "ICC"                          "Glucosa"                     
## [13] "HBA1c"                        "Colesterol_total"            
## [15] "VLDL"                         "LDL"                         
## [17] "HDL"                          "Trigliceridos"               
## [19] "Creatinina"                   "Urea"                        
## [21] "BUN"                          "TFGe"                        
## [23] "DISFUNCIÓN_RENAL"             "RIESGO_CARDIO-VASCULAR"      
## [25] "RIESGO_CV_Dx_Framingham"      "Fuma"                        
## [27] "Consume_alcohol"              "HTA"                         
## [29] "TX_HTA"                       "Diabetes_Mellitus"           
## [31] "Dislipidemia"                 "Tratamiento_Lipemiante"      
## [33] "ApoE"                         "Riesgo_ApoE"                 
## [35] "Grupos_de_estudio"            "Disfunción_renal"            
## [37] "Consumo_de_alcohol"           "Hipertensión"                
## [39] "Diabetes_mellitus"            "Tratamiento_antihipertensivo"
## [41] "Tratamiento_antilipemiante"   "IL6"
#Perform association analysis for each SNP
association(TFGe ~ IL6, data = SNPs)
## 
## SNP: IL6  adjusted by: 
##                n    me    se     dif   lower  upper p-value  AIC
## Codominant                                                      
## G/G          213 87.45 2.014  0.0000                 0.1308 3101
## G/C           96 82.88 3.108 -4.5755 -11.611  2.460             
## C/C           14 98.57 3.027 11.1188  -4.672 26.910             
## Dominant                                                        
## G/G          213 87.45 2.014  0.0000                 0.4544 3103
## G/C-C/C      110 84.87 2.782 -2.5781  -9.324  4.168             
## Recessive                                                       
## G/G-G/C      309 86.03 1.692  0.0000                 0.1174 3101
## C/C           14 98.57 3.027 12.5403  -3.114 28.194             
## Overdominant                                                    
## G/G-C/C      227 88.14 1.906  0.0000                 0.1404 3101
## G/C           96 82.88 3.108 -5.2613 -12.239  1.716             
## log-Additive                                                    
## 0,1,2                        -0.1825  -5.811  5.446  0.9494 3103
# Reemplazar "NA" por NA en las variables numéricas
data$Cintura[data$Cintura == "NA"] <- NA
data$ICC[data$ICC== "NA"] <- NA
data$Cadera[data$Cadera == "NA"] <- NA
data$HBA1c[data$HBA1c == "NA"] <- NA
# Convertir columnas a numéricas
data$Cintura <- as.numeric(as.character(data$Cintura))
data$Cadera <- as.numeric(as.character(data$Cadera))
data$ICC <- as.numeric(as.character(data$ICC))
data$HBA1c <- as.numeric(as.character(data$HBA1c))
# Verificar qué filas tienen valores no numéricos en cada columna
str(data$Cintura)      
##  num [1:323] 113 105 109 103 87 ...
str(data$Cadera)
##  num [1:323] 123 115 107 100 94 ...
str(data$HBA1c)   
##  num [1:323] 9.1 7.9 5.7 7.4 5.8 9.5 8 7.9 6.5 8.1 ...
str(data$ICC)
##  num [1:323] 0.919 0.913 1.019 1.025 0.926 ...
# Verificar cuántos NA hay en cada columna
sum(is.na(data$Cintura))
## [1] 2
sum(is.na(data$Cadera))
## [1] 2
sum(is.na(data$HBA1c))
## [1] 1
sum(is.na(data$ICC))
## [1] 2
#install.packages("car")
library(car)
# Identificar las variables colineales
modelo <- lm(IMC ~ IL6 + Glucosa + HBA1c + Sexo + Edad + Urea + BUN + TFGe +
               Creatinina + Colesterol_total + HDL + LDL + VLDL + Trigliceridos +
               Consume_alcohol + HTA + Fuma, data = data)

alias_info <- alias(modelo)

colineales <- rownames(alias_info$Complete)
print("Variables colineales:")
## [1] "Variables colineales:"
print(colineales)
## [1] "VLDL"            "Trigliceridos"   "Consume_alcohol" "HTA"            
## [5] "FumaSí"
colSums(is.na(data))
##                     Registro                       Nombre 
##                            0                            0 
##                        GRUPO                         Sexo 
##                            0                            0 
##                         Edad                         Peso 
##                            0                            0 
##                        Talla                          IMC 
##                            0                            0 
##                      Cintura                       Cadera 
##                            2                            2 
##                          ICC                      Glucosa 
##                            2                            0 
##                        HBA1c             Colesterol_total 
##                            1                            0 
##                         VLDL                          LDL 
##                            0                            0 
##                          HDL                Trigliceridos 
##                            0                            0 
##                   Creatinina                         Urea 
##                            0                            0 
##                          BUN                         TFGe 
##                            0                            0 
##             DISFUNCIÓN_RENAL       RIESGO_CARDIO-VASCULAR 
##                            0                            0 
##      RIESGO_CV_Dx_Framingham                         Fuma 
##                            0                            0 
##              Consume_alcohol                          HTA 
##                            0                            0 
##                       TX_HTA            Diabetes_Mellitus 
##                            0                            0 
##                 Dislipidemia       Tratamiento_Lipemiante 
##                            0                            0 
##                          IL6                         ApoE 
##                            0                            0 
##                  Riesgo_ApoE            Grupos_de_estudio 
##                            0                            0 
##             Disfunción_renal           Consumo_de_alcohol 
##                            0                            0 
##                 Hipertensión            Diabetes_mellitus 
##                            0                            0 
## Tratamiento_antihipertensivo   Tratamiento_antilipemiante 
##                            0                            0
data[!complete.cases(data), ]
##       Registro                            Nombre GRUPO Sexo Edad  Peso Talla
## 26     MIDE087 RODRÍGUEZ MORALES JESÚS FRANCISCO     2    M   62  59.6  1.58
## 94  IRC5-ND031  María del Rosario Sarabia Zamora     2    F   57  60.0  1.66
## 239  IRC-ND043        Jesus Enrique Ramirez Vega     1    M   36 103.0  1.78
##          IMC Cintura Cadera      ICC Glucosa HBA1c Colesterol_total   VLDL
## 26  23.87438      NA     NA       NA  210.61   6.9           224.33 36.134
## 94  21.77384      98     95 1.031579  278.00    NA           197.30 16.400
## 239 32.50852      NA     NA       NA   87.90   6.4           114.00 51.860
##        LDL   HDL Trigliceridos Creatinina   Urea      BUN  TFGe
## 26  171.68 16.52        180.67       3.80 176.32 82.93000  16.0
## 94   116.9 64.00         82.00       5.81 134.20 62.62834   5.7
## 239  27.84 34.30        259.30       0.75  37.90 17.70000 118.0
##     DISFUNCIÓN_RENAL RIESGO_CARDIO-VASCULAR RIESGO_CV_Dx_Framingham Fuma
## 26                 1                     30                    ALTO   Sí
## 94                 1     8.6999999999999993                    BAJO   No
## 239                0                    5.3                    BAJO   No
##     Consume_alcohol HTA TX_HTA Diabetes_Mellitus Dislipidemia
## 26                0   0      0                 1           No
## 94                1   1      1                 1           No
## 239               0   0      0                 1           Sí
##     Tratamiento_Lipemiante IL6  ApoE    Riesgo_ApoE Grupos_de_estudio
## 26                       0 G/G E3/E4 Cardiovascular                ND
## 94                       0 G/G E4/E4 Cardiovascular                ND
## 239                      1 C/C E3/E3     Referencia               DM2
##         Disfunción_renal Consumo_de_alcohol Hipertensión Diabetes_mellitus
## 26  Con disfunción renal                 No           No                Sí
## 94  Con disfunción renal                 Sí           Sí                Sí
## 239 Sin disfunción renal                 No           No                Sí
##     Tratamiento_antihipertensivo Tratamiento_antilipemiante
## 26                            No                         No
## 94                            Sí                         No
## 239                           No                         Sí
data <- na.omit(data)
colSums(is.na(data))
##                     Registro                       Nombre 
##                            0                            0 
##                        GRUPO                         Sexo 
##                            0                            0 
##                         Edad                         Peso 
##                            0                            0 
##                        Talla                          IMC 
##                            0                            0 
##                      Cintura                       Cadera 
##                            0                            0 
##                          ICC                      Glucosa 
##                            0                            0 
##                        HBA1c             Colesterol_total 
##                            0                            0 
##                         VLDL                          LDL 
##                            0                            0 
##                          HDL                Trigliceridos 
##                            0                            0 
##                   Creatinina                         Urea 
##                            0                            0 
##                          BUN                         TFGe 
##                            0                            0 
##             DISFUNCIÓN_RENAL       RIESGO_CARDIO-VASCULAR 
##                            0                            0 
##      RIESGO_CV_Dx_Framingham                         Fuma 
##                            0                            0 
##              Consume_alcohol                          HTA 
##                            0                            0 
##                       TX_HTA            Diabetes_Mellitus 
##                            0                            0 
##                 Dislipidemia       Tratamiento_Lipemiante 
##                            0                            0 
##                          IL6                         ApoE 
##                            0                            0 
##                  Riesgo_ApoE            Grupos_de_estudio 
##                            0                            0 
##             Disfunción_renal           Consumo_de_alcohol 
##                            0                            0 
##                 Hipertensión            Diabetes_mellitus 
##                            0                            0 
## Tratamiento_antihipertensivo   Tratamiento_antilipemiante 
##                            0                            0
data$Sexo <- as.factor(data$Sexo)
levels(data$Sexo)
## [1] "F" "M"
data$Sexo <- relevel(data$Sexo, ref = "M")
### Evaluar la asociación entre variantes genéticas (IL-6 y ApoE) y la presencia de disfunción renal
set.seed(123)  # Para reproducibilidad
data <- data[sample(nrow(data)), ]

modelo_nulo <- glm(DISFUNCIÓN_RENAL ~ 1, data = data, family = binomial, na.action = na.exclude)

# Modelo completo 
modelo_completo <- glm(DISFUNCIÓN_RENAL ~ IL6 + ApoE + Edad + Sexo + HBA1c, 
                        family = binomial, data = data)


OR <- exp(coef(modelo_completo))
CI <- exp(confint(modelo_completo))
## Waiting for profiling to be done...
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
p_values <- summary(modelo_completo)$coefficients[, 4]
OR_completo <- cbind(OR, CI, p_values)
print(OR_completo)
##                       OR       2.5 %       97.5 %     p_values
## (Intercept) 3.888603e-02 0.001441672 7.905513e-01 0.0418448514
## IL6G/C      1.141075e+00 0.563575042 2.254517e+00 0.7077647460
## IL6C/C      1.282622e-07          NA 5.785429e+24 0.9875715946
## ApoEE2/E3   5.947689e-01 0.052186999 6.813698e+00 0.6622100231
## ApoEE2/E4   1.212036e+00 0.129214172 1.350098e+01 0.8670946100
## ApoEE3/E3   5.635615e-01 0.103147069 4.541643e+00 0.5369128582
## ApoEE3/E4   8.969081e-01 0.159878873 7.285258e+00 0.9075755842
## ApoEE4/E4   3.654006e-01 0.031191633 4.213214e+00 0.4011679793
## Edad        1.057630e+00 1.025464300 1.093584e+00 0.0006054667
## SexoF       3.252070e-01 0.167104506 6.219443e-01 0.0007640348
## HBA1c       8.883826e-01 0.718721699 1.079144e+00 0.2517371543
summary(modelo_completo)
## 
## Call:
## glm(formula = DISFUNCIÓN_RENAL ~ IL6 + ApoE + Edad + Sexo + 
##     HBA1c, family = binomial, data = data)
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)    
## (Intercept)   -3.24712    1.59559  -2.035 0.041845 *  
## IL6G/C         0.13197    0.35205   0.375 0.707765    
## IL6C/C       -15.86919 1018.73641  -0.016 0.987572    
## ApoEE2/E3     -0.51958    1.18935  -0.437 0.662210    
## ApoEE2/E4      0.19230    1.14910   0.167 0.867095    
## ApoEE3/E3     -0.57348    0.92873  -0.617 0.536913    
## ApoEE3/E4     -0.10880    0.93716  -0.116 0.907576    
## ApoEE4/E4     -1.00676    1.19919  -0.840 0.401168    
## Edad           0.05603    0.01634   3.429 0.000605 ***
## SexoF         -1.12329    0.33377  -3.366 0.000764 ***
## HBA1c         -0.11835    0.10326  -1.146 0.251737    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 280.72  on 319  degrees of freedom
## Residual deviance: 243.15  on 309  degrees of freedom
## AIC: 265.15
## 
## Number of Fisher Scoring iterations: 16
##removimos del modelo la variable de TFGe porque esta perfectamente alineado con la disfunción renal
###Evaluar el RCV por RLM 
##Antes de ajustar el modelo, asegurémonos de que las variables están en el formato correcto
library(nnet)

data$RIESGO_CV_Dx_Framingham <- factor(data$RIESGO_CV_Dx_Framingham, 
                                       levels = c("BAJO", "MODERADO", "ALTO"))  # "BAJO" como referencia

data$IL6 <- factor(data$IL6, levels = c("G/G", "G/C", "C/C"))
data$IL6 <- relevel(data$IL6, ref = "G/G")  # Establecer referencia en "G/G"

data$ApoE <- as.factor(data$ApoE)
data$Sexo <- as.factor(data$Sexo)
data$DISFUNCIÓN_RENAL <- as.factor(data$DISFUNCIÓN_RENAL)

num_vars <- c("Edad", "HBA1c", "IMC", "TFGe", "Creatinina")
data[num_vars] <- lapply(data[num_vars], as.numeric)

data <- droplevels(data)
# Ajustar el modelo
modelo_multinom <- multinom(RIESGO_CV_Dx_Framingham ~ IL6 + ApoE + Edad + Sexo + HBA1c + IMC + TFGe + Creatinina, 
                            data = data)
## # weights:  45 (28 variable)
## initial  value 351.555932 
## iter  10 value 294.557952
## iter  20 value 256.606337
## iter  30 value 250.444030
## iter  40 value 250.134863
## iter  40 value 250.134863
## iter  40 value 250.134863
## final  value 250.134863 
## converged
exp(cbind(OR = coef(modelo_multinom), confint(modelo_multinom)))
## Warning in cbind(OR = coef(modelo_multinom), confint(modelo_multinom)): number
## of rows of result is not a multiple of vector length (arg 2)
##           (Intercept)    IL6G/C   IL6C/C ApoEE2/E3 ApoEE2/E4 ApoEE3/E3
## MODERADO 2.615571e-05 1.3512822 1.874396 0.3005051 1.3473818 0.5710123
## ALTO     1.254371e-07 0.6101471 0.734676 0.5484217 0.6031813 0.4568554
##          ApoEE3/E4 ApoEE4/E4     Edad     SexoF    HBA1c      IMC      TFGe
## MODERADO 0.6128642 0.4854360 1.114979 0.4922020 1.446485 1.090690 1.0009310
## ALTO     0.2783592 0.6293414 1.238810 0.2588276 1.594076 1.107588 0.9843991
##          Creatinina             
## MODERADO   1.644636 4.022852e-08
## ALTO       1.616108 6.476752e-01
z_values <- coef(modelo_multinom) / summary(modelo_multinom)$standard.errors
p_values <- 2 * (1 - pnorm(abs(z_values)))

OR_table <- exp(coef(modelo_multinom))
CI_lower <- exp(coef(modelo_multinom) - 1.96 * summary(modelo_multinom)$standard.errors)
CI_upper <- exp(coef(modelo_multinom) + 1.96 * summary(modelo_multinom)$standard.errors)

resultados <- data.frame(OR = OR_table, Lower95 = CI_lower, Upper95 = CI_upper, p_values)
print(resultados)
##          OR..Intercept. OR.IL6G.C OR.IL6C.C OR.ApoEE2.E3 OR.ApoEE2.E4
## MODERADO   2.615571e-05 1.3512822  1.874396    0.3005051    1.3473818
## ALTO       1.254371e-07 0.6101471  0.734676    0.5484217    0.6031813
##          OR.ApoEE3.E3 OR.ApoEE3.E4 OR.ApoEE4.E4  OR.Edad  OR.SexoF OR.HBA1c
## MODERADO    0.5710123    0.6128642    0.4854360 1.114979 0.4922020 1.446485
## ALTO        0.4568554    0.2783592    0.6293414 1.238810 0.2588276 1.594076
##            OR.IMC   OR.TFGe OR.Creatinina Lower95..Intercept. Lower95.IL6G.C
## MODERADO 1.090690 1.0009310      1.644636        4.022373e-08      0.6476665
## ALTO     1.107588 0.9843991      1.616108        8.408510e-11      0.2529850
##          Lower95.IL6C.C Lower95.ApoEE2.E3 Lower95.ApoEE2.E4 Lower95.ApoEE3.E3
## MODERADO     0.36952126        0.01712973        0.07187028        0.05094031
## ALTO         0.09423943        0.02939918        0.02524783        0.03627083
##          Lower95.ApoEE3.E4 Lower95.ApoEE4.E4 Lower95.Edad Lower95.SexoF
## MODERADO        0.05264534        0.03120928     1.065546     0.2192881
## ALTO            0.02083757        0.03445786     1.170001     0.1039754
##          Lower95.HBA1c Lower95.IMC Lower95.TFGe Lower95.Creatinina
## MODERADO      1.179688    1.021376    0.9731968          0.5630997
## ALTO          1.258140    1.025672    0.9552741          0.5485378
##          Upper95..Intercept. Upper95.IL6G.C Upper95.IL6C.C Upper95.ApoEE2.E3
## MODERADO        0.0170078952       2.819296       9.507875          5.271733
## ALTO            0.0001871255       1.471548       5.727420         10.230435
##          Upper95.ApoEE2.E4 Upper95.ApoEE3.E3 Upper95.ApoEE3.E4
## MODERADO          25.25992          6.400727          7.134583
## ALTO              14.41025          5.754400          3.718467
##          Upper95.ApoEE4.E4 Upper95.Edad Upper95.SexoF Upper95.HBA1c Upper95.IMC
## MODERADO          7.550577     1.166706     1.1047699      1.773621    1.164708
## ALTO             11.494348     1.311665     0.6443035      2.019712    1.196046
##          Upper95.TFGe Upper95.Creatinina X.Intercept.    IL6G.C    IL6C.C
## MODERADO     1.029456           4.803461 1.409083e-03 0.4223578 0.4482387
## ALTO         1.014412           4.761393 2.023923e-05 0.2713612 0.7685486
##          ApoEE2.E3 ApoEE2.E4 ApoEE3.E3 ApoEE3.E4 ApoEE4.E4         Edad
## MODERADO 0.4107298 0.8419639 0.6495108 0.6958261 0.6057444 2.551292e-06
## ALTO     0.6874049 0.7548661 0.5444547 0.3335597 0.7547007 2.058353e-13
##                SexoF        HBA1c         IMC      TFGe Creatinina
## MODERADO 0.085713386 0.0003873197 0.009559738 0.9482453  0.3629291
## ALTO     0.003675876 0.0001125500 0.009145035 0.3048168  0.3839019
##Si el p-valor de la prueba es < 0.05, significa que al menos un predictor está asociado significativamente con el riesgo cardiovascular.
# Comparar con el modelo nulo (sin predictores)
modelo_nulo <- multinom(RIESGO_CV_Dx_Framingham ~ 1, data = data)
## # weights:  6 (2 variable)
## initial  value 351.555932 
## final  value 348.989670 
## converged
# Prueba de razón de verosimilitudes (LR Test)
anova(modelo_nulo, modelo_multinom, test = "Chisq")
## Likelihood ratio tests of Multinomial Models
## 
## Response: RIESGO_CV_Dx_Framingham
##                                                        Model Resid. df
## 1                                                          1       638
## 2 IL6 + ApoE + Edad + Sexo + HBA1c + IMC + TFGe + Creatinina       612
##   Resid. Dev   Test    Df LR stat. Pr(Chi)
## 1   697.9793                              
## 2   500.2697 1 vs 2    26 197.7096       0
####    Pr(Chi) = 0 significa que el modelo completo es significativamente mejor que el modelo nulo, lo que indica que al menos una de las variables predictoras está asociada con el riesgo cardiovascular. No significa que todas las variables sean significativas, pero al menos una de ellas tiene un efecto importante.
###Evaluar cómo IL6 y ApoE se asocian con variables clínicas continuas (HBA1c, IMC, TFGe, etc.), usamos modelos de regresión lineal
# Regresión lineal con TFGe como variable de respuesta
modelo_lineal_TFGe <- lm(TFGe ~ IL6 + ApoE + Edad + Sexo + IMC + HBA1c + Creatinina, data = data)

coef_table_TFGe <- summary(modelo_lineal_TFGe)$coefficients
CI_TFGe <- confint(modelo_lineal_TFGe)
OR_TFGe <- exp(coef_table_TFGe[, 1])

resultados_TFGe <- data.frame(
  Variable = rownames(coef_table_TFGe), 
  OR = OR_TFGe,
  Coef = coef_table_TFGe[,1], 
  Lower95 = CI_TFGe[,1], 
  Upper95 = CI_TFGe[,2], 
  p_values = coef_table_TFGe[,4]
)

print("Resultados del modelo con TFGe como variable de respuesta:")
## [1] "Resultados del modelo con TFGe como variable de respuesta:"
print(resultados_TFGe)
##                Variable           OR         Coef     Lower95     Upper95
## (Intercept) (Intercept) 2.616844e+67 155.23517011 134.8667725 175.6035677
## IL6G/C           IL6G/C 2.133877e+00   0.75794049  -3.2973278   4.8132088
## IL6C/C           IL6C/C 2.159569e+01   3.07249373  -6.2316474  12.3766349
## ApoEE2/E3     ApoEE2/E3 3.402816e-01  -1.07798183 -14.9936773  12.8377137
## ApoEE2/E4     ApoEE2/E4 4.706831e-01  -0.75357020 -15.4106399  13.9034995
## ApoEE3/E3     ApoEE3/E3 2.824974e+00   1.03849912 -10.6026580  12.6796562
## ApoEE3/E4     ApoEE3/E4 1.330171e+00   0.28530744 -11.5345707  12.1051855
## ApoEE4/E4     ApoEE4/E4 2.932719e+00   1.07593000 -12.4935900  14.6454500
## Edad               Edad 3.890993e-01  -0.94392070  -1.1079400  -0.7799014
## SexoF             SexoF 3.904189e-01  -0.94053503  -4.9276833   3.0466132
## IMC                 IMC 1.066305e+00   0.06419921  -0.2850323   0.4134307
## HBA1c             HBA1c 8.273930e-01  -0.18947546  -1.2068894   0.8279385
## Creatinina   Creatinina 1.376999e-05 -11.19301885 -12.2125547 -10.1734830
##                 p_values
## (Intercept) 1.598089e-38
## IL6G/C      7.132964e-01
## IL6C/C      5.163087e-01
## ApoEE2/E3   8.789480e-01
## ApoEE2/E4   9.194837e-01
## ApoEE3/E3   8.607719e-01
## ApoEE3/E4   9.621482e-01
## ApoEE4/E4   8.761190e-01
## Edad        4.483717e-25
## SexoF       6.428556e-01
## IMC         7.178055e-01
## HBA1c       7.142791e-01
## Creatinina  1.408226e-63
##El modelo esta desajustado por los valores de OR tan extremos es necesario utilizar otro tipo de regresion para minimar el desajuste por el tamaño de muestra en los grupos. Dado que muchas variables no son significativas, intentar con un modelo parsimonioso
library(MASS)

modelo_inicial <- lm(TFGe ~ IL6 + ApoE + Edad + Sexo + IMC + HBA1c + Creatinina, data = data)

# Modelo parsimonioso
modelo_parsimonioso <- stepAIC(modelo_inicial, direction = "both", trace = FALSE)
summary(modelo_parsimonioso)
## 
## Call:
## lm(formula = TFGe ~ Edad + Creatinina, data = data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -46.014  -5.019   3.236   9.523  67.811 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 156.43656    4.81785   32.47   <2e-16 ***
## Edad         -0.95016    0.08016  -11.85   <2e-16 ***
## Creatinina  -11.10541    0.48284  -23.00   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 16.01 on 317 degrees of freedom
## Multiple R-squared:  0.6921, Adjusted R-squared:  0.6902 
## F-statistic: 356.3 on 2 and 317 DF,  p-value: < 2.2e-16
coef_table <- summary(modelo_parsimonioso)$coefficients
CI <- confint(modelo_parsimonioso)

resultados <- data.frame(
  Variable = rownames(coef_table), 
  Coef = coef_table[,1], 
  Lower95 = CI[,1], 
  Upper95 = CI[,2], 
  p_values = coef_table[,4]
)


print("Resultados del modelo parsimonioso con TFGe como variable de respuesta:")
## [1] "Resultados del modelo parsimonioso con TFGe como variable de respuesta:"
print(resultados)
##                Variable        Coef    Lower95     Upper95      p_values
## (Intercept) (Intercept) 156.4365606 146.957556 165.9155657 7.752900e-103
## Edad               Edad  -0.9501645  -1.107871  -0.7924584  4.448406e-27
## Creatinina   Creatinina -11.1054074 -12.055389 -10.1554262  1.519506e-69
###El modelo parsimonioso resultante incluye solo Edad y Creatinina como predictores significativos de TFGe, lo cual indica que las demás variables no aportaban información relevante para la predicción.
unique(data$RIESGO_CV_Dx_Framingham)
## [1] BAJO     ALTO     MODERADO
## Levels: BAJO MODERADO ALTO
# Crear la nueva variable combinada
data <- data %>%
  mutate(Riesgo_Combinado = case_when(
    DISFUNCIÓN_RENAL == 0 & RIESGO_CV_Dx_Framingham %in% c("BAJO", "MODERADO") ~ "SinDisfuncion_SinRCV",
    DISFUNCIÓN_RENAL == 0 & RIESGO_CV_Dx_Framingham == "ALTO" ~ "SinDisfuncion_ConRCV",
    DISFUNCIÓN_RENAL == 1 & RIESGO_CV_Dx_Framingham %in% c("BAJO", "MODERADO") ~ "ConDisfuncion_SinRCV",
    DISFUNCIÓN_RENAL == 1 & RIESGO_CV_Dx_Framingham == "ALTO" ~ "ConDisfuncion_ConRCV",
    TRUE ~ NA_character_  # Para manejar valores inesperados
  ))

# Convertir en factor con niveles ordenados
data$Riesgo_Combinado <- factor(data$Riesgo_Combinado, 
                                 levels = c("SinDisfuncion_SinRCV", "SinDisfuncion_ConRCV", 
                                            "ConDisfuncion_SinRCV", "ConDisfuncion_ConRCV"))

data$Riesgo_Combinado <- relevel(data$Riesgo_Combinado, ref = "SinDisfuncion_SinRCV")
levels(data$Riesgo_Combinado)
## [1] "SinDisfuncion_SinRCV" "SinDisfuncion_ConRCV" "ConDisfuncion_SinRCV"
## [4] "ConDisfuncion_ConRCV"
# Verificar la distribución de la nueva variable
table(data$Riesgo_Combinado, useNA = "always")
## 
## SinDisfuncion_SinRCV SinDisfuncion_ConRCV ConDisfuncion_SinRCV 
##                  185                   84                   17 
## ConDisfuncion_ConRCV                 <NA> 
##                   34                    0
modelo_nulo <- multinom(Riesgo_Combinado ~ 1, data = data)
## # weights:  8 (3 variable)
## initial  value 443.614196 
## iter  10 value 339.847436
## final  value 339.847395 
## converged
modelo_multinom <- multinom(Riesgo_Combinado ~  ApoE + Edad + Sexo + HBA1c + IMC + Creatinina, 
                            data = data)
## # weights:  48 (33 variable)
## initial  value 443.614196 
## iter  10 value 297.016124
## iter  20 value 220.960783
## iter  30 value 188.914323
## iter  40 value 173.846961
## iter  50 value 173.020945
## iter  60 value 173.002654
## final  value 173.002530 
## converged
summary(modelo_nulo)
## Call:
## multinom(formula = Riesgo_Combinado ~ 1, data = data)
## 
## Coefficients:
##                      (Intercept)
## SinDisfuncion_ConRCV   -0.789539
## ConDisfuncion_SinRCV   -2.387142
## ConDisfuncion_ConRCV   -1.693995
## 
## Std. Errors:
##                      (Intercept)
## SinDisfuncion_ConRCV   0.1315681
## ConDisfuncion_SinRCV   0.2534343
## ConDisfuncion_ConRCV   0.1865936
## 
## Residual Deviance: 679.6948 
## AIC: 685.6948
summary(modelo_multinom)
## Call:
## multinom(formula = Riesgo_Combinado ~ ApoE + Edad + Sexo + HBA1c + 
##     IMC + Creatinina, data = data)
## 
## Coefficients:
##                      (Intercept)   ApoEE2/E3 ApoEE2/E4  ApoEE3/E3 ApoEE3/E4
## SinDisfuncion_ConRCV   -11.27056  -0.3147825 -1.079277 -0.8527057 -1.404732
## ConDisfuncion_SinRCV   -22.58366 -27.1546513 -3.873265 -4.3213133 -2.791523
## ConDisfuncion_ConRCV   -29.01262  -4.2099319 -2.946158 -3.3391152 -3.064102
##                        ApoEE4/E4       Edad      SexoF      HBA1c         IMC
## SinDisfuncion_ConRCV  -0.5585813 0.14546730 -0.8567108  0.1793499  0.06157167
## ConDisfuncion_SinRCV -31.6652447 0.09012073  4.5767337 -0.1400128 -0.02975089
## ConDisfuncion_ConRCV  -3.6368206 0.21365175  4.3627902 -0.1060410 -0.09050612
##                       Creatinina
## SinDisfuncion_ConRCV -0.06594493
## ConDisfuncion_SinRCV 17.92032485
## ConDisfuncion_ConRCV 18.03858554
## 
## Std. Errors:
##                      (Intercept)    ApoEE2/E3 ApoEE2/E4 ApoEE3/E3 ApoEE3/E4
## SinDisfuncion_ConRCV    2.193357 1.146217e+00  1.276492 0.9700548 0.9998134
## ConDisfuncion_SinRCV    7.461464 1.712930e-08  2.991415 2.1172734 2.0397215
## ConDisfuncion_ConRCV    7.377621 3.080385e+00  3.030837 2.2583120 2.2322331
##                         ApoEE4/E4       Edad     SexoF      HBA1c        IMC
## SinDisfuncion_ConRCV 1.106930e+00 0.02129847 0.3891885 0.08703264 0.03142896
## ConDisfuncion_SinRCV 3.667593e-11 0.05680744 1.4940365 0.37628520 0.09868710
## ConDisfuncion_ConRCV 2.677192e+00 0.05495667 1.4500735 0.34947955 0.09737431
##                      Creatinina
## SinDisfuncion_ConRCV  0.9722161
## ConDisfuncion_SinRCV  3.5777450
## ConDisfuncion_ConRCV  3.5758173
## 
## Residual Deviance: 346.0051 
## AIC: 412.0051
###educción en la deviance (691.08 a 347.14) indica que los predictores mejoran el modelo 
OR_table <- exp(coef(modelo_multinom))
CI_lower <- exp(coef(modelo_multinom) - 1.96 * summary(modelo_multinom)$standard.errors)
CI_upper <- exp(coef(modelo_multinom) + 1.96 * summary(modelo_multinom)$standard.errors)
z_values <- coef(modelo_multinom) / summary(modelo_multinom)$standard.errors
p_values <- 2 * (1 - pnorm(abs(z_values)))

resultados <- data.frame(
  Variable = rownames(OR_table),
  OR = OR_table,
  Lower95 = CI_lower,
  Upper95 = CI_upper,
  p_values = p_values
)

print(resultados)
##                                  Variable OR..Intercept. OR.ApoEE2.E3
## SinDisfuncion_ConRCV SinDisfuncion_ConRCV   1.274265e-05 7.299476e-01
## ConDisfuncion_SinRCV ConDisfuncion_SinRCV   1.556107e-10 1.610218e-12
## ConDisfuncion_ConRCV ConDisfuncion_ConRCV   2.511768e-13 1.484738e-02
##                      OR.ApoEE2.E4 OR.ApoEE3.E3 OR.ApoEE3.E4 OR.ApoEE4.E4
## SinDisfuncion_ConRCV   0.33984115   0.42626005   0.24543270 5.720200e-01
## ConDisfuncion_SinRCV   0.02079038   0.01328243   0.06132775 1.769942e-14
## ConDisfuncion_ConRCV   0.05254119   0.03546833   0.04669574 2.633594e-02
##                       OR.Edad   OR.SexoF  OR.HBA1c    OR.IMC OR.Creatinina
## SinDisfuncion_ConRCV 1.156580  0.4245562 1.1964393 1.0635067  9.361824e-01
## ConDisfuncion_SinRCV 1.094306 97.1963981 0.8693471 0.9706873  6.063148e+07
## ConDisfuncion_ConRCV 1.238191 78.4757912 0.8993878 0.9134687  6.824301e+07
##                      Lower95..Intercept. Lower95.ApoEE2.E3 Lower95.ApoEE2.E4
## SinDisfuncion_ConRCV        1.730757e-07      7.719907e-02      2.784223e-02
## ConDisfuncion_SinRCV        6.929673e-17      1.610218e-12      5.909066e-05
## ConDisfuncion_ConRCV        1.318323e-19      3.544645e-05      1.382289e-04
##                      Lower95.ApoEE3.E3 Lower95.ApoEE3.E4 Lower95.ApoEE4.E4
## SinDisfuncion_ConRCV      0.0636718250      0.0345839085      6.533912e-02
## ConDisfuncion_SinRCV      0.0002094199      0.0011256698      1.769942e-14
## ConDisfuncion_ConRCV      0.0004241571      0.0005877086      1.385725e-04
##                      Lower95.Edad Lower95.SexoF Lower95.HBA1c Lower95.IMC
## SinDisfuncion_ConRCV    1.1092924     0.1979936     1.0088044   0.9999709
## ConDisfuncion_SinRCV    0.9790018     5.1987701     0.4158079   0.7999728
## ConDisfuncion_ConRCV    1.1117515     4.5751804     0.4533817   0.7547568
##                      Lower95.Creatinina Upper95..Intercept. Upper95.ApoEE2.E3
## SinDisfuncion_ConRCV       1.392494e-01        9.381738e-04      6.901942e+00
## ConDisfuncion_SinRCV       5.460849e+04        3.494348e-04      1.610218e-12
## ConDisfuncion_ConRCV       6.169657e+04        4.785608e-07      6.219089e+00
##                      Upper95.ApoEE2.E4 Upper95.ApoEE3.E3 Upper95.ApoEE3.E4
## SinDisfuncion_ConRCV          4.148088         2.8536583          1.741770
## ConDisfuncion_SinRCV          7.314859         0.8424362          3.341204
## ConDisfuncion_ConRCV         19.971046         2.9658877          3.710158
##                      Upper95.ApoEE4.E4 Upper95.Edad Upper95.SexoF Upper95.HBA1c
## SinDisfuncion_ConRCV      5.007825e+00     1.205883     0.9103727      1.418974
## ConDisfuncion_SinRCV      1.769942e-14     1.223191  1817.1874715      1.817580
## ConDisfuncion_ConRCV      5.005193e+00     1.379011  1346.0561743      1.784144
##                      Upper95.IMC Upper95.Creatinina p_values..Intercept.
## SinDisfuncion_ConRCV    1.131079       6.294012e+00         2.769479e-07
## ConDisfuncion_SinRCV    1.177832       6.731878e+10         2.472338e-03
## ConDisfuncion_ConRCV    1.105555       7.548406e+10         8.406103e-05
##                      p_values.ApoEE2.E3 p_values.ApoEE2.E4 p_values.ApoEE3.E3
## SinDisfuncion_ConRCV          0.7836026          0.3978304         0.37938591
## ConDisfuncion_SinRCV          0.0000000          0.1953914         0.04125279
## ConDisfuncion_ConRCV          0.1717225          0.3310204         0.13925021
##                      p_values.ApoEE3.E4 p_values.ApoEE4.E4 p_values.Edad
## SinDisfuncion_ConRCV          0.1600229          0.6138243  8.494982e-12
## ConDisfuncion_SinRCV          0.1711305          0.0000000  1.126429e-01
## ConDisfuncion_ConRCV          0.1698573          0.1743222  1.012236e-04
##                      p_values.SexoF p_values.HBA1c p_values.IMC
## SinDisfuncion_ConRCV    0.027716607     0.03932981   0.05010406
## ConDisfuncion_SinRCV    0.002188852     0.70982415   0.76305853
## ConDisfuncion_ConRCV    0.002623954     0.76156562   0.35264760
##                      p_values.Creatinina
## SinDisfuncion_ConRCV        9.459214e-01
## ConDisfuncion_SinRCV        5.476125e-07
## ConDisfuncion_ConRCV        4.544593e-07