options(scipen=999)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(readxl)
load ("C:/Users/Eduardo User/Downloads/data_comercio_exterior.RData")
head(data_comercio_exterior,n=10)
nombre_archivo <- ("C:/Users/Eduardo User/Downloads/master_paises_iso.xlsx")
nombres_iso_paises <- read_excel(nombre_archivo)
## New names:
## • `codigo_pais` -> `codigo_pais...5`
## • `codigo_pais` -> `codigo_pais...6`
## • `` -> `...13`
data_comercio_exterior %>%
  left_join(nombres_iso_paises,
            by = c("pais" = "nom_pais_esp")) -> data_comercio_exterior_unida
head(data_comercio_exterior_unida, n=10)
anios_ranking<-2018:2020
data_comercio_exterior_unida %>% 
  filter(anio %in% anios_ranking) -> data_ranking

data_ranking %>% 
  group_by(anio,iso_3) %>% 
  summarise(total=sum(valor_fob)) %>% mutate(percent=round(prop.table(total)*100,2)) %>% 
  slice_max(n = 5,order_by = total) %>% 
  as.data.frame() %>% 
  group_by(anio) %>% 
  mutate(rank = row_number(),
         data=paste(iso_3,"|",percent,sep = "")) %>% 
  select(anio,data,rank) %>% as.data.frame() -> insumo_reporte
## `summarise()` has grouped output by 'anio'. You can override using the
## `.groups` argument.
print(insumo_reporte)
##    anio      data rank
## 1  2018 USA|44.07    1
## 2  2018 HND|15.34    2
## 3  2018 GTM|14.36    3
## 4  2018  NIC|6.87    4
## 5  2018  CRI|4.39    5
## 6  2019 USA|41.88    1
## 7  2019 GTM|15.95    2
## 8  2019 HND|15.91    3
## 9  2019  NIC|6.68    4
## 10 2019   CRI|4.5    5
## 11 2020 USA|35.73    1
## 12 2020  GTM|16.9    2
## 13 2020 HND|15.21    3
## 14 2020  NIC|7.65    4
## 15 2020  CRI|5.21    5
library(tidyr)
insumo_reporte %>% 
pivot_wider(names_from = rank,values_from = data)->mi_tabla
print(mi_tabla)
## # A tibble: 3 × 6
##    anio `1`       `2`       `3`       `4`      `5`     
##   <dbl> <chr>     <chr>     <chr>     <chr>    <chr>   
## 1  2018 USA|44.07 HND|15.34 GTM|14.36 NIC|6.87 CRI|4.39
## 2  2019 USA|41.88 GTM|15.95 HND|15.91 NIC|6.68 CRI|4.5 
## 3  2020 USA|35.73 GTM|16.9  HND|15.21 NIC|7.65 CRI|5.21
library(kableExtra)
## 
## Attaching package: 'kableExtra'
## The following object is masked from 'package:dplyr':
## 
##     group_rows
mi_tabla %>%
  kable(caption = paste("Top",5,"Socios Comerciales, periodo 2018-2022, datos en porcentajes",
    min(anios_ranking),"-",max(anios_ranking))) %>%
  add_footnote(label = "Elaboracion propia con base en datos del BCR")
Top 5 Socios Comerciales, periodo 2018-2022, datos en porcentajes 2018 - 2020
anio 1 2 3 4 5
2018 USA|44.07 HND|15.34 GTM|14.36 NIC|6.87 CRI|4.39
2019 USA|41.88 GTM|15.95 HND|15.91 NIC|6.68 CRI|4.5
2020 USA|35.73 GTM|16.9 HND|15.21 NIC|7.65 CRI|5.21

Note: aElaboracion propia con base en datos del BCR