R/rfca_cityweather_locations.R

Defines functions rfca_cityweather_locations

Documented in rfca_cityweather_locations

#' rfca_cityweather_locations
#' @description Used to retrieve identifying information for cities
#' covered by Environment Canada City weather forecasts.
#' @param prov (Optional) Filter results to only include a specific province.
#' Options are \itemize{
#' \item{AB - Alberta}
#' \item{BC - British Columbia}
#' \item{MB - Manitoba}
#' \item{NB - New Brunswick}
#' \item{NL - Newfoundland}
#' \item{NS - Nova Scotia}
#' \item{NT - North West Territories}
#' \item{NU - Nunavut}
#' \item{ON - Ontario}
#' \item{PE - Prince Edward Island}
#' \item{QC - Quebec}
#' \item{SK - Saskatchewan}
#' \item{YT - Yukon}}
#' @return Data frame containing
#' \item{site_name}{The name of the site, usually a city.}
#' \item{site_id}{The unique identifier to be passed to
#' \code{rfca_get_forecast()}}
#' \item{province}{Province short name}
#' @export

rfca_cityweather_locations <- function(prov) {
  # Station Information XML
  stn_info <- xml2::read_xml("https://dd.weather.gc.ca/citypage_weather/xml/siteList.xml")

  # Parse to data frame
  stn_info_ch <- xml2::xml_children(stn_info)

  stn_info_parsed <- lapply(stn_info_ch, function(x) {
    # Get station id from node
    site_id_node <- xml2::xml_attrs(x)
    site_id <- site_id_node[[1]]

    # Get station name and prov from children
    site_name <- xml2::xml_text(xml2::xml_child(x, "nameEn"))


    province <- xml2::xml_text(xml2::xml_child(x, "provinceCode"))

    data.frame(
      site_name,
      site_id,
      province,
      stringsAsFactors = FALSE
    )
  })
  stn_info_out <- do.call(rbind, stn_info_parsed)

  # Check for province filter
  if (!missing(prov)) {
    stn_info_out <- dplyr::filter(stn_info_out,
                                     province == prov)
  }

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