Skip to content

Instantly share code, notes, and snippets.

@adamhsparks
Last active October 17, 2023 02:46
Show Gist options
  • Save adamhsparks/646d8c4e610ba6915587634a65f95853 to your computer and use it in GitHub Desktop.
Save adamhsparks/646d8c4e610ba6915587634a65f95853 to your computer and use it in GitHub Desktop.
Given a list of named places, get a list of weather stations in R from {weatherOz} or capture the message if no stations were found
# Find stations in both the DPIRD and SILO weather station networks given a
# vector of locations or capture messages when no stations are found
library("tidygeocoder")
library("data.table")
library("weatherOz")
library("purrr")
# Step 1: Create a vector of named locations to geocode
locations <-
c(
"Badgingarra",
"Merredin",
"York"
)
# Step 2: Geocode using vector of named locations
loc_lonlat <-
rbindlist(Map(
geo,
city = locations,
state = "WA",
country = "AU"
))
# Step 3: Get the matching station codes and lat/lon values for each of the
# locations
#
# Step 3.1 Create a new function to handle a vector of lon/lat values
#
#' @param x a vector of longitude and latitude values in that order
find_nearby_stations2 <- function(x) {
return(
find_nearby_stations(
longitude = x[[1]],
latitude = x[[2]],
which_api = "all",
distance_km = 10,
api_key = Sys.getenv("DPIRD_API_KEY")
)
)
}
# Step 3.2: Wrap new function in `possibly()`
q_find_nearby_stations2 <- quietly(.f = find_nearby_stations2)
# Step 3.3: Use `purrr::map()` to iterate through the data
y <-
map(.f = q_find_nearby_stations2,
.x = split(loc_lonlat[, c(5, 4)], seq_len(nrow(loc_lonlat))))
# Step 3.4 Assign location names from vector to the names of the list of stations
names(y) <- locations
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment