DrMattG/SDGsR

Requesting indicator data for multiple countries with get_indicator() function

Opened this issue · 1 comments

Hey,

Thanks for your work putting this together.

I'm trying to download all available data for the same four countries. Unfortunately, there doesn't appear to be a simple way to do this on V1 of their API. But, it does appear to be possible to download data for more than one country at once with a relatively minor tweak of the get_indicator() function code.

In case it's helpful for your next update or others using the package:

fnc_get_indicator_n_geos<-function (Country, indicator) 
{
  country_string<-paste(Country,collapse = "&areaCode=")
   url <- paste0("https://unstats.un.org/sdgs/UNSDGAPIV5/v1/sdg/Indicator/Data?indicator=", 
                 indicator, "&areaCode=",country_string)
  datcall <- jsonlite::fromJSON(url)
  page <- as.data.frame(datcall$data)
  return(page)

}

Okay, as the approach above has to cycle through indicators it's not particularly efficient.

After going through their API "documentation" I managed to figure out a way to return a dataset for a series of countries and goals. This allowed me to achieve what I wanted in one fifth of the time. In case it's helpful for others I've included the code below.

This downloads all data for the specified SDGs (e.g. 1 to 17) and country area codes (M49 country codes). The data is in csv format so then just has to be converted to make it a dataframe or tibble.

library(httr)
  
  fnc_sdg_data_post <- function(goals, area_codes) {
    url <- "https://unstats.un.org/sdgs/UNSDGAPIV5/v1/sdg/Goal/DataCSV"
    
    body <- list()
    for (goal in goals) {
      body <- c(body, list(goal = goal))
    }
    for (code in area_codes) {
      body <- c(body, list(areaCodes = code))
    }
    
    response <- POST(
      url = url,
      body = body,
      encode = "multipart",
      add_headers("accept" = "text/plain"),
      content_type("multipart/form-data")
    )
    
    return(content(response, "text")) 
  }