rrnoaa

Retrieving climate data on "rnoaa" package in R


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.


Solution

  • 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)