# - pedro.j.perez@uv.es [2024-04-09]
#- Acceder a datos del Banco Mundial ---------------------------------------------
#- API: https://datahelpdesk.worldbank.org/knowledgebase/topics/125589
#- documentación datos: https://databank.worldbank.org/home.aspx
#- hay 2 pkgs:  WDI (https://vincentarelbundock.github.io/WDI/index.html) y wbstats (https://github.com/gshs-ornl/wbstats)
#- slides de Bruno Thiago Tomio: https://bttomio.github.io/slides/WDI2021/Slides.html#1
#- Un book sobre la API del world bank: https://econandrew.github.io/wdi-api-R-gettingstarted/index.html

library(tidyverse)
library("WDI")  #- install.packages("WDI")

#---- buscamos datos relacionados con GDP
aa <- WDIsearch('gdp') %>% as_tibble()
aa <- WDIsearch('gdp.*capita.*constant') %>% as_tibble()
#---- descargamos "NY.GDP.PCAP.KD":  GDP per capita (constant 2010 US$)
df <- WDI(indicator = "NY.GDP.PCAP.KD")
#---- podemos filtrar la querry
df <- WDI(indicator = "NY.GDP.PCAP.KD", country = c('MX','CA','US'), start = 1960, end = 2017)


#- catalogo de datos
info <- WDI_data
df_paises <- as.data.frame(info$country)     #- paises
df_series <- as.data.frame(info$series)      #- series/indicadores
names(df_series)
zz <- as.data.frame(info$series) %>% filter(indicator == "NY.GDP.PCAP.KD")


#- un ejemplo ----------
# indicator = IT.NET.USER.ZS / name = Individuals using the Internet (% of population)
indicator <- c("Individuals using the Internet (% of population)" = 'IT.NET.USER.ZS')
datall <- WDI(indicator, country="all", end = 2019)
LATAM <- df_paises %>%
  filter(region == "Latin America & Caribbean") %>%
  select(country) %>%
  unlist()

datall %>%
  filter(country %in% LATAM) %>%
  ggplot(aes(year, `Individuals using the Internet (% of population)`)) + geom_line() +
  facet_wrap(vars(country), scales = "free_y")



#- con el pkg wbstats ----------------------------------------------------------
library("wbstats")  #- install.packages("wbstats")


#-------  lista de indicadores disponibles
aa <- wb_cachelist

#---- buscamos datos relacionados con GDP
aa <- wb_search(pattern = "gdp")  
aa <- wb_search('gdp.*capita.*constant')

#---- descargamos "NY.GDP.PCAP.KD":  GDP per capita (constant 2010 US$)
df <- wb_data(indicator = "NY.GDP.PCAP.KD")

#---- podemos filtrar la querry
df <- wb_data(indicator = "NY.GDP.PCAP.KD", country = c('MX','CA','US'), start_date = 2000, end_date = 2017)





