1

我正在建立一个列表,其中包含基于纬度和经度的 R 中类似于气象站的天气观测类型。

## 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)
}

但这会返回一个计数为 11 的空列表,这意味着它会在适当的时间内迭代函数,但不会返回列表中的任何数据。

4

1 回答 1

1

找到答案:

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)
于 2018-09-13T20:11:33.350 回答