library(dplyr)
library(tidyr)
library(ggplot2)
library(tibble)
library(FactoMineR)
library(factoextra)


Paises = c("USA", "China", "Russian Federation", "Japan", "Brazil", "Australia",
                                             "Canada","Germany", "Spain", "France", "Italy", "Poland", "Sweden",
                                             "Netherlands","Portugal", "Greece", "Ireland", "Austria", "Belgium", 
                                             "Croatia", "Hungary","Romania", "Finland", "Denmark", "Czechia",
                                             "Estonia", "Slovakia", "Slovenia","Lithuania", "Latvia", "Bulgaria",
                                             "Luxembourg")

# filtrado de paises
COMEXP2 = COMEXP[COMEXP$country_or_area %in% Paises,]
COMIMP2 = COMIMP[COMIMP$country_or_area %in% Paises,]

EU_25 <- c("Germany", "Spain", "France", "Italy", "Poland", "Sweden",
           "Netherlands","Portugal", "Greece", "Ireland", "Austria", "Belgium", 
           "Croatia", "Hungary","Romania", "Finland", "Denmark", "Czechia",
           "Estonia", "Slovakia", "Slovenia","Lithuania", "Latvia", "Bulgaria", "Luxembourg")

# Crear nueva columna "grupo_mod"
COMEXP2 <- COMEXP2 %>%
  mutate(grupo_mod = ifelse(country_or_area %in% EU_25, "EU_25", country_or_area))

# Conversión de columnas numéricas
COMEXP2 <- COMEXP2 %>%
  mutate(
    trade_usd = as.numeric(trade_usd),
    year = as.numeric(year)
  )

COMEXP_wide <- COMEXP2 %>%
  group_by(grupo_mod, year, category) %>%
  summarise(trade_usd = sum(trade_usd, na.rm = TRUE), .groups = "drop") %>%
  pivot_wider(
    names_from = category,
    values_from = trade_usd,
    values_fill = 0
  )


# SEPARACION POR PERIODOS
PRECRISIS_EXP = COMEXP_wide[COMEXP_wide$year %in% c(2006:2008),]
CRISIS_EXP = COMEXP_wide[COMEXP_wide$year %in% c(2009:2011),]
POSTCRISIS_EXP = COMEXP_wide[COMEXP_wide$year %in% c(2012:2016),]

#Función PCA
HACER_PCA <- function(df, titulo) {
  # Detectar y eliminar columna de identificación (grupo_mod o country_or_area)
  id_cols <- c("country_or_area", "grupo_mod", "year")
  df <- df %>% select(-any_of(id_cols))

  # Ejecutar PCA
  res.pca <- PCA(scale(df), graph = FALSE)

  # Visualizaciones
  print(fviz_pca_var(res.pca, axes = c(1,2), title = titulo))
  print(fviz_contrib(res.pca, choice = "var", axes = 1, top = 10, 
                     title = paste("Contribución al PC1 -", titulo)))
  print(fviz_contrib(res.pca, choice = "var", axes = 2, top = 10, 
                     title = paste("Contribución al PC2 -", titulo)))

  # Mostrar tabla de contribuciones combinadas PC1+PC2
  contrib_total <- rowSums(res.pca$var$contrib[, 1:2])
  top10 = (sort(contrib_total, decreasing = TRUE)[1:10])
  print(knitr::kable(top10))

  return(list(res.pca, names(top10)))
}


# Aplicar a cada periodo
pca_pre <- HACER_PCA(PRECRISIS_EXP, "Exportaciones 2006–2008 (Pre-crisis)")

## 
## 
## |                                                      |        x|
## |:-----------------------------------------------------|--------:|
## |63_other_made_textile_articles_sets_worn_clothing_etc | 4.955416|
## |52_cotton                                             | 4.939733|
## |46_manufactures_of_plaiting_material_basketwork_etc   | 4.870621|
## |67_bird_skin_feathers_artificial_flowers_human_hair   | 4.807887|
## |55_manmade_staple_fibres                              | 4.704015|
## |66_umbrellas_walking_sticks_seat_sticks_whips_etc     | 4.573384|
## |54_manmade_filaments                                  | 4.548866|
## |96_miscellaneous_manufactured_articles                | 4.267263|
## |82_tools_implements_cutlery_etc_of_base_metal         | 4.204634|
## |95_toys_games_sports_requisites                       | 3.917670|
pca_cri <- HACER_PCA(CRISIS_EXP, "Exportaciones 2009–2011 (Crisis)")

## 
## 
## |                                                      |        x|
## |:-----------------------------------------------------|--------:|
## |63_other_made_textile_articles_sets_worn_clothing_etc | 4.120717|
## |52_cotton                                             | 4.052948|
## |67_bird_skin_feathers_artificial_flowers_human_hair   | 4.029999|
## |54_manmade_filaments                                  | 3.983768|
## |46_manufactures_of_plaiting_material_basketwork_etc   | 3.975048|
## |55_manmade_staple_fibres                              | 3.960142|
## |66_umbrellas_walking_sticks_seat_sticks_whips_etc     | 3.929465|
## |82_tools_implements_cutlery_etc_of_base_metal         | 3.730290|
## |96_miscellaneous_manufactured_articles                | 3.722950|
## |50_silk                                               | 3.332857|
pca_post <- HACER_PCA(POSTCRISIS_EXP, "Exportaciones 2012–2016 (Post-crisis)")

## 
## 
## |                                                      |        x|
## |:-----------------------------------------------------|--------:|
## |63_other_made_textile_articles_sets_worn_clothing_etc | 3.611137|
## |67_bird_skin_feathers_artificial_flowers_human_hair   | 3.578768|
## |54_manmade_filaments                                  | 3.571676|
## |52_cotton                                             | 3.552475|
## |55_manmade_staple_fibres                              | 3.502750|
## |66_umbrellas_walking_sticks_seat_sticks_whips_etc     | 3.476160|
## |46_manufactures_of_plaiting_material_basketwork_etc   | 3.472516|
## |82_tools_implements_cutlery_etc_of_base_metal         | 3.377921|
## |96_miscellaneous_manufactured_articles                | 3.354027|
## |70_glass_and_glassware                                | 3.294894|

PCA importación

# --- PASO 1: preparar y agrupar COMIMP ---
COMIMP_mod <- COMIMP2 %>%
  mutate(
    trade_usd = as.numeric(trade_usd),
    year = as.numeric(year),
    grupo_mod = ifelse(country_or_area %in% EU_25, "EU_25", country_or_area)
  ) %>%
  group_by(grupo_mod, year, category) %>%
  summarise(trade_usd = sum(trade_usd, na.rm = TRUE), .groups = "drop") %>%
  pivot_wider(names_from = category, values_from = trade_usd, values_fill = 0)

# --- PASO 2: separar por periodos ---
PRECRISIS_IMP <- COMIMP_mod %>% filter(year %in% 2006:2008)
CRISIS_IMP    <- COMIMP_mod %>% filter(year %in% 2009:2011)
POSTCRISIS_IMP<- COMIMP_mod %>% filter(year %in% 2012:2016)

# --- PASO 4: aplicar PCA ---
pca_imp_pre  <- HACER_PCA(PRECRISIS_IMP, "PCA Importaciones Pre-Crisis (2006–2008)")

## 
## 
## |                                                      |        x|
## |:-----------------------------------------------------|--------:|
## |52_cotton                                             | 7.813841|
## |55_manmade_staple_fibres                              | 7.640172|
## |40_rubber_and_articles_thereof                        | 6.415096|
## |25_salt_sulphur_earth_stone_plaster_lime_and_cement   | 5.933868|
## |54_manmade_filaments                                  | 5.810276|
## |12_oil_seed_oleagic_fruits_grain_seed_fruit_etc_ne    | 5.622188|
## |26_ores_slag_and_ash                                  | 5.496725|
## |03_fish_crustaceans_molluscs_aquatic_invertebrates_ne | 5.180095|
## |44_wood_and_articles_of_wood_wood_charcoal            | 4.430021|
## |74_copper_and_articles_thereof                        | 4.127749|
pca_imp_cri  <- HACER_PCA(CRISIS_IMP,    "PCA Importaciones Crisis (2009–2011)")

## 
## 
## |                                                      |        x|
## |:-----------------------------------------------------|--------:|
## |52_cotton                                             | 6.738719|
## |55_manmade_staple_fibres                              | 6.576824|
## |40_rubber_and_articles_thereof                        | 6.074507|
## |26_ores_slag_and_ash                                  | 5.752115|
## |12_oil_seed_oleagic_fruits_grain_seed_fruit_etc_ne    | 5.726721|
## |74_copper_and_articles_thereof                        | 5.292766|
## |54_manmade_filaments                                  | 5.282262|
## |25_salt_sulphur_earth_stone_plaster_lime_and_cement   | 5.275753|
## |44_wood_and_articles_of_wood_wood_charcoal            | 5.104751|
## |03_fish_crustaceans_molluscs_aquatic_invertebrates_ne | 4.911336|
pca_imp_post <- HACER_PCA(POSTCRISIS_IMP,"PCA Importaciones Post-Crisis (2012–2016)")

## 
## 
## |                                                      |        x|
## |:-----------------------------------------------------|--------:|
## |55_manmade_staple_fibres                              | 5.748922|
## |52_cotton                                             | 5.647229|
## |40_rubber_and_articles_thereof                        | 5.444360|
## |25_salt_sulphur_earth_stone_plaster_lime_and_cement   | 5.375902|
## |12_oil_seed_oleagic_fruits_grain_seed_fruit_etc_ne    | 5.366515|
## |70_glass_and_glassware                                | 5.308241|
## |26_ores_slag_and_ash                                  | 5.234925|
## |44_wood_and_articles_of_wood_wood_charcoal            | 5.172552|
## |03_fish_crustaceans_molluscs_aquatic_invertebrates_ne | 4.806955|
## |74_copper_and_articles_thereof                        | 4.770071|