rlistfunctionrstudiornoaa

Function in R to pull weather data based on Lat/Lon - RNOAA package


I am building a list with types of weather observations in R based on Latitude and Longitude that is similar to the weather station.

## List of airports you want to include in your weather extract

airport_list <- c("KABE" , "KBWI", "KRAL")

## Drilldown of your airport locations ( I have a separate table that pulls in this info

airport_list_dd <- airport_locs[airport_locs$icao %in% airport_list,]

## Mutate the data frame to make lat/lon compatible for searching the    NOAA GHCND 

airport_list_similar <- airport_list_dd %>%
  mutate(lon_similar = str_extract(longitude, "([-0-9]+)\\.."),
         lat_similar = str_extract(latitude, "([-0-9]+)\\.."),
         lon_exact = str_extract(longitude, "([-0-9]+)\\....."),
         lat_exact = str_extract(latitude, "([-0-9]+)\\....."))

## Define your date range

 date_min <- Sys.Date() - (10 * 365)
 date_max <- Sys.Date()
 filter_year <- year(Sys.Date()) - 1

# THIS IS WHERE I AM HAVING THE ISSUE
 ## Build your weather extracts
 ghcnd_near_airport <- list()
 build_lon_table <- function(x){
  i <- 1
  for (i in 1:length(x)) {
    lon_similar <- x$lon_similar[i]
    lat_similar <- x$lat_similar[i]
    ghcnd_near_airport <- c(ghcnd_stations %>%
                                filter(str_detect(longitude, lon_similar), str_detect(latitude, lat_similar)), list(i))
  }
  return(ghcnd_near_airport)
}

but this returns an empty list with a count of 11, which means that it is iterating through the function the appropriate amount of time, but is not returning any data in the list.


Solution

  • FOUND THE ANSWER:

    build_lon_table <- function(x){
      i <- 1
      ghcnd_near_airport_app <- data.frame(id = character(), latitude = numeric(), longitude = numeric(), elevation = numeric(), state = character(), name = character(), gsn_flag = character(), wmo_id = character(), element = character(),first_year = integer(), last_year = integer(), stringsAsFactors = FALSE)
      for (i in 1:nrow(x)) {
        ghcnd_near_airport_filter <- ghcnd_stations %>%
              filter(str_detect(longitude, x$lon_similar[i]), str_detect(latitude, x$lat_similar[i]), last_year >= filter_year, element == "TMIN"| element == "WT01") %>%
              mutate(lon_diff = abs(longitude - as.numeric(airport_list_similar$lon_exact[i])), lat_diff = abs(latitude - as.numeric(airport_list_similar$lat_exact[i])),    total_diff = lon_diff + lat_diff) %>%
              arrange(total_diff)
    
        ghcnd_near_airport_filter <- head(ghcnd_near_airport_filter, 2)
        ghcnd_near_airport_app <- rbind(ghcnd_near_airport_app, ghcnd_near_airport_filter)
        i <- i + 1
      }
      return(ghcnd_near_airport_app)
    }
    
    test <- build_lon_table(airport_list_similar)