Vamos a leer las librerias necesarias para seguir con el análisis de datos y las bases sobre las que vamos a trabajar.
library(readxl);
library(dplyr);
library(writexl);
library(knitr);
library(corrplot);
IE <- read_excel("union_europea_IE.xlsx", col_types = 'text');
PIB <- read_excel("union_europea_PIB.xlsx", col_types = 'text');
Se muestran los datos originales sobre los que vamos a trabajar.
| DATAFLOW | LAST UPDATE | freq | unit | nace_r2 | na_item | geo | TIME_PERIOD | OBS_VALUE | OBS_FLAG | CONF_STATUS |
|---|---|---|---|---|---|---|---|---|---|---|
| ESTAT:NAMA_10_A10(1.0) | 27/02/25 23:00:00 | Annual | Chain linked volumes (2005), million euro | Agriculture, forestry and fishing | Value added, gross | Albania | 2019 | 2086.6 | b | NA |
| ESTAT:NAMA_10_A10(1.0) | 27/02/25 23:00:00 | Annual | Chain linked volumes (2005), million euro | Agriculture, forestry and fishing | Value added, gross | Albania | 2020 | 2124.1 | NA | NA |
| ESTAT:NAMA_10_A10(1.0) | 27/02/25 23:00:00 | Annual | Chain linked volumes (2005), million euro | Agriculture, forestry and fishing | Value added, gross | Albania | 2021 | 2088.3000000000002 | NA | NA |
| ESTAT:NAMA_10_A10(1.0) | 27/02/25 23:00:00 | Annual | Chain linked volumes (2005), million euro | Agriculture, forestry and fishing | Value added, gross | Albania | 2022 | 1987.6 | NA | NA |
| ESTAT:NAMA_10_A10(1.0) | 27/02/25 23:00:00 | Annual | Chain linked volumes (2005), million euro | Agriculture, forestry and fishing | Value added, gross | Albania | 2023 | 1951.3 | p | NA |
| ESTAT:NAMA_10_A10(1.0) | 27/02/25 23:00:00 | Annual | Chain linked volumes (2005), million euro | Agriculture, forestry and fishing | Value added, gross | Austria | 1995 | 2953.8 | NA | NA |
| DATAFLOW | LAST UPDATE | freq | unit | na_item | geo | TIME_PERIOD | OBS_VALUE | OBS_FLAG | CONF_STATUS |
|---|---|---|---|---|---|---|---|---|---|
| ESTAT:NAMA_10_EXI(1.0) | 27/02/25 23:00:00 | Annual | Chain linked volumes (2005), million euro | Exports of goods and services | Albania | 2019 | 3678.6 | b | NA |
| ESTAT:NAMA_10_EXI(1.0) | 27/02/25 23:00:00 | Annual | Chain linked volumes (2005), million euro | Exports of goods and services | Albania | 2020 | 2658.7 | NA | NA |
| ESTAT:NAMA_10_EXI(1.0) | 27/02/25 23:00:00 | Annual | Chain linked volumes (2005), million euro | Exports of goods and services | Albania | 2021 | 4043.8 | NA | NA |
| ESTAT:NAMA_10_EXI(1.0) | 27/02/25 23:00:00 | Annual | Chain linked volumes (2005), million euro | Exports of goods and services | Albania | 2022 | 4733 | NA | NA |
| ESTAT:NAMA_10_EXI(1.0) | 27/02/25 23:00:00 | Annual | Chain linked volumes (2005), million euro | Exports of goods and services | Albania | 2023 | 5180.3999999999996 | p | NA |
| ESTAT:NAMA_10_EXI(1.0) | 27/02/25 23:00:00 | Annual | Chain linked volumes (2005), million euro | Exports of goods and services | Austria | 1995 | 63483.8 | NA | NA |
Antes de empezar con el análisis de datos ya sabemos que vamos a descartar unas variables de la base de datos que no interesan como son: DATAFLOW, LAST_UPDATE, freq, unit, OBS_FLAG y CONF_STATUS
PIB2 <- PIB[, 4:9];
knitr::kable(head(PIB2), caption= 'Variables empleadas PIB');
| unit | nace_r2 | na_item | geo | TIME_PERIOD | OBS_VALUE |
|---|---|---|---|---|---|
| Chain linked volumes (2005), million euro | Agriculture, forestry and fishing | Value added, gross | Albania | 2019 | 2086.6 |
| Chain linked volumes (2005), million euro | Agriculture, forestry and fishing | Value added, gross | Albania | 2020 | 2124.1 |
| Chain linked volumes (2005), million euro | Agriculture, forestry and fishing | Value added, gross | Albania | 2021 | 2088.3000000000002 |
| Chain linked volumes (2005), million euro | Agriculture, forestry and fishing | Value added, gross | Albania | 2022 | 1987.6 |
| Chain linked volumes (2005), million euro | Agriculture, forestry and fishing | Value added, gross | Albania | 2023 | 1951.3 |
| Chain linked volumes (2005), million euro | Agriculture, forestry and fishing | Value added, gross | Austria | 1995 | 2953.8 |
IE2 <- IE[, 4:8];
knitr::kable(head(IE2), caption= 'Variables empleadas IE');
| unit | na_item | geo | TIME_PERIOD | OBS_VALUE |
|---|---|---|---|---|
| Chain linked volumes (2005), million euro | Exports of goods and services | Albania | 2019 | 3678.6 |
| Chain linked volumes (2005), million euro | Exports of goods and services | Albania | 2020 | 2658.7 |
| Chain linked volumes (2005), million euro | Exports of goods and services | Albania | 2021 | 4043.8 |
| Chain linked volumes (2005), million euro | Exports of goods and services | Albania | 2022 | 4733 |
| Chain linked volumes (2005), million euro | Exports of goods and services | Albania | 2023 | 5180.3999999999996 |
| Chain linked volumes (2005), million euro | Exports of goods and services | Austria | 1995 | 63483.8 |
Describimos de qué tipo son las variables de cada base de datos
Lo mostramos en estas tablas:
| variable | tipo |
|---|---|
| unit | text |
| na_item | categorical |
| geo | categorical |
| TIME_PERIOD | numerical |
| OBS_VALUE | numerical |
| variable | tipo |
|---|---|
| unit | text |
| nace_r2 | categorical |
| na_item | text |
| geo | categorical |
| TIME_PERIOD | numerical |
| OBS_VALUE | numerical |
PIB3 <- PIB2[PIB2$unit %in% c('Current prices, million euro', 'Percentage of gross domestic product(GDP)','Percentage of total'),]
PIB3 <- PIB3[!PIB3$geo %in% c('Euro area - 12 countries (2001-2006)', 'Euro area - 19 countries (2015-2022)', 'Euro area - 20 countries (from 2023)','European Union - 27 countries (from 2020)', 'Euro area (EA11-1999, EA12-2001, EA13-2007, EA15-208, EA16-2009, EA17-2011, EA18-2014, EA19-2015, EA15-2023'),]
PIB3 <- PIB3[!PIB3$nace_r2 == 'Total - all NACE activities',]
IE3 <- IE2[IE2$unit=='Current prices, million euro', ]
IE3 <- IE3[IE3$na_item %in% c('Exports of goods and services', 'Imports of goods and services'), ]
Vamos a observar los valores faltantes de la base de datos IE por cada variable tanto en cantidad como en porcentaje sobre el total.
| Variable | numNA | percNA | |
|---|---|---|---|
| OBS_VALUE | OBS_VALUE | 320 | 0.44 |
Observamos que solo hay valores faltantes en la variable obs_value,
en concreto 320, que es un 0.44% sobre el total. Como la variable que
queremos estudiar es esta, no nos interesa mantener las observaciones
sobre las cuales no tenemos esa información, más adelante tras analizar
la base de datos PIB, eliminaremos aquellas observaciones en las que no
se tenga información en la variable OBS_VALUE.
Ahora vamos a observar los valores faltantes de la base de datos
PIB:
| Variable | numNA | percNA | |
|---|---|---|---|
| OBS_VALUE | OBS_VALUE | 6309 | 0.81 |
En esta base de datos encontramos 6309 casos faltantes únicamente en la variable OBS_VALUE, aunque pueda parecer una cantidad excesiva es únicamente el 0.81 % del total, como se repite la situación en la que es esta la variable que queremos estudiar, vamos a eliminar aquellas observaciones en las que no se tenga esta información.
Partiendo de que no nos interesan aquellas filas en las que falte aparezcan valores faltantes, debido a que la carencia de información en alguna de todas las variables, la observación no nos sirve. Se eliminan todas las filas en las que falte cualquier tipo de información.
PIB3 <- PIB3[!is.na(PIB3$OBS_VALUE),]
IE3 <- IE3[!is.na(IE3$OBS_VALUE),]
Se vuelve a cambiar de base de datos y ahora trataremos la que muestra los datos de exportación e importación de cada país. La utilizaremos para comprobar si el índice de libertad, y el PIB tiene relación con el nivel de importaciones y exportaciones.
Se empieza con la lectura de las bases de datos.
## [1] "EXPORT" "IMPORT"
Se empieza a borrar aquellas variables que tenemos claro que queremos descartar, que son: ‘comm_code’, ‘quantity_name’, ‘quantity’ y ‘flow’.
De la información otorgada por esta base de datos, solo nos informa de cada país por específico, por eso eliminamos los casos de ‘EU-28’, y el de la suma de todos las commodities ‘ALL COMMODITIES’.
# Filtrar COMEXP
COMEXP <- COMEXP[!(COMEXP$commodity == "ALL COMMODITIES" & COMEXP$country_or_area == "EU-28"), ];
COMIMP <- COMIMP[!(COMIMP$commodity == "ALL COMMODITIES" & COMIMP$country_or_area == "EU-28"), ];
• Comparar y analizar el impacto de la crisis financiera de 2008 y la pandemia de COVID-19 en los flujos de exportación e importación de diferentes países seleccionados de distintas zonas geográficas, evaluando la permanencia de los efectos, las diferencias en la recuperación del sector comercial, y los factores que influyeron en la velocidad y el patrón de recuperación de cada país.
library(dplyr)
library(ggplot2)
IE3 <- IE3 %>%
mutate(
OBS_VALUE = as.numeric(gsub(",", ".", gsub("[^0-9,\\.]", "", OBS_VALUE))),
TIME_PERIOD = as.numeric(TIME_PERIOD)
)
# Lista de países de la UE
paises_ue_lista <- 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")
# Detectar países con datos disponibles
paises_presentes <- IE3 %>%
filter(TIME_PERIOD %in% 2006:2012 | TIME_PERIOD %in% 2018:2023,
na_item %in% c("Exports of goods and services", "Imports of goods and services")) %>%
distinct(geo) %>%
pull(geo)
# Clasificación UE / No UE
paises_total <- data.frame(
geo = paises_presentes,
grupo = ifelse(paises_presentes %in% paises_ue_lista, "UE", "No UE")
)
# Filtrar y preparar datos
IE_crisis_pandemia <- IE3 %>%
filter(geo %in% paises_total$geo,
TIME_PERIOD %in% 2006:2012 | TIME_PERIOD %in% 2018:2023,
na_item %in% c("Exports of goods and services", "Imports of goods and services"))
datos_combinados <- IE_crisis_pandemia %>%
mutate(flujo = ifelse(na_item == "Exports of goods and services", "Exportaciones", "Importaciones")) %>%
left_join(paises_total, by = "geo")
datos_combinados$grupo <- factor(datos_combinados$grupo, levels = c("UE", "No UE"))
# --- GRÁFICO UE ---
grafico_ue <- datos_combinados %>%
filter(grupo == "UE") %>%
ggplot(aes(x = TIME_PERIOD, y = OBS_VALUE/1000, color = flujo)) +
geom_line(linewidth = 1.1) +
geom_vline(xintercept = 2008, linetype = "dashed", color = "red", linewidth = 0.8) +
geom_vline(xintercept = 2020, linetype = "dashed", color = "blue", linewidth = 0.8) +
facet_wrap(~geo, ncol = 3, scales = "free_y") +
labs(
title = "Exportaciones e importaciones (2006–2012 y 2018–2023)",
subtitle = "Países de la Unión Europea (líneas: 2008 y 2020)",
x = "Año", y = "Valor en miles de millones €",
color = "Tipo de flujo"
) +
scale_x_continuous(breaks = seq(2006, 2023, by = 2)) +
theme_minimal(base_size = 13) +
theme(
plot.title = element_text(size = 18, face = "bold"),
plot.subtitle = element_text(size = 14),
strip.text = element_text(size = 11, face = "bold"),
axis.text.x = element_text(angle = 45, hjust = 1)
)
# --- GRÁFICO No UE ---
grafico_no_ue <- datos_combinados %>%
filter(grupo == "No UE") %>%
ggplot(aes(x = TIME_PERIOD, y = OBS_VALUE/1000, color = flujo)) +
geom_line(linewidth = 1.1) +
geom_vline(xintercept = 2008, linetype = "dashed", color = "red", linewidth = 0.8) +
geom_vline(xintercept = 2020, linetype = "dashed", color = "blue", linewidth = 0.8) +
facet_wrap(~geo, ncol = 3, scales = "free_y") +
labs(
title = "Exportaciones e importaciones (2006–2012 y 2018–2023)",
subtitle = "Países fuera de la Unión Europea (líneas: 2008 y 2020)",
x = "Año", y = "Valor en miles de millones €",
color = "Tipo de flujo"
) +
scale_x_continuous(breaks = seq(2006, 2023, by = 2)) +
theme_minimal(base_size = 13) +
theme(
plot.title = element_text(size = 18, face = "bold"),
plot.subtitle = element_text(size = 14),
strip.text = element_text(size = 11, face = "bold"),
axis.text.x = element_text(angle = 45, hjust = 1)
)
# Mostrar
print(grafico_ue)
print(grafico_no_ue)
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|
# --- 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|
library(dplyr)
library(ggplot2)
library(tidyr)
graficar_top_categoria <- function(df, categorias,titulo) {
df %>%
select(any_of(categorias)) %>%
summarise(across(everything(), ~ sum(.x, na.rm = TRUE))) %>%
pivot_longer(everything(), names_to = "categoria", values_to = "valor_total") %>%
arrange(desc(valor_total)) %>%
ggplot(aes(x = reorder(categoria, valor_total), y = valor_total / 1e9)) +
geom_bar(stat = "identity", fill = "darkorange") +
coord_flip() +
labs(
title = titulo,
x = "Categoría",
y = "Valor total (miles de millones USD)"
) +
theme_minimal(base_size = 10)
}
prexp = pca_pre[[2]]
graficar_top_categoria(PRECRISIS_EXP, prexp, 'Exportaciones globales pre-crisis')
primp = pca_imp_pre[[2]]
graficar_top_categoria(PRECRISIS_IMP,primp, 'Importaciones globales pre-crisis')
crexp = pca_cri[[2]]
graficar_top_categoria(CRISIS_EXP, crexp, 'Exportaciones globales crisis')
crimp = pca_imp_cri[[2]]
graficar_top_categoria(CRISIS_IMP,crimp, 'Importaciones globales crisis')
postexp = pca_post[[2]]
graficar_top_categoria(POSTCRISIS_EXP, postexp, 'Exportaciones globales post-crisis')
postimp = pca_imp_post[[2]]
graficar_top_categoria(POSTCRISIS_IMP,postimp, 'Importaciones globales post-crisis')