A14 Base de Datos Comercio Exterior

Carga y procesamiento de Datos

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.2.1     ✔ readr     2.2.0
## ✔ forcats   1.0.1     ✔ stringr   1.6.0
## ✔ ggplot2   4.0.3     ✔ tibble    3.3.1
## ✔ lubridate 1.9.5     ✔ tidyr     1.3.2
## ✔ purrr     1.2.2     
## ── 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(countrycode)
library(kableExtra)
## 
## Adjuntando el paquete: 'kableExtra'
## 
## The following object is masked from 'package:dplyr':
## 
##     group_rows

1. Carga de Base de Datos Comercio Exterior.

load("C:/Users/laura/OneDrive/Documentos/MAE/comercio_exterior/comercio_exterior/data_comercio_exterior.RData")
data_comercio_exterior %>%
  head(10) %>%
  kable(caption = "Comercio Exterior (BCR) - primeros 10 casos")
Comercio Exterior (BCR) - primeros 10 casos
pais sac anio mes valor_cif kilogramos_importaciones valor_fob kilogramos_exportaciones
AFGANISTAN 8708990000 2022 2 220.50 0.29 0 0
AFGANISTAN 8471900000 2022 5 665.90 4.00 0 0
AFGANISTAN 5702310000 2022 6 913.74 22.02 0 0
AFGANISTAN 5702502000 2022 6 566.35 11.36 0 0
AFGANISTAN 6111200000 2022 8 213.69 1.56 0 0
AFGANISTAN 8536509000 2022 9 42.28 2.00 0 0
AFGANISTAN 6210400000 2023 7 204.75 0.10 0 0
AFGANISTAN 0901210000 2024 4 0.00 0.00 440 21
AFGANISTAN 4909000000 2024 4 0.07 0.15 0 0
AFGANISTAN 8473300000 2024 6 60.18 1.00 0 0

2. Información estandarizada.

data_iso <- data_comercio_exterior %>%
  mutate(
    iso_3 = countrycode(pais,               
                        origin = "country.name",
                        destination = "iso3c"),
    region = countrycode(pais,             
                          origin = "country.name",
                          destination = "region")
  )
## Warning: There were 4 warnings in `mutate()`.
## The first warning was:
## ℹ In argument: `iso_3 = countrycode(pais, origin = "country.name", destination
##   = "iso3c")`.
## Caused by warning:
## ! Some values were not matched unambiguously: AFGANISTAN, ALEMANIA, ANTILLAS HOLANDESAS, ARABIA SAUDITA, ARGELIA, BAHREIN, ISLA (EST.P.), BELGICA, BELICE, BRASIL, BUTAN, CAMBOYA, CAMERUN, CEILAN, CHIPRE, COSTA DE MARFIL, CROACIA, DINAMARCA, DJIBOUTI (EX-SOMALIA FRANC.), EGIPTO, EMIRATOS ARABES UNIDOS, ESLOVAQUIA, ESPANA, ESTADOS FEDERADOS DE MICRONESI, ESTADOS UNIDOS DE AMERICA, ETIOPIA, FEDERACION DE RUSIA, FILIPINAS, FRANCIA, GRANADA, GRECIA, GROENLANDIA, GUADALUPE, GUAM (USA), GUAYANA, GUINEA (ANTE. FRANCESA), HOLANDA, HUNGRIA, I.GEORGIA Y SANDWICH DEL SUR, IRLANDA, ISLA WAKE, ISLANDIA, ISLAS ALAND, ISLAS CAIMAN (R.U.), ISLAS FEROE, ISLAS NAVIDAD, ISLAS SALOMON, ISLAS STO. TOME Y PRIN., ISLAS VIRGENES BRITANICAS (R.U, ISLAS VIRGENES DE E.U.A., ITALIA, JAPON, KENIA, KIRGUISTAN -KIRGYSTAN, KOWEIT, LETONIA, LIBANO, LIBIA, LITUANIA, MALASIA, MALDIVAS, ISLAS (EST.PR), MARRUECOS, MARTINICA (FRA), MAURICIO, MONSERRAT, NIVE, ISLAS (R.U.), NORUEGA, NUEVA CALIDONIA (FRA.), NUEVA ZELANDIA, OTROS PAISES, PAPUA NUEVA GUINEA, PAQUISTAN, POLONIA, REINO UNIDO, REP. ARABE UNIDA (SIRIA), REPUBLICA CENTROAFRICANA, REPUBLICA CHECA, REPUBLICA DE COREA, REPUBLICA DOMINICANA, SAN BARTOLOME, SAN VICENTE Y LAS GRANADINAS, SANTA ELENA, SANTA SEDE, SINGAPUR, SUD-AFRICA, SUECIA, SUIZA, TAILANDIA, TIMOR ORIENTAL, TUNEZ, TURCAS Y CAICOS (R.U.), UCRANIA, YUGOESLAVIA -NUEVA ORGANIZACIO
## To fix unmatched values, please use the `custom_match` argument. If you think the default matching rules should be improved, please file an issue at https://github.com/vincentarelbundock/countrycode/issues
## ℹ Run `dplyr::last_dplyr_warnings()` to see the 3 remaining warnings.
head(data_iso,10)
## # A tibble: 10 × 10
##    pais       sac         anio   mes valor_cif kilogramos_importacio…¹ valor_fob
##    <chr>      <chr>      <dbl> <dbl>     <dbl>                   <dbl>     <dbl>
##  1 AFGANISTAN 8708990000  2022     2    220.                      0.29         0
##  2 AFGANISTAN 8471900000  2022     5    666.                      4            0
##  3 AFGANISTAN 5702310000  2022     6    914.                     22.0          0
##  4 AFGANISTAN 5702502000  2022     6    566.                     11.4          0
##  5 AFGANISTAN 6111200000  2022     8    214.                      1.56         0
##  6 AFGANISTAN 8536509000  2022     9     42.3                     2            0
##  7 AFGANISTAN 6210400000  2023     7    205.                      0.1          0
##  8 AFGANISTAN 0901210000  2024     4      0                       0          440
##  9 AFGANISTAN 4909000000  2024     4      0.07                    0.15         0
## 10 AFGANISTAN 8473300000  2024     6     60.2                     1            0
## # ℹ abbreviated name: ¹​kilogramos_importaciones
## # ℹ 3 more variables: kilogramos_exportaciones <dbl>, iso_3 <chr>, region <chr>

3 . Ranking anual, 5 principales socios.

ranking_top5 <- data_iso %>%
  group_by(anio, iso_3) %>%
  summarise(total_fob = sum(valor_fob, na.rm = TRUE), .groups = "drop_last") %>%
  mutate(percent = round((total_fob / sum(total_fob)) * 100, 1)) %>%
  slice_max(order_by = total_fob, n = 5) %>%
  mutate(
    rank = row_number(),
    celda = paste0(iso_3, " | ", percent)
  ) %>%
  select(anio, rank, celda) %>%
  pivot_wider(names_from = rank, values_from = celda)

# Presentación en formato de tabla
ranking_top5 %>%
  kbl(
    col.names = c("Año", "1", "2", "3", "4", "5"),
    caption = "Top 5 Socios comerciales, periodo 2022-2026, datos en porcentaje de las exportaciones totales.",
    align = "c"
  ) %>%
  kable_styling(bootstrap_options = c("striped", "hover", "condensed")) %>%
  footnote(
    general_title = "Fuente:",
    general = "Elaboración propia, con base en información del BCR.",
    footnote_as_chunk = TRUE
  )
Top 5 Socios comerciales, periodo 2022-2026, datos en porcentaje de las exportaciones totales.
Año 1 2 3 4 5
2022 NA | 46 GTM | 17.1 HND | 16.7 NIC | 7 CRI | 4.3
2023 NA | 42.6 GTM | 18.4 HND | 16.3 NIC | 7.8 CRI | 4.8
2024 NA | 40.5 GTM | 19.5 HND | 16.1 NIC | 8.9 CRI | 4.7
2025 NA | 40.2 GTM | 19.6 HND | 16.7 NIC | 9.1 CRI | 4.5
2026 NA | 40.6 GTM | 19.5 HND | 15.4 NIC | 8.7 CRI | 4.5
Fuente: Elaboración propia, con base en información del BCR.