Objetivo general

El objetivo es crear un fichero en formato Rmd, programado en R y usando las librerías y el estilo del tidyverse y generando como resultado tablas en formato académico con calidad de publicación usando librerías como gtsummary. Los gráficos deben ser también de calidad profesional usando ggplot2 y patchwork.

Datos

Provienen de dos dataframes llamadoa spssLong y spssTrans que se cargan haciendo load(“../_arreglado/spssTrans_Long.RData)

spssTrans

Este dataframe tiene una variable especial que es Codigo e identifica al paciente. Otras variables importantes son:

  • grupo_int: Binaria, Que describe el grupo al que pertenece el paciente.
  • sexo_s1: Binaria, El sexo de los pacientes
  • edad_s1: Numérica, Su edad al inicio del estudio

spssLong

Este dataframe tiene dos variables especiales llamadas:

  • Codigo: Caracter, Identifica a un paciente al que se le van a hacer medidas repetidas. Es clave externa de Codigo en spssTrans.
  • Tiempo: Numérica, Identifica la repetición concreta de las mediciones. Representa el tiempo en años desde que se inicia el estudio, que es en Tiempo==0. El conjunto de sus posibles valores es [0, 0.5, 1, 2]

Todas las demás variables están identificadas por el Codigo y el Tiempo y representan medidas repetidas dentro de cada paciente identificado por Codigo. Las más importantes que se hacen para cada paciente en cada tiempo se dividen en varias categorías: Validez, Antropometría, Cuestionario y Acelerometría.

Variables de Validez

  • critval4d: Numérica, Debe vale 1 para que las medicione sean válidas y en otro caso se eliminará toda la fila.

  • n_daily: Númerica, representa el número de días donde el paciente ha usado un acelerómetro. Debe tomar un valor superior o igual al 3 para que la fila sea válida.

Variables de Antropometría

  • imc: Numérica, Índice de masa corporal del paciente
  • peso: Numérica, El peso del paciene
  • cintura: Numérica, El perímetro del cintura

Variables de Cuestionario

Se utilizan REGICOR Physical Activity Questionnaire con la intención de saber lo que perciben los pacientes que es su actividad

  • temps_lig: Numérica, Minutos semanales en LPA reportado por el paciente
  • temps_mod: Numérica, Minutos semanales en MVPA reportado por el paciente
  • temps_int: Numérica, Minutos semanales en VPA reportado por el paciente

Variables de Acelerometría

Se utiliza para saber si la actividad que describen con el cuestionario se corresponde con lo que se mide con un acelerómetro. Son:

  • lpa_b1_weekly_mean: Numérica, mide los minutos semanales de LPA que ha realizado el paciente y se usará para estudiar la diferencia con temps_lig
  • mvpa_b1_weekly_mean: Numérica, mide los minutos semanales de MVPA y se usará para estudiar la diferencia con temps_mod
  • mvpa_b10_weekly_mean: Numérica, mide los minutos semanales de VPA y se usará para estudiar la diferencia con temps_int

Análisis estadístico

Describir todas las variables de spssLong mencionadas en una tabla con gtsummary para cada uno de los valores de Tiempo en [0, 0.5, 1, 2]

Repetir lo anterior pero comparando a los pacientes según la variable grupo_int. Acompañarlo de gráficos donde se pueda estudiar la evolución de las medias de ambos grupos (según grupo_int) en el tiempo.

Calcula las correlaciones de Pearson y las de Spearman entre las variables del Cuestionario y su equivalente de Acelerometría. Hazlo para cada tiempo por separado y muestralo en tablas adecuada.

Resultado hecho por la IA

1. Carga de librerías y datos

# Librerías principales
library(tidyverse)
library(gtsummary)
library(patchwork)

# Carga de datos
#load("../_arreglado/spssTrans_Long.RData")
spssLong=haven::read_sav("../_arreglado/spssNew-Long.sav") %>% as_factor()
spssTrans=haven::read_sav("../_arreglado/spssNew-Trans.sav") %>% as_factor()

spssTrans=spssTrans %>% #Convierte de tipo labelled a factor las variables sexo_s1 y grupo_int
  mutate(sexo_s1=as.factor(sexo_s1), grupo_int=as.factor(grupo_int))
# Data frames resultantes:
#  - spssTrans
#  - spssLong

2. Filtrado y preparación de los datos

# Nos quedamos solo con las filas en spssLong que cumplan los criterios de validez:
# critval4d == 1 y n_daily >= 3
spssLong_f <- spssLong %>% 
  mutate(critval4d=1, n_daily =3) %>%    # OJO! Faltan las columnas
  filter(critval4d == 1, n_daily >= 3)

# Unimos la información de spssTrans (grupo_int, sexo_s1, edad_s1) 
# para poder usarla en comparaciones
spssLong_f <- spssLong_f %>%
  left_join(
    spssTrans %>% select(Codigo, grupo_int, sexo_s1, edad_s1),
    by = "Codigo"
  )

# Revisa la estructura final si lo deseas
# str(spssLong_f)

3. Descriptiva de las variables por tiempo

# Listamos las variables a describir
vars_validez <- c("critval4d", "n_daily")
vars_antropometria <- c("imc", "peso", "cintura")
vars_cuestionario <- c("temps_lig", "temps_mod", "temps_int")
vars_acelerometria <- c("lpa_b1_weekly_mean", "mvpa_b1_weekly_mean", "mvpa_b10_weekly_mean")

vars_a_incluir <- c(
  vars_validez,
  vars_antropometria,
  vars_cuestionario,
  vars_acelerometria
)

# Tabla descriptiva estratificada por Tiempo
tbl_tiempo <- spssLong_f %>%
  select(all_of(vars_a_incluir), Tiempo) %>%
  tbl_summary(
    by = Tiempo,
    # Ajusta a conveniencia
    type = all_continuous() ~ "continuous",
    statistic = all_continuous() ~ "{mean} ({sd})",
    digits = all_continuous() ~ c(1, 1),   # 1 decimal en media y sd
    missing = "ifany"
  ) %>%
  add_overall() %>%
  bold_labels()

tbl_tiempo
Characteristic Overall
N = 61,866
1
0
N = 6,874
1
0.5
N = 6,874
1
1
N = 6,874
1
2
N = 6,874
1
3
N = 6,874
1
4
N = 6,874
1
5
N = 6,874
1
6
N = 6,874
1
7
N = 6,874
1
critval4d









    1 61,866 (100%) 6,874 (100%) 6,874 (100%) 6,874 (100%) 6,874 (100%) 6,874 (100%) 6,874 (100%) 6,874 (100%) 6,874 (100%) 6,874 (100%)
n_daily









    3 61,866 (100%) 6,874 (100%) 6,874 (100%) 6,874 (100%) 6,874 (100%) 6,874 (100%) 6,874 (100%) 6,874 (100%) 6,874 (100%) 6,874 (100%)
imc 32.0 (3.6) 32.6 (3.5) 31.9 (3.6) 31.7 (3.7) 31.8 (3.7) 31.6 (3.8) 31.8 (3.8) 31.7 (4.0) 31.6 (4.2) 31.8 (4.0)
    Unknown 34,102 3 319 327 447 6,586 6,589 6,594 6,609 6,628
peso 84.9 (13.1) 86.6 (13.0) 84.6 (13.0) 84.3 (13.2) 84.5 (13.3) 82.3 (12.6) 82.6 (12.9) 81.9 (12.8) 81.3 (12.7) 81.9 (13.0)
    Unknown 34,098 3 319 327 447 6,586 6,587 6,593 6,609 6,627
cintura 105.7 (10.1) 107.6 (9.7) 105.2 (9.9) 104.8 (10.1) 105.2 (10.3) 104.0 (9.7) 103.9 (10.0) 103.5 (10.9) 103.9 (10.0) 104.3 (10.4)
    Unknown 35,125 3 574 649 855 6,595 6,598 6,601 6,616 6,634
temps_lig 203.2 (238.3) 190.2 (238.3) 196.7 (234.1) 204.4 (235.9) 220.5 (243.4) 250.6 (257.9) 229.6 (243.5) 172.6 (207.5) 190.1 (225.5) 239.7 (253.2)
    Unknown 34,886 0 525 565 787 6,588 6,590 6,594 6,609 6,628
temps_mod 220.3 (325.4) 189.0 (297.1) 241.2 (337.6) 240.6 (335.4) 230.6 (332.5) 86.7 (213.5) 131.0 (253.2) 203.1 (364.2) 152.1 (268.1) 134.3 (374.8)
    Unknown 34,886 0 525 565 787 6,588 6,590 6,594 6,609 6,628
temps_int 104.3 (170.9) 90.7 (160.8) 104.6 (169.4) 113.5 (175.6) 112.2 (179.7) 107.1 (172.0) 88.3 (149.1) 93.3 (160.2) 85.7 (148.3) 92.2 (171.6)
    Unknown 34,886 0 525 565 787 6,588 6,590 6,594 6,609 6,628
lpa_b1_weekly_mean 17.7 (7.7) 17.9 (7.6) 18.3 (7.5) 17.9 (7.7) 17.8 (7.8) 16.5 (7.5) 16.2 (7.5) 16.4 (8.3) 15.7 (7.7) NA (NA)
    Unknown 53,934 4,647 5,336 5,265 5,302 6,624 6,628 6,615 6,643 6,874
mvpa_b1_weekly_mean 276.0 (233.8) 283.5 (229.2) 299.6 (242.3) 290.7 (241.1) 277.0 (233.3) 201.9 (193.6) 191.4 (180.6) 198.2 (219.6) 193.6 (208.6) NA (NA)
    Unknown 53,936 4,649 5,336 5,265 5,302 6,624 6,628 6,615 6,643 6,874
mvpa_b10_weekly_mean 143.8 (189.0) 145.0 (183.6) 159.5 (198.7) 154.8 (197.5) 144.3 (191.4) 91.1 (138.7) 94.4 (148.5) 100.6 (167.7) 105.3 (178.2) NA (NA)
    Unknown 53,936 4,649 5,336 5,265 5,302 6,624 6,628 6,615 6,643 6,874
1 n (%); Mean (SD)

4. Comparación de grupos en cada tiempo

tbl_grupos_por_tiempo <- spssLong_f %>%
  select(all_of(vars_a_incluir), Tiempo, grupo_int) %>%
  tbl_strata(
    strata = Tiempo,
    .tbl_fun = ~ .x %>%
      tbl_summary(
        by = grupo_int,
        type = all_continuous() ~ "continuous",
        statistic = all_continuous() ~ "{mean} ({sd})",
        digits = all_continuous() ~ c(1, 1),
        missing = "ifany"
      ) %>%
      add_p() %>%      # Añade p-valor de la comparación
      bold_labels()
  )

tbl_grupos_por_tiempo
Characteristic
0
0.5
1
2
3
4
5
6
7
A
N = 3,468
1
B
N = 3,406
1
p-value2 A
N = 3,468
1
B
N = 3,406
1
p-value2 A
N = 3,468
1
B
N = 3,406
1
p-value2 A
N = 3,468
1
B
N = 3,406
1
p-value2 A
N = 3,468
1
B
N = 3,406
1
p-value2 A
N = 3,468
1
B
N = 3,406
1
p-value2 A
N = 3,468
1
B
N = 3,406
1
p-value2 A
N = 3,468
1
B
N = 3,406
1
p-value2 A
N = 3,468
1
B
N = 3,406
1
p-value2
critval4d


























    1 3,468 (100%) 3,406 (100%)
3,468 (100%) 3,406 (100%)
3,468 (100%) 3,406 (100%)
3,468 (100%) 3,406 (100%)
3,468 (100%) 3,406 (100%)
3,468 (100%) 3,406 (100%)
3,468 (100%) 3,406 (100%)
3,468 (100%) 3,406 (100%)
3,468 (100%) 3,406 (100%)
n_daily


























    3 3,468 (100%) 3,406 (100%)
3,468 (100%) 3,406 (100%)
3,468 (100%) 3,406 (100%)
3,468 (100%) 3,406 (100%)
3,468 (100%) 3,406 (100%)
3,468 (100%) 3,406 (100%)
3,468 (100%) 3,406 (100%)
3,468 (100%) 3,406 (100%)
3,468 (100%) 3,406 (100%)
imc 32.6 (3.5) 32.6 (3.4) 0.7 32.3 (3.6) 31.4 (3.5) <0.001 32.3 (3.7) 31.2 (3.6) <0.001 32.3 (3.7) 31.3 (3.6) <0.001 32.0 (4.0) 31.2 (3.4) 0.2 32.1 (4.1) 31.4 (3.4) 0.3 31.9 (4.2) 31.4 (3.7) 0.6 31.4 (4.3) 31.7 (4.2) 0.5 31.7 (4.2) 31.9 (3.9) 0.4
    Unknown 1 2
156 163
141 186
214 233
3,327 3,259
3,331 3,258
3,331 3,263
3,336 3,273
3,347 3,281
peso 86.5 (13.0) 86.7 (13.0) 0.5 85.8 (13.1) 83.4 (12.8) <0.001 85.6 (13.3) 82.9 (12.9) <0.001 85.7 (13.4) 83.2 (13.1) <0.001 83.4 (13.2) 81.1 (11.8) 0.3 83.7 (13.5) 81.6 (12.4) 0.3 82.6 (13.1) 81.3 (12.6) 0.5 81.2 (12.9) 81.5 (12.6) 0.6 82.1 (13.3) 81.7 (12.8) >0.9
    Unknown 1 2
156 163
141 186
214 233
3,327 3,259
3,329 3,258
3,330 3,263
3,336 3,273
3,346 3,281
cintura 107.6 (9.7) 107.6 (9.6) 0.9 106.6 (9.9) 103.8 (9.8) <0.001 106.4 (10.0) 103.1 (9.9) <0.001 106.8 (10.2) 103.5 (10.2) <0.001 104.7 (10.0) 103.2 (9.4) 0.2 105.2 (10.0) 102.7 (9.8) 0.030 104.3 (11.7) 102.8 (10.0) 0.4 104.2 (9.7) 103.6 (10.3) 0.5 103.5 (10.0) 105.2 (10.7) 0.2
    Unknown 1 2
279 295
281 368
390 465
3,332 3,263
3,334 3,264
3,332 3,269
3,340 3,276
3,349 3,285
temps_lig 192.7 (243.3) 187.6 (233.1) 0.9 195.0 (233.1) 198.5 (235.2) 0.7 199.3 (232.7) 209.7 (239.1) 0.10 211.6 (231.2) 229.7 (255.2) 0.074 151.9 (198.8) 342.5 (272.8) <0.001 178.0 (210.2) 278.4 (262.9) <0.001 141.7 (180.8) 202.7 (227.0) 0.013 146.9 (185.6) 233.1 (252.5) 0.008 205.8 (222.4) 272.6 (276.7) 0.11
    Unknown


252 273
239 326
360 427
3,330 3,258
3,330 3,260
3,330 3,264
3,336 3,273
3,347 3,281
temps_mod 202.4 (311.4) 175.4 (281.1) 0.002 217.1 (338.9) 266.0 (334.4) <0.001 212.3 (330.8) 270.3 (337.6) <0.001 202.1 (316.0) 260.4 (346.4) <0.001 84.2 (183.9) 89.0 (238.5) 0.5 115.3 (236.4) 145.9 (268.0) 0.3 156.0 (260.3) 248.9 (438.5) 0.12 152.9 (267.4) 151.3 (269.8) 0.8 119.8 (273.8) 148.4 (452.3) 0.4
    Unknown


252 273
239 326
360 427
3,330 3,258
3,330 3,260
3,330 3,264
3,336 3,273
3,347 3,281
temps_int 92.6 (161.1) 88.7 (160.4) 0.5 94.8 (162.4) 114.6 (175.7) <0.001 100.3 (163.8) 127.2 (186.2) <0.001 98.8 (168.2) 126.2 (190.1) <0.001 99.2 (150.2) 114.6 (190.3) >0.9 81.4 (143.3) 94.8 (154.7) 0.4 69.7 (109.6) 116.2 (195.0) 0.083 66.0 (111.1) 105.2 (176.0) 0.3 96.7 (146.0) 87.8 (193.6) 0.2
    Unknown


252 273
239 326
360 427
3,330 3,258
3,330 3,260
3,330 3,264
3,336 3,273
3,347 3,281
lpa_b1_weekly_mean 17.6 (7.6) 18.1 (7.6) 0.10 18.4 (7.5) 18.2 (7.5) >0.9 17.8 (7.6) 18.0 (7.8) 0.5 17.4 (7.6) 18.0 (7.9) 0.11 16.2 (7.5) 16.8 (7.6) 0.5 16.4 (8.2) 15.9 (6.6) 0.9 15.7 (7.7) 17.0 (8.9) 0.4 15.0 (7.2) 16.4 (8.1) 0.3 NA (NA) NA (NA)
    Unknown 2,497 2,150
2,845 2,491
2,795 2,470
2,815 2,487
3,338 3,286
3,342 3,286
3,338 3,277
3,351 3,292
3,468 3,406
mvpa_b1_weekly_mean 273.7 (225.3) 291.2 (231.9) 0.053 273.6 (208.8) 317.4 (261.4) 0.013 251.2 (205.3) 319.1 (260.3) <0.001 246.4 (201.2) 298.8 (251.5) <0.001 180.4 (175.8) 225.3 (209.3) 0.032 180.8 (178.4) 202.5 (183.1) 0.2 176.9 (190.9) 219.7 (244.1) 0.3 172.5 (180.5) 215.4 (232.7) 0.2 NA (NA) NA (NA)
    Unknown 2,497 2,152
2,845 2,491
2,795 2,470
2,815 2,487
3,338 3,286
3,342 3,286
3,338 3,277
3,351 3,292
3,468 3,406
mvpa_b10_weekly_mean 137.1 (180.6) 151.0 (185.7) 0.064 132.3 (158.4) 178.0 (220.2) 0.002 123.2 (157.5) 177.5 (219.1) <0.001 117.7 (152.3) 163.2 (213.0) <0.001 68.7 (103.4) 115.5 (165.9) 0.011 83.2 (137.7) 106.2 (158.8) 0.3 81.0 (135.1) 120.3 (193.6) 0.5 85.8 (139.0) 125.3 (209.8) 0.3 NA (NA) NA (NA)
    Unknown 2,497 2,152
2,845 2,491
2,795 2,470
2,815 2,487
3,338 3,286
3,342 3,286
3,338 3,277
3,351 3,292
3,468 3,406
1 n (%); Mean (SD)
2 Wilcoxon rank sum test

5. Gráficos de evolución de la media por grupo

5.1 Variables de Acelerometría

# LPA (lpa_b1_weekly_mean)
plot_lpa <- spssLong_f %>%
  group_by(Tiempo, grupo_int) %>%
  summarise(
    mean_lpa = mean(lpa_b1_weekly_mean, na.rm = TRUE),
    sd_lpa   = sd(lpa_b1_weekly_mean, na.rm = TRUE),
    n        = n()
  ) %>%
  mutate(se_lpa = sd_lpa / sqrt(n)) %>%
  ggplot(aes(x = Tiempo, y = mean_lpa, color = grupo_int)) +
  geom_line() +
  geom_point() +
  geom_errorbar(aes(ymin = mean_lpa - se_lpa, ymax = mean_lpa + se_lpa), 
                width = 0.1) +
  theme_minimal() +
  labs(title = "Evolución de LPA (acelerometría)",
       x = "Tiempo (años)",
       y = "Min/sem LPA")

# MVPA (mvpa_b1_weekly_mean)
plot_mvpa <- spssLong_f %>%
  group_by(Tiempo, grupo_int) %>%
  summarise(
    mean_mvpa = mean(mvpa_b1_weekly_mean, na.rm = TRUE),
    sd_mvpa   = sd(mvpa_b1_weekly_mean, na.rm = TRUE),
    n         = n()
  ) %>%
  mutate(se_mvpa = sd_mvpa / sqrt(n)) %>%
  ggplot(aes(x = Tiempo, y = mean_mvpa, color = grupo_int)) +
  geom_line() +
  geom_point() +
  geom_errorbar(aes(ymin = mean_mvpa - se_mvpa, ymax = mean_mvpa + se_mvpa), 
                width = 0.1) +
  theme_minimal() +
  labs(title = "Evolución de MVPA (acelerometría)",
       x = "Tiempo (años)",
       y = "Min/sem MVPA")

# VPA (mvpa_b10_weekly_mean)
plot_mvpa10 <- spssLong_f %>%
  group_by(Tiempo, grupo_int) %>%
  summarise(
    mean_mvpa10 = mean(mvpa_b10_weekly_mean, na.rm = TRUE),
    sd_mvpa10   = sd(mvpa_b10_weekly_mean, na.rm = TRUE),
    n           = n()
  ) %>%
  mutate(se_mvpa10 = sd_mvpa10 / sqrt(n)) %>%
  ggplot(aes(x = Tiempo, y = mean_mvpa10, color = grupo_int)) +
  geom_line() +
  geom_point() +
  geom_errorbar(aes(ymin = mean_mvpa10 - se_mvpa10, ymax = mean_mvpa10 + se_mvpa10), 
                width = 0.1) +
  theme_minimal() +
  labs(title = "Evolución de VPA (acelerometría)",
       x = "Tiempo (años)",
       y = "Min/sem VPA")

# Combinamos los tres gráficos
(plot_lpa / plot_mvpa / plot_mvpa10)

5.2 Variables antropométricas (IMC, peso, cintura)

# IMC
plot_imc <- spssLong_f %>%
  group_by(Tiempo, grupo_int) %>%
  summarise(
    mean_imc = mean(imc, na.rm = TRUE),
    sd_imc   = sd(imc, na.rm = TRUE),
    n        = n()
  ) %>%
  mutate(se_imc = sd_imc / sqrt(n)) %>%
  ggplot(aes(x = Tiempo, y = mean_imc, color = grupo_int)) +
  geom_line() +
  geom_point() +
  geom_errorbar(aes(ymin = mean_imc - se_imc, ymax = mean_imc + se_imc),
                width = 0.1) +
  theme_minimal() +
  labs(title = "Evolución del IMC",
       x = "Tiempo (años)",
       y = "IMC (kg/m^2)")

# Peso
plot_peso <- spssLong_f %>%
  group_by(Tiempo, grupo_int) %>%
  summarise(
    mean_peso = mean(peso, na.rm = TRUE),
    sd_peso   = sd(peso, na.rm = TRUE),
    n         = n()
  ) %>%
  mutate(se_peso = sd_peso / sqrt(n)) %>%
  ggplot(aes(x = Tiempo, y = mean_peso, color = grupo_int)) +
  geom_line() +
  geom_point() +
  geom_errorbar(aes(ymin = mean_peso - se_peso, ymax = mean_peso + se_peso),
                width = 0.1) +
  theme_minimal() +
  labs(title = "Evolución del peso",
       x = "Tiempo (años)",
       y = "Peso (kg)")

# Cintura
plot_cintura <- spssLong_f %>%
  group_by(Tiempo, grupo_int) %>%
  summarise(
    mean_cintura = mean(cintura, na.rm = TRUE),
    sd_cintura   = sd(cintura, na.rm = TRUE),
    n            = n()
  ) %>%
  mutate(se_cintura = sd_cintura / sqrt(n)) %>%
  ggplot(aes(x = Tiempo, y = mean_cintura, color = grupo_int)) +
  geom_line() +
  geom_point() +
  geom_errorbar(aes(ymin = mean_cintura - se_cintura, ymax = mean_cintura + se_cintura),
                width = 0.1) +
  theme_minimal() +
  labs(title = "Evolución de la cintura",
       x = "Tiempo (años)",
       y = "Perímetro cintura (cm)")

# Combinamos en una sola visualización
(plot_imc / plot_peso / plot_cintura)

5.3 Variables de cuestionario (temps_lig, temps_mod, temps_int)

# LPA (temps_lig)
plot_temps_lig <- spssLong_f %>%
  group_by(Tiempo, grupo_int) %>%
  summarise(
    mean_tl = mean(temps_lig, na.rm = TRUE),
    sd_tl   = sd(temps_lig, na.rm = TRUE),
    n       = n()
  ) %>%
  mutate(se_tl = sd_tl / sqrt(n)) %>%
  ggplot(aes(x = Tiempo, y = mean_tl, color = grupo_int)) +
  geom_line() +
  geom_point() +
  geom_errorbar(aes(ymin = mean_tl - se_tl, ymax = mean_tl + se_tl),
                width = 0.1) +
  theme_minimal() +
  labs(title = "Evolución de LPA (cuestionario)",
       x = "Tiempo (años)",
       y = "Min/sem LPA")

# MVPA (temps_mod)
plot_temps_mod <- spssLong_f %>%
  group_by(Tiempo, grupo_int) %>%
  summarise(
    mean_tm = mean(temps_mod, na.rm = TRUE),
    sd_tm   = sd(temps_mod, na.rm = TRUE),
    n       = n()
  ) %>%
  mutate(se_tm = sd_tm / sqrt(n)) %>%
  ggplot(aes(x = Tiempo, y = mean_tm, color = grupo_int)) +
  geom_line() +
  geom_point() +
  geom_errorbar(aes(ymin = mean_tm - se_tm, ymax = mean_tm + se_tm),
                width = 0.1) +
  theme_minimal() +
  labs(title = "Evolución de MVPA (cuestionario)",
       x = "Tiempo (años)",
       y = "Min/sem MVPA")

# VPA (temps_int)
plot_temps_int <- spssLong_f %>%
  group_by(Tiempo, grupo_int) %>%
  summarise(
    mean_ti = mean(temps_int, na.rm = TRUE),
    sd_ti   = sd(temps_int, na.rm = TRUE),
    n       = n()
  ) %>%
  mutate(se_ti = sd_ti / sqrt(n)) %>%
  ggplot(aes(x = Tiempo, y = mean_ti, color = grupo_int)) +
  geom_line() +
  geom_point() +
  geom_errorbar(aes(ymin = mean_ti - se_ti, ymax = mean_ti + se_ti),
                width = 0.1) +
  theme_minimal() +
  labs(title = "Evolución de VPA (cuestionario)",
       x = "Tiempo (años)",
       y = "Min/sem VPA")

# Combinamos los tres gráficos en verical

(plot_temps_lig / plot_temps_mod / plot_temps_int)

5.4 Gráficos de evolución de la media (solo variables de acelerometría)

# LPA
plot_lpa <- spssLong_f %>%
  group_by(Tiempo, grupo_int) %>%
  summarise(
    mean_lpa = mean(lpa_b1_weekly_mean, na.rm = TRUE),
    sd_lpa   = sd(lpa_b1_weekly_mean, na.rm = TRUE),
    n        = n()
  ) %>%
  mutate(se_lpa = sd_lpa / sqrt(n)) %>%
  ggplot(aes(x = Tiempo, y = mean_lpa, color = grupo_int)) +
  geom_line() +
  geom_point() +
  geom_errorbar(aes(ymin = mean_lpa - se_lpa, ymax = mean_lpa + se_lpa),
                width = 0.1) +
  theme_minimal() +
  labs(title = "Evolución de LPA (acelerometría)",
       x = "Tiempo (años)",
       y = "Min/sem LPA")

# MVPA
plot_mvpa <- spssLong_f %>%
  group_by(Tiempo, grupo_int) %>%
  summarise(
    mean_mvpa = mean(mvpa_b1_weekly_mean, na.rm = TRUE),
    sd_mvpa   = sd(mvpa_b1_weekly_mean, na.rm = TRUE),
    n         = n()
  ) %>%
  mutate(se_mvpa = sd_mvpa / sqrt(n)) %>%
  ggplot(aes(x = Tiempo, y = mean_mvpa, color = grupo_int)) +
  geom_line() +
  geom_point() +
  geom_errorbar(aes(ymin = mean_mvpa - se_mvpa, ymax = mean_mvpa + se_mvpa),
                width = 0.1) +
  theme_minimal() +
  labs(title = "Evolución de MVPA (acelerometría)",
       x = "Tiempo (años)",
       y = "Min/sem MVPA")

# VPA
plot_mvpa10 <- spssLong_f %>%
  group_by(Tiempo, grupo_int) %>%
  summarise(
    mean_mvpa10 = mean(mvpa_b10_weekly_mean, na.rm = TRUE),
    sd_mvpa10   = sd(mvpa_b10_weekly_mean, na.rm = TRUE),
    n           = n()
  ) %>%
  mutate(se_mvpa10 = sd_mvpa10 / sqrt(n)) %>%
  ggplot(aes(x = Tiempo, y = mean_mvpa10, color = grupo_int)) +
  geom_line() +
  geom_point() +
  geom_errorbar(aes(ymin = mean_mvpa10 - se_mvpa10, ymax = mean_mvpa10 + se_mvpa10),
                width = 0.1) +
  theme_minimal() +
  labs(title = "Evolución de VPA (acelerometría)",
       x = "Tiempo (años)",
       y = "Min/sem VPA")

# Combinamos los tres gráficos en una cuadrícula con patchwork
(plot_lpa / plot_mvpa / plot_mvpa10)

5.5 Correlaciones entre cuestionario y acelerometría

## 1. Definir pares de variables (Cuestionario vs. Acelerometría)

pairs <- tibble::tribble(
  ~var_cuestionario, ~var_acelerometria,
  "temps_lig",       "lpa_b1_weekly_mean",
  "temps_mod",       "mvpa_b1_weekly_mean",
  "temps_int",       "mvpa_b10_weekly_mean"
)


## 2. Calcular correlaciones para cada Tiempo

library(dplyr)
library(purrr)

cor_results <- spssLong_f %>%
  # Filtramos los tiempos de interés (0, 0.5, 1, 2) 
  # Si el dataset ya sólo contiene esos tiempos, no es necesario filtrar.
  filter(Tiempo %in% c(0, 0.5, 1, 2,3,4,5,6)) %>%
  # Separamos el data frame por cada nivel de Tiempo
  group_by(Tiempo) %>%
  group_split() %>%
  # Para cada subset (cada tiempo), calculamos correlaciones para cada par
  map_dfr(~ {
    # .x es el subset de datos para un valor concreto de Tiempo
    # Extraemos su valor de Tiempo
    t_val <- unique(.x$Tiempo)
    
    # Iteramos sobre cada fila de 'pairs'
    map_dfr(1:nrow(pairs), function(i) {
      varQ <- pairs$var_cuestionario[i]
      varA <- pairs$var_acelerometria[i]
      
      # Subconjunto con las dos variables de interés, eliminando missing
      subdf <- .x %>%
        select(all_of(varQ), all_of(varA)) %>%
        drop_na()
      
      # Correlación Pearson
      test_pearson <- cor.test(subdf[[varQ]], subdf[[varA]], method = "pearson")
      # Correlación Spearman
      test_spearman <- cor.test(subdf[[varQ]], subdf[[varA]], method = "spearman")
      
      # Devolvemos un data frame con las estadísticas de interés
      tibble(
        Tiempo                  = t_val,
        Variable_cuestionario   = varQ,
        Variable_acelerometria  = varA,
        Pearson_r               = test_pearson$estimate,
        Pearson_p               = test_pearson$p.value,
        Spearman_r              = test_spearman$estimate,
        Spearman_p              = test_spearman$p.value
      )
    })
  })


## 3. Mostrar el resultado en una tabla

# Ajustamos el redondeo y convertimos p-valores a un formato legible
cor_results_tidy <- cor_results %>%
  mutate(
    Pearson_r   = round(Pearson_r,  2),
    Spearman_r  = round(Spearman_r, 2),
    Pearson_p   = ifelse(Pearson_p < 0.001, "<0.001", round(Pearson_p,  3)),
    Spearman_p  = ifelse(Spearman_p < 0.001, "<0.001", round(Spearman_p, 3))
  )

# Usamos kable para mostrar en formato tabular simple (puedes reemplazar por gt, DT o gtsummary)
knitr::kable(
  cor_results_tidy,
  caption = "Correlaciones (Pearson y Spearman) Cuestionario vs. Acelerometría, separadas por Tiempo.",
  align = "c"
)
Correlaciones (Pearson y Spearman) Cuestionario vs. Acelerometría, separadas por Tiempo.
Tiempo Variable_cuestionario Variable_acelerometria Pearson_r Pearson_p Spearman_r Spearman_p
0.0 temps_lig lpa_b1_weekly_mean -0.01 0.62 -0.04 0.047
0.0 temps_mod mvpa_b1_weekly_mean 0.25 <0.001 0.31 <0.001
0.0 temps_int mvpa_b10_weekly_mean 0.08 <0.001 0.09 <0.001
0.5 temps_lig lpa_b1_weekly_mean 0.05 0.069 0.03 0.263
0.5 temps_mod mvpa_b1_weekly_mean 0.30 <0.001 0.37 <0.001
0.5 temps_int mvpa_b10_weekly_mean 0.12 <0.001 0.15 <0.001
1.0 temps_lig lpa_b1_weekly_mean -0.01 0.704 -0.02 0.369
1.0 temps_mod mvpa_b1_weekly_mean 0.33 <0.001 0.39 <0.001
1.0 temps_int mvpa_b10_weekly_mean 0.13 <0.001 0.16 <0.001
2.0 temps_lig lpa_b1_weekly_mean -0.01 0.578 -0.03 0.208
2.0 temps_mod mvpa_b1_weekly_mean 0.32 <0.001 0.36 <0.001
2.0 temps_int mvpa_b10_weekly_mean 0.14 <0.001 0.20 <0.001
3.0 temps_lig lpa_b1_weekly_mean 0.06 0.35 0.08 0.221
3.0 temps_mod mvpa_b1_weekly_mean 0.26 <0.001 0.23 <0.001
3.0 temps_int mvpa_b10_weekly_mean 0.05 0.394 0.15 0.018
4.0 temps_lig lpa_b1_weekly_mean 0.14 0.029 0.10 0.121
4.0 temps_mod mvpa_b1_weekly_mean 0.39 <0.001 0.37 <0.001
4.0 temps_int mvpa_b10_weekly_mean 0.07 0.256 0.06 0.313
5.0 temps_lig lpa_b1_weekly_mean 0.09 0.129 0.06 0.366
5.0 temps_mod mvpa_b1_weekly_mean 0.35 <0.001 0.44 <0.001
5.0 temps_int mvpa_b10_weekly_mean 0.18 0.004 0.21 <0.001
6.0 temps_lig lpa_b1_weekly_mean 0.13 0.058 0.04 0.583
6.0 temps_mod mvpa_b1_weekly_mean 0.43 <0.001 0.45 <0.001
6.0 temps_int mvpa_b10_weekly_mean 0.15 0.024 0.21 0.002