GlobalFishingWatch / gfwr

R package for accessing data from Global Fishing Watch APIs
https://globalfishingwatch.github.io/gfwr/
Apache License 2.0
58 stars 7 forks source link

Allow `get_region_id` to take region ids as input #72

Closed natemiller closed 2 years ago

natemiller commented 2 years ago

The events API returns events that include region codes (for EEZs, etc.). There is currently no way to translate the codes back into the EEZ label. A quick modification to the get_region_id function should allow it to take in a EEZ or MPA code an return the corresponding label. See the code below for one implementation.

get_region_id <- function(region_name, region_source = "eez", key) {
  result <- get_endpoint(dataset_type = region_source) %>%
    httr2::req_headers(Authorization = paste("Bearer", key, sep = " ")) %>%
    httr2::req_user_agent("gfwr/1.0.0 (https://github.com/GlobalFishingWatch/gfwr)") %>%
    httr2::req_error(body = gist_error_body) %>%
    httr2::req_perform(.) %>%
    httr2::resp_body_json(.) %>%
    dplyr::bind_rows()

  # EEZ names
  if (region_source == "eez" & is.character(region_name)) {
    result %>%
      dplyr::filter(agrepl(region_name, .$label) | agrepl(paste0("^", region_name), .$iso3)) %>%
      dplyr::mutate(id = as.numeric(id))
  }
  # EEZ ids
  else if (region_source == "eez" & is.numeric(region_name)) {
    result %>%
      dplyr::filter(id == {{ region_name }})
  }
  # MPA names
  else if (region_source == "mpa" & is.character(region_name)) {
    result %>%
      dplyr::filter(agrepl(region_name, .$label)) %>%
      dplyr::mutate(id = as.numeric(id))
  }
  # MPA ids
  else if (region_source == "mpa" & is.numeric(region_name)) {
    result %>%
      dplyr::filter(id == {{ region_name }})
  } else {
    stop("Enter a valid region source")
  }
}
natemiller commented 2 years ago

Addressed by PR #75