1

I am trying to retrieve climate data for a specific station_ID on a specific date. My dataset contains both elements.

for(i in data$date){lapply(data$station_id[i],
                           ghcnd_search,
                           var = "PRCP", 
                           date_min = data$date[i],
                           date_max = data$date[i])}

I tried this but to no avail. I would be grateful if someone can help me out.

Dave2e
  • 22,192
  • 18
  • 42
  • 50
  • 2
    Please show a small reproducible example. I assume that you need only `for` loop or `lapply` – akrun Jun 24 '20 at 21:52
  • May be this works for you. `out <- vector('list', nrow(data)); for(i in seq_len(nrow(data))) out[[i]] <- ghcnd_search(stationid = data$station_id[i], var = "PRCP", date_min = data$date[i], date_max = data$date[i])` – akrun Jun 24 '20 at 22:54

1 Answers1

0

We can loop over the sequence of rows and then use that index to subset the values of 'date' and 'station_id'

library(rnoaa)
out <- vector('list', nrow(data))
for(i in seq_len(nrow(data))){
 out[[i]] <- ghcnd_search(stationid  = data$station_id[i], 
   var = "PRCP", date_min = data$date[i], date_max = data$date[i])
}

-output

out
#[[1]]
#[[1]]$prcp
# A tibble: 1 x 6
#  id           prcp date       mflag qflag sflag
#  <chr>       <int> <date>     <chr> <chr> <chr>
#1 AGE00147704    90 1920-01-01 " "   " "   E    


#[[2]]
#[[2]]$prcp
# A tibble: 1 x 6
#  id           prcp date       mflag qflag sflag
#  <chr>       <int> <date>     <chr> <chr> <chr>
#1 AGE00147704     0 1915-01-01 " "   " "   E    

or using Map

out1 <- Map(function(x, y) ghcnd_search(stationid = x, var = "PRCP",
         date_min = y, date_max= y), data$station_id, data$date)

data

data <- data.frame(station_id = c("AGE00147704", "AGE00147704"),
    date = c("1920-01-01", "1915-01-01"), stringsAsFactors = FALSE)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks for your quick response. I tried and getting this; Error in curl::curl_fetch_memory(x$url$url, handle = x$url$handle) : Timeout was reached: [ftp.ncdc.noaa.gov] server response timeout – user13794388 Jun 25 '20 at 23:29
  • @user13794388 you may need some `Sys.sleep` in between to avoid the error. anyway, I answered the question asked. thank you – akrun Jun 25 '20 at 23:30