rnoaa: fetch nearest parameter for a given date

climate
rnoaa
Tags: #<Tag:0x00007f6573ecd0a8> #<Tag:0x00007f6573eccf40>

#1

An rnoaa user brought up an issue (https://github.com/ropensci/rnoaa/issues/226) with the pkg, asking if there’s a way to request a certain parameter for a given date, at the closest station to a given location. So there’s three criteria there:

  • Parameter: e.g,. temperature
  • Date: e.g., 2017-07-21
  • Spatial location: e.g., lon 151.2070, lat -33.8675

There wasn’t a way to do this already in rnoaa. So I came up with an attempt at this:

library(rnoaa)
library(dplyr)
statenv <- new.env()
fetch_nearest_parameter <- function(latitude, longitude, date, element, radius = NULL, ...) {
  if (is.null(statenv$station_data)) {
    statenv$station_data <- rnoaa::ghcnd_stations()
  }
  lldf <- data.frame(id = 1, latitude = latitude, longitude = longitude)
  yr <- as.numeric(format(as.Date(date), "%Y"))
  xx <- rnoaa::meteo_nearby_stations(lat_lon_df = lldf, var = element, 
                              station_data = statenv$station_data, 
                              year_min = yr, year_max = yr + 1, radius = radius, ...)
  ns <- dplyr::bind_rows(xx)
  dat <- rnoaa::meteo_pull_monitors(ns$id, var = element, 
                             date_min = date, date_max = date)
  dplyr::left_join(dat, ns, by = "id")
}

The new.env() bit is so that if you run the function > 1, you don’t have to download the station list again (via ghcnd_stations()).

Example use:

fetch_nearest_parameter(latitude = -33.8675, longitude = 151.2070,
                        date = "2016-05-03", element = "TMAX", radius = 10)
# A tibble: 4 x 7
           id       date  tmax                           name latitude longitude  distance
        <chr>     <date> <dbl>                          <chr>    <dbl>     <dbl>     <dbl>
1 ASN00066062 2016-05-03   264      SYDNEY (OBSERVATORY HILL) -33.8607  151.2050 0.7783486
2 ASN00066196 2016-05-03   252 SYDNEY HARBOUR (WEDDING CAKE W -33.8414  151.2633 5.9540769
3 ASN00066037 2016-05-03   269             SYDNEY AIRPORT AMO -33.9465  151.1731 9.3248624
4 ASN00066194 2016-05-03   256      CANTERBURY RACECOURSE AWS -33.9057  151.1134 9.6276700


Anyone have thoughts? Modifications to the above, or an alternative way to do it?