R/rfca_naefs_locations.R

Defines functions rfca_naefs_locations

Documented in rfca_naefs_locations

#' rfca_naefs_locations
#' @description Provides metadata for locations with NAEFS forecast available.
#' @param country (Optional)
#' @param province_state (Optional)
#' @return Data frame containing location name, province/state, country and the file path for retrieving data.
#' The location name can then be passed to \code{rfca_naefs_forecast()} to retrieve forecast.
#' @export
#'

rfca_naefs_locations <- function(country, province_state){
  # Check for country/province_state args
  if (missing(country) & missing(province_state)) {
    message(
      paste0(
        "No country or province_state specified. ",
        "Returning results for all jurisidictions."
      )
    )
  }

  # Location of XML metadata
  base_url <- "http://dd.weatheroffice.gc.ca/ensemble/doc/naefs/xml/locations.xml"

  # Read in metadata
  stn_raw <- xml2::read_xml(base_url)

  # Iterate through all locations
  stn_dat <- lapply(1:length(xml2::xml_children(stn_raw)), function(x) {
    current_child <- xml2::xml_children(stn_raw)[[x]]

    # Construct data frame
    data.frame(
      City = xml2::xml_attr(current_child, "description"),
      WMO_code = xml2::xml_text(xml2::xml_child(current_child, "station_code_wmo")),
      Latitude = xml2::xml_text(xml2::xml_child(current_child, "latitude")),
      Longitude = xml2::xml_text(xml2::xml_child(current_child, "longitude")),
      Altitude = xml2::xml_text(xml2::xml_child(current_child, "altitude")),
      Country = xml2::xml_attr(current_child, "pays_country"),
      Province_state = xml2::xml_attr(current_child, "province_state"),
      File_path = xml2::xml_attr(current_child, "file_desc"),
      stringsAsFactors = FALSE
    )
  })

  stn_dat <- do.call(rbind, stn_dat)

  # Filter for country/province_state
  if (!missing(country)) {
    stn_dat <- stn_dat %>%
      filter(Country == country)
  }

  if (!missing(province_state)) {
    stn_dat <- stn_dat %>%
      filter(Province_state == province_state)
  }


  # Return
  return(stn_dat)
}
rywhale/rforecastca documentation built on May 4, 2019, 7:38 a.m.