Created
January 13, 2023 12:54
-
-
Save sebastian-c/6765812df5c23c0b0466d991343dbc1e to your computer and use it in GitHub Desktop.
Function to pull data from FENIX API in FAOSTAT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(httr) | |
readFAOData <- function(area_codes, element_codes, item_codes, year_codes, | |
area_format = "M49", | |
item_format = "CPC", | |
dataset = "FBS", | |
metadata_cols = c("codes", "units", "flags", "notes"), | |
include_na = FALSE, | |
return_n_records_only = FALSE, | |
base_url = "https://fenixservices.fao.org/faostat/api/v1/en/data/"){ | |
coll <- function(string){ | |
paste0(string, collapse = ",") | |
} | |
area_coll = coll(area_codes) | |
item_coll = coll(item_codes) | |
element_coll = coll(element_codes) | |
year_coll = coll(year_codes) | |
params <- list( | |
area = area_coll, #These are FAO codes even if displayed in M49 | |
area_cs = area_format, | |
element = element_coll, | |
item = item_coll, #I think these are FAO codes too, but they _happen_ to match for CPC | |
item_cs = item_format, | |
year = year_coll, | |
show_codes = "codes" %in% metadata_cols, | |
show_unit = "units" %in% metadata_cols, | |
show_flags = "flags" %in% metadata_cols, | |
show_notes = "notes" %in% metadata_cols, | |
null_values = include_na, | |
no_records = return_n_records_only, # Used to only return the number of records | |
# page_number = 1, # For pagination | |
# page_size = 100, # Number of records for pagination | |
datasource = "DB4", | |
output_type = "objects" | |
) | |
resp <- GET(paste0(base_url, dataset), query = params) | |
if(status_code(resp) != 200){ | |
stop("Request failed") | |
} | |
resp_list <- content(resp) | |
ret <- lapply(resp_list$data, as.data.frame) | |
return(do.call(rbind, ret)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment